Remove legacy parameter from add_string()
[vlc/asuraparaju-public.git] / modules / demux / live555.cpp
blob415cd57995d664f7584bde25c1add5ede9a3f15d
1 /*****************************************************************************
2 * live555.cpp : LIVE555 Streaming Media support.
3 *****************************************************************************
4 * Copyright (C) 2003-2007 the VideoLAN team
5 * $Id$
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * Derk-Jan Hartman <hartman at videolan. org>
9 * Derk-Jan Hartman <djhartman at m2x .dot. nl> for M2X
10 * Sébastien Escudier <sebastien-devel celeos eu>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
28 * Preamble
29 *****************************************************************************/
31 /* For inttypes.h
32 * Note: config.h may include inttypes.h, so make sure we define this option
33 * early enough. */
34 #define __STDC_CONSTANT_MACROS 1
36 #ifdef HAVE_CONFIG_H
37 # include "config.h"
38 #endif
40 #include <inttypes.h>
42 #include <vlc_common.h>
43 #include <vlc_plugin.h>
44 #include <vlc_input.h>
45 #include <vlc_demux.h>
46 #include <vlc_dialog.h>
47 #include <vlc_url.h>
48 #include <vlc_strings.h>
50 #include <iostream>
51 #include <limits.h>
52 #include <assert.h>
55 #if defined( WIN32 )
56 # include <winsock2.h>
57 #endif
59 #include <UsageEnvironment.hh>
60 #include <BasicUsageEnvironment.hh>
61 #include <GroupsockHelper.hh>
62 #include <liveMedia.hh>
64 extern "C" {
65 #include "../access/mms/asf.h" /* Who said ugly ? */
68 using namespace std;
70 /*****************************************************************************
71 * Module descriptor
72 *****************************************************************************/
73 static int Open ( vlc_object_t * );
74 static void Close( vlc_object_t * );
76 #define CACHING_TEXT N_("Caching value (ms)")
77 #define CACHING_LONGTEXT N_( \
78 "Allows you to modify the default caching value for RTSP streams. This " \
79 "value should be set in millisecond units." )
81 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
82 #define KASENNA_LONGTEXT N_( "Kasenna servers use an old and nonstandard " \
83 "dialect of RTSP. With this parameter VLC will try this dialect, but "\
84 "then it cannot connect to normal RTSP servers." )
86 #define WMSERVER_TEXT N_("WMServer RTSP dialect")
87 #define WMSERVER_LONGTEXT N_("WMServer uses an unstandard dialect " \
88 "of RTSP. Selecting this parameter will tell VLC to assume some " \
89 "options contrary to RFC 2326 guidelines.")
91 #define USER_TEXT N_("RTSP user name")
92 #define USER_LONGTEXT N_("Sets the username for the connection, " \
93 "if no username or password are set in the url.")
94 #define PASS_TEXT N_("RTSP password")
95 #define PASS_LONGTEXT N_("Sets the password for the connection, " \
96 "if no username or password are set in the url.")
98 vlc_module_begin ()
99 set_description( N_("RTP/RTSP/SDP demuxer (using Live555)" ) )
100 set_capability( "demux", 50 )
101 set_shortname( "RTP/RTSP")
102 set_callbacks( Open, Close )
103 add_shortcut( "live", "livedotcom" )
104 set_category( CAT_INPUT )
105 set_subcategory( SUBCAT_INPUT_DEMUX )
107 add_submodule ()
108 set_description( N_("RTSP/RTP access and demux") )
109 add_shortcut( "rtsp", "pnm", "sdp", "live", "livedotcom" )
110 set_capability( "access_demux", 0 )
111 set_callbacks( Open, Close )
112 add_bool( "rtsp-tcp", false, NULL,
113 N_("Use RTP over RTSP (TCP)"),
114 N_("Use RTP over RTSP (TCP)"), true )
115 change_safe()
116 add_integer( "rtp-client-port", -1, NULL,
117 N_("Client port"),
118 N_("Port to use for the RTP source of the session"), true )
119 add_bool( "rtsp-mcast", false, NULL,
120 N_("Force multicast RTP via RTSP"),
121 N_("Force multicast RTP via RTSP"), true )
122 change_safe()
123 add_bool( "rtsp-http", false, NULL,
124 N_("Tunnel RTSP and RTP over HTTP"),
125 N_("Tunnel RTSP and RTP over HTTP"), true )
126 change_safe()
127 add_integer( "rtsp-http-port", 80, NULL,
128 N_("HTTP tunnel port"),
129 N_("Port to use for tunneling the RTSP/RTP over HTTP."),
130 true )
131 add_integer("rtsp-caching", 4 * DEFAULT_PTS_DELAY / 1000, NULL,
132 CACHING_TEXT, CACHING_LONGTEXT, true )
133 change_safe()
134 add_bool( "rtsp-kasenna", false, NULL, KASENNA_TEXT,
135 KASENNA_LONGTEXT, true )
136 change_safe()
137 add_bool( "rtsp-wmserver", false, NULL, WMSERVER_TEXT,
138 WMSERVER_LONGTEXT, true)
139 change_safe()
140 add_string( "rtsp-user", NULL, USER_TEXT,
141 USER_LONGTEXT, true )
142 change_safe()
143 add_password( "rtsp-pwd", NULL, NULL, PASS_TEXT,
144 PASS_LONGTEXT, true )
145 change_safe()
146 vlc_module_end ()
149 /*****************************************************************************
150 * Local prototypes
151 *****************************************************************************/
153 typedef struct
155 demux_t *p_demux;
156 MediaSubsession *sub;
158 es_format_t fmt;
159 es_out_id_t *p_es;
161 bool b_muxed;
162 bool b_quicktime;
163 bool b_asf;
164 block_t *p_asf_block;
165 bool b_discard_trunc;
166 stream_t *p_out_muxed; /* for muxed stream */
168 uint8_t *p_buffer;
169 unsigned int i_buffer;
171 bool b_rtcp_sync;
172 char waiting;
173 int64_t i_pts;
174 float i_npt;
176 } live_track_t;
178 struct timeout_thread_t
180 demux_sys_t *p_sys;
181 vlc_thread_t handle;
182 bool b_handle_keep_alive;
185 class RTSPClientVlc;
187 struct demux_sys_t
189 char *p_sdp; /* XXX mallocated */
190 char *psz_path; /* URL-encoded path */
191 vlc_url_t url;
193 MediaSession *ms;
194 TaskScheduler *scheduler;
195 UsageEnvironment *env ;
196 RTSPClientVlc *rtsp;
198 /* */
199 int i_track;
200 live_track_t **track; /* XXX mallocated */
202 /* Weird formats */
203 asf_header_t asfh;
204 stream_t *p_out_asf;
205 bool b_real;
207 /* */
208 int64_t i_pcr; /* The clock */
209 float i_npt;
210 float i_npt_length;
211 float i_npt_start;
213 /* timeout thread information */
214 int i_timeout; /* session timeout value in seconds */
215 bool b_timeout_call;/* mark to send an RTSP call to prevent server timeout */
216 timeout_thread_t *p_timeout; /* the actual thread that makes sure we don't timeout */
218 /* */
219 bool b_force_mcast;
220 bool b_multicast; /* if one of the tracks is multicasted */
221 bool b_no_data; /* if we never received any data */
222 int i_no_data_ti; /* consecutive number of TaskInterrupt */
224 char event;
226 bool b_get_param; /* Does the server support GET_PARAMETER */
227 bool b_paused; /* Are we paused? */
228 bool b_error;
229 int i_live555_ret; /* live555 callback return code */
231 float f_seek_request;/* In case we receive a seek request while paused*/
235 class RTSPClientVlc : public RTSPClient
237 public:
238 RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
239 char const* applicationName, portNumBits tunnelOverHTTPPortNum,
240 demux_sys_t *p_sys) :
241 RTSPClient( env, rtspURL, verbosityLevel, applicationName,
242 tunnelOverHTTPPortNum )
244 this->p_sys = p_sys;
246 demux_sys_t *p_sys;
249 static int Demux ( demux_t * );
250 static int Control( demux_t *, int, va_list );
252 static int Connect ( demux_t * );
253 static int SessionsSetup( demux_t * );
254 static int Play ( demux_t *);
255 static int ParseASF ( demux_t * );
256 static int RollOverTcp ( demux_t * );
258 static void StreamRead ( void *, unsigned int, unsigned int,
259 struct timeval, unsigned int );
260 static void StreamClose ( void * );
261 static void TaskInterrupt( void * );
263 static void* TimeoutPrevention( void * );
265 static unsigned char* parseH264ConfigStr( char const* configStr,
266 unsigned int& configSize );
268 /*****************************************************************************
269 * DemuxOpen:
270 *****************************************************************************/
271 static int Open ( vlc_object_t *p_this )
273 demux_t *p_demux = (demux_t*)p_this;
274 demux_sys_t *p_sys = NULL;
276 int i_return;
277 int i_error = VLC_EGENERIC;
279 if( p_demux->s )
281 /* See if it looks like a SDP
282 v, o, s fields are mandatory and in this order */
283 const uint8_t *p_peek;
284 if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
286 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
287 memcmp( p_peek, "v=0\n", 4 ) &&
288 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
290 return VLC_EGENERIC;
293 var_Create( p_demux, "rtsp-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
295 p_demux->pf_demux = Demux;
296 p_demux->pf_control= Control;
297 p_demux->p_sys = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
298 if( !p_sys ) return VLC_ENOMEM;
300 p_sys->p_sdp = NULL;
301 p_sys->scheduler = NULL;
302 p_sys->env = NULL;
303 p_sys->ms = NULL;
304 p_sys->rtsp = NULL;
305 p_sys->i_track = 0;
306 p_sys->track = NULL;
307 p_sys->i_pcr = 0;
308 p_sys->i_npt = 0.;
309 p_sys->i_npt_start = 0.;
310 p_sys->i_npt_length = 0.;
311 p_sys->p_out_asf = NULL;
312 p_sys->b_no_data = true;
313 p_sys->i_no_data_ti = 0;
314 p_sys->p_timeout = NULL;
315 p_sys->i_timeout = 0;
316 p_sys->b_timeout_call = false;
317 p_sys->b_multicast = false;
318 p_sys->b_real = false;
319 p_sys->psz_path = strdup( p_demux->psz_location );
320 p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
321 p_sys->b_get_param = false;
322 p_sys->b_paused = false;
323 p_sys->f_seek_request = -1;
324 p_sys->b_error = false;
325 p_sys->i_live555_ret = 0;
327 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
328 vlc_UrlParse( &p_sys->url, p_sys->psz_path, 0 );
330 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
332 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
333 goto error;
335 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
337 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
338 goto error;
341 if( strcasecmp( p_demux->psz_access, "sdp" ) )
343 char *p = p_sys->psz_path;
344 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
347 if( p_demux->s != NULL )
349 /* Gather the complete sdp file */
350 int i_sdp = 0;
351 int i_sdp_max = 1000;
352 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
354 if( !p_sdp )
356 i_error = VLC_ENOMEM;
357 goto error;
360 for( ;; )
362 int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
363 i_sdp_max - i_sdp - 1 );
365 if( !vlc_object_alive (p_demux) )
367 free( p_sdp );
368 goto error;
371 if( i_read < 0 )
373 msg_Err( p_demux, "failed to read SDP" );
374 free( p_sdp );
375 goto error;
378 i_sdp += i_read;
380 if( i_read < i_sdp_max - i_sdp - 1 )
382 p_sdp[i_sdp] = '\0';
383 break;
386 i_sdp_max += 1000;
387 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
389 p_sys->p_sdp = (char*)p_sdp;
391 else if( ( p_demux->s == NULL ) &&
392 !strcasecmp( p_demux->psz_access, "sdp" ) )
394 /* sdp:// link from SAP */
395 p_sys->p_sdp = strdup( p_sys->psz_path );
397 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
399 msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
400 goto error;
403 if( p_sys->p_sdp == NULL )
405 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
406 i_error = VLC_ENOMEM;
407 goto error;
410 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
412 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
413 goto error;
416 if( p_sys->b_real ) goto error;
418 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
419 goto error;
421 if( p_sys->p_out_asf && ParseASF( p_demux ) )
423 msg_Err( p_demux, "cannot find a usable asf header" );
424 /* TODO Clean tracks */
425 goto error;
428 if( p_sys->i_track <= 0 )
429 goto error;
431 return VLC_SUCCESS;
433 error:
434 Close( p_this );
435 return i_error;
438 /*****************************************************************************
439 * DemuxClose:
440 *****************************************************************************/
441 static void Close( vlc_object_t *p_this )
443 demux_t *p_demux = (demux_t*)p_this;
444 demux_sys_t *p_sys = p_demux->p_sys;
446 if( p_sys->p_timeout )
448 vlc_cancel( p_sys->p_timeout->handle );
449 vlc_join( p_sys->p_timeout->handle, NULL );
450 free( p_sys->p_timeout );
453 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
454 if( p_sys->ms ) Medium::close( p_sys->ms );
455 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
456 if( p_sys->env ) p_sys->env->reclaim();
458 for( int i = 0; i < p_sys->i_track; i++ )
460 live_track_t *tk = p_sys->track[i];
462 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
463 es_format_Clean( &tk->fmt );
464 free( tk->p_buffer );
465 free( tk );
468 if( p_sys->i_track ) free( p_sys->track );
469 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
470 delete p_sys->scheduler;
471 free( p_sys->p_sdp );
472 free( p_sys->psz_path );
474 vlc_UrlClean( &p_sys->url );
476 free( p_sys );
479 static inline const char *strempty( const char *s ) { return s?s:""; }
480 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
482 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
484 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
485 demux_sys_t *p_sys = client_vlc->p_sys;
486 delete []result_string;
487 p_sys->i_live555_ret = result_code;
488 p_sys->b_error = p_sys->i_live555_ret != 0;
489 p_sys->event = 1;
492 /* return true if the RTSP command succeeded */
493 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
495 TaskToken task;
496 demux_sys_t * p_sys = p_demux->p_sys;
497 p_sys->event = 0;
498 if( i_timeout > 0 )
500 /* Create a task that will be called if we wait more than timeout ms */
501 task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000, TaskInterrupt,
502 p_demux );
504 p_sys->event = 0;
505 p_sys->b_error = true;
506 p_sys->i_live555_ret = 0;
507 p_sys->scheduler->doEventLoop( &p_sys->event );
508 //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
509 if( i_timeout > 0 )
511 /* remove the task */
512 p_sys->scheduler->unscheduleDelayedTask( task );
514 return !p_sys->b_error;
517 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
518 char* result_string )
520 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
521 demux_sys_t *p_sys = client_vlc->p_sys;
522 p_sys->i_live555_ret = result_code;
523 if ( result_code == 0 )
525 char* sdpDescription = result_string;
526 free( p_sys->p_sdp );
527 p_sys->p_sdp = NULL;
528 if( sdpDescription )
530 p_sys->p_sdp = strdup( sdpDescription );
531 p_sys->b_error = false;
534 else
535 p_sys->b_error = true;
536 delete[] result_string;
537 p_sys->event = 1;
540 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
541 char* result_string )
543 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
544 demux_sys_t *p_sys = client_vlc->p_sys;
545 p_sys->i_live555_ret = result_code;
546 if ( result_code != 0 )
548 p_sys->b_error = true;
549 p_sys->event = 1;
551 else
553 p_sys->b_get_param = (bool)strstr( result_string, "GET_PARAMETER" );
554 client->sendDescribeCommand( continueAfterDESCRIBE );
556 delete[] result_string;
559 /*****************************************************************************
560 * Connect: connects to the RTSP server to setup the session DESCRIBE
561 *****************************************************************************/
562 static int Connect( demux_t *p_demux )
564 demux_sys_t *p_sys = p_demux->p_sys;
565 Authenticator authenticator;
566 char *psz_user = NULL;
567 char *psz_pwd = NULL;
568 char *psz_url = NULL;
569 char *psz_options = NULL;
570 char *p_sdp = NULL;
571 int i_http_port = 0;
572 int i_ret = VLC_SUCCESS;
573 const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
575 /* Get the user name and password */
576 if( p_sys->url.psz_username || p_sys->url.psz_password )
578 /* Create the URL by stripping away the username/password part */
579 if( p_sys->url.i_port == 0 )
580 p_sys->url.i_port = 554;
581 if( asprintf( &psz_url, "rtsp://%s:%d%s",
582 strempty( p_sys->url.psz_host ),
583 p_sys->url.i_port,
584 strempty( p_sys->url.psz_path ) ) == -1 )
585 return VLC_ENOMEM;
587 psz_user = strdup( strempty( p_sys->url.psz_username ) );
588 psz_pwd = strdup( strempty( p_sys->url.psz_password ) );
590 else
592 if( asprintf( &psz_url, "rtsp://%s", p_sys->psz_path ) == -1 )
593 return VLC_ENOMEM;
595 psz_user = var_InheritString( p_demux, "rtsp-user" );
596 psz_pwd = var_InheritString( p_demux, "rtsp-pwd" );
599 createnew:
600 if( !vlc_object_alive (p_demux) )
602 i_ret = VLC_EGENERIC;
603 goto bailout;
606 if( var_InheritBool( p_demux, "rtsp-http" ) )
607 i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
609 p_sys->rtsp = new RTSPClientVlc( *p_sys->env, psz_url,
610 var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
611 "LibVLC/"VERSION, i_http_port, p_sys );
612 if( !p_sys->rtsp )
614 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
615 p_sys->env->getResultMsg() );
616 i_ret = VLC_EGENERIC;
617 goto bailout;
620 /* Kasenna enables KeepAlive by analysing the User-Agent string.
621 * Appending _KA to the string should be enough to enable this feature,
622 * however, there is a bug where the _KA doesn't get parsed from the
623 * default User-Agent as created by VLC/Live555 code. This is probably due
624 * to spaces in the string or the string being too long. Here we override
625 * the default string with a more compact version.
627 if( var_InheritBool( p_demux, "rtsp-kasenna" ))
629 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
632 describe:
633 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
635 p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
637 if( !wait_Live555_response( p_demux, i_timeout ) )
639 int i_code = p_sys->i_live555_ret;
640 if( i_code == 401 )
642 msg_Dbg( p_demux, "authentication failed" );
644 free( psz_user );
645 free( psz_pwd );
646 dialog_Login( p_demux, &psz_user, &psz_pwd,
647 _("RTSP authentication"), "%s",
648 _("Please enter a valid login name and a password.") );
649 if( psz_user != NULL && psz_pwd != NULL )
651 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
652 goto describe;
655 else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
657 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
658 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
659 var_SetBool( p_demux, "rtsp-http", true );
660 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
661 p_sys->rtsp = NULL;
662 goto createnew;
664 else
666 if( i_code == 0 )
667 msg_Dbg( p_demux, "connection timeout" );
668 else
669 msg_Dbg( p_demux, "connection error %d", i_code );
670 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
671 p_sys->rtsp = NULL;
673 i_ret = VLC_EGENERIC;
676 bailout:
677 /* malloc-ated copy */
678 free( psz_url );
679 free( psz_user );
680 free( psz_pwd );
682 return i_ret;
685 /*****************************************************************************
686 * SessionsSetup: prepares the subsessions and does the SETUP
687 *****************************************************************************/
688 static int SessionsSetup( demux_t *p_demux )
690 demux_sys_t *p_sys = p_demux->p_sys;
691 MediaSubsessionIterator *iter = NULL;
692 MediaSubsession *sub = NULL;
694 bool b_rtsp_tcp = false;
695 int i_client_port;
696 int i_return = VLC_SUCCESS;
697 unsigned int i_buffer = 0;
698 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
700 b_rtsp_tcp = var_InheritBool( p_demux, "rtsp-tcp" ) ||
701 var_InheritBool( p_demux, "rtsp-http" );
702 i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
704 /* Create the session from the SDP */
705 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
707 msg_Err( p_demux, "Could not create the RTSP Session: %s",
708 p_sys->env->getResultMsg() );
709 return VLC_EGENERIC;
712 /* Initialise each media subsession */
713 iter = new MediaSubsessionIterator( *p_sys->ms );
714 while( ( sub = iter->next() ) != NULL )
716 Boolean bInit;
717 live_track_t *tk;
719 if( !vlc_object_alive (p_demux) )
721 delete iter;
722 return VLC_EGENERIC;
725 /* Value taken from mplayer */
726 if( !strcmp( sub->mediumName(), "audio" ) )
727 i_buffer = 100000;
728 else if( !strcmp( sub->mediumName(), "video" ) )
729 i_buffer = 2000000;
730 else if( !strcmp( sub->mediumName(), "text" ) )
732 else continue;
734 if( i_client_port != -1 )
736 sub->setClientPortNum( i_client_port );
737 i_client_port += 2;
740 if( strcasestr( sub->codecName(), "REAL" ) )
742 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
743 p_sys->b_real = true; /* This is a problem, we'll handle it later */
744 continue;
747 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
748 bInit = sub->initiate( 0 );
749 else
750 bInit = sub->initiate();
752 if( !bInit )
754 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
755 sub->mediumName(), sub->codecName(),
756 p_sys->env->getResultMsg() );
758 else
760 if( sub->rtpSource() != NULL )
762 int fd = sub->rtpSource()->RTPgs()->socketNum();
764 /* Increase the buffer size */
765 if( i_buffer > 0 )
766 increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
768 /* Increase the RTP reorder timebuffer just a bit */
769 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
771 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
772 sub->codecName() );
774 /* Issue the SETUP */
775 if( p_sys->rtsp )
777 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
778 toBool( b_rtsp_tcp ),
779 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
780 if( !wait_Live555_response( p_demux ) )
782 /* if we get an unsupported transport error, toggle TCP
783 * use and try again */
784 if( p_sys->i_live555_ret == 461 )
785 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
786 toBool( b_rtsp_tcp ), False );
787 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
789 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
790 sub->mediumName(), sub->codecName(),
791 p_sys->env->getResultMsg() );
792 continue;
797 /* Check if we will receive data from this subsession for
798 * this track */
799 if( sub->readSource() == NULL ) continue;
800 if( !p_sys->b_multicast )
802 /* We need different rollover behaviour for multicast */
803 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
806 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
807 if( !tk )
809 delete iter;
810 return VLC_ENOMEM;
812 tk->p_demux = p_demux;
813 tk->sub = sub;
814 tk->p_es = NULL;
815 tk->b_quicktime = false;
816 tk->b_asf = false;
817 tk->p_asf_block = NULL;
818 tk->b_muxed = false;
819 tk->b_discard_trunc = false;
820 tk->p_out_muxed = NULL;
821 tk->waiting = 0;
822 tk->b_rtcp_sync = false;
823 tk->i_pts = VLC_TS_INVALID;
824 tk->i_npt = 0.;
825 tk->i_buffer = 65536;
826 tk->p_buffer = (uint8_t *)malloc( 65536 );
827 if( !tk->p_buffer )
829 free( tk );
830 delete iter;
831 return VLC_ENOMEM;
834 /* Value taken from mplayer */
835 if( !strcmp( sub->mediumName(), "audio" ) )
837 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
838 tk->fmt.audio.i_channels = sub->numChannels();
839 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
841 if( !strcmp( sub->codecName(), "MPA" ) ||
842 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
843 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
845 tk->fmt.i_codec = VLC_CODEC_MPGA;
846 tk->fmt.audio.i_rate = 0;
848 else if( !strcmp( sub->codecName(), "AC3" ) )
850 tk->fmt.i_codec = VLC_CODEC_A52;
851 tk->fmt.audio.i_rate = 0;
853 else if( !strcmp( sub->codecName(), "L16" ) )
855 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
856 tk->fmt.audio.i_bitspersample = 16;
858 else if( !strcmp( sub->codecName(), "L8" ) )
860 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
861 tk->fmt.audio.i_bitspersample = 8;
863 else if( !strcmp( sub->codecName(), "PCMU" ) )
865 tk->fmt.i_codec = VLC_CODEC_MULAW;
867 else if( !strcmp( sub->codecName(), "PCMA" ) )
869 tk->fmt.i_codec = VLC_CODEC_ALAW;
871 else if( !strncmp( sub->codecName(), "G726", 4 ) )
873 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
874 tk->fmt.audio.i_rate = 8000;
875 tk->fmt.audio.i_channels = 1;
876 if( !strcmp( sub->codecName()+5, "40" ) )
877 tk->fmt.i_bitrate = 40000;
878 else if( !strcmp( sub->codecName()+5, "32" ) )
879 tk->fmt.i_bitrate = 32000;
880 else if( !strcmp( sub->codecName()+5, "24" ) )
881 tk->fmt.i_bitrate = 24000;
882 else if( !strcmp( sub->codecName()+5, "16" ) )
883 tk->fmt.i_bitrate = 16000;
885 else if( !strcmp( sub->codecName(), "AMR" ) )
887 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
889 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
891 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
893 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
895 unsigned int i_extra;
896 uint8_t *p_extra;
898 tk->fmt.i_codec = VLC_CODEC_MP4A;
900 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
901 i_extra ) ) )
903 tk->fmt.i_extra = i_extra;
904 tk->fmt.p_extra = xmalloc( i_extra );
905 memcpy( tk->fmt.p_extra, p_extra, i_extra );
906 delete[] p_extra;
908 /* Because the "faad" decoder does not handle the LATM
909 * data length field at the start of each returned LATM
910 * frame, tell the RTP source to omit it. */
911 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
913 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
915 unsigned int i_extra;
916 uint8_t *p_extra;
918 tk->fmt.i_codec = VLC_CODEC_MP4A;
920 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
921 i_extra ) ) )
923 tk->fmt.i_extra = i_extra;
924 tk->fmt.p_extra = xmalloc( i_extra );
925 memcpy( tk->fmt.p_extra, p_extra, i_extra );
926 delete[] p_extra;
929 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
931 tk->b_asf = true;
932 if( p_sys->p_out_asf == NULL )
933 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
934 p_demux->out );
936 else if( !strcmp( sub->codecName(), "X-QT" ) ||
937 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
939 tk->b_quicktime = true;
941 else if( !strcmp( sub->codecName(), "SPEEX" ) )
943 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
944 if ( sub->rtpTimestampFrequency() )
945 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
946 else
948 msg_Warn( p_demux,"Using 8kHz as default sample rate." );
949 tk->fmt.audio.i_rate = 8000;
953 else if( !strcmp( sub->mediumName(), "video" ) )
955 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
956 if( !strcmp( sub->codecName(), "MPV" ) )
958 tk->fmt.i_codec = VLC_CODEC_MPGV;
959 tk->fmt.b_packetized = false;
961 else if( !strcmp( sub->codecName(), "H263" ) ||
962 !strcmp( sub->codecName(), "H263-1998" ) ||
963 !strcmp( sub->codecName(), "H263-2000" ) )
965 tk->fmt.i_codec = VLC_CODEC_H263;
967 else if( !strcmp( sub->codecName(), "H261" ) )
969 tk->fmt.i_codec = VLC_CODEC_H261;
971 else if( !strcmp( sub->codecName(), "H264" ) )
973 unsigned int i_extra = 0;
974 uint8_t *p_extra = NULL;
976 tk->fmt.i_codec = VLC_CODEC_H264;
977 tk->fmt.b_packetized = false;
979 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
980 i_extra ) ) )
982 tk->fmt.i_extra = i_extra;
983 tk->fmt.p_extra = xmalloc( i_extra );
984 memcpy( tk->fmt.p_extra, p_extra, i_extra );
986 delete[] p_extra;
989 else if( !strcmp( sub->codecName(), "JPEG" ) )
991 tk->fmt.i_codec = VLC_CODEC_MJPG;
993 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
995 unsigned int i_extra;
996 uint8_t *p_extra;
998 tk->fmt.i_codec = VLC_CODEC_MP4V;
1000 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1001 i_extra ) ) )
1003 tk->fmt.i_extra = i_extra;
1004 tk->fmt.p_extra = xmalloc( i_extra );
1005 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1006 delete[] p_extra;
1009 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1010 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1011 !strcmp( sub->codecName(), "X-QDM" ) ||
1012 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1013 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1015 tk->b_quicktime = true;
1017 else if( !strcmp( sub->codecName(), "MP2T" ) )
1019 tk->b_muxed = true;
1020 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
1022 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1023 !strcmp( sub->codecName(), "MP1S" ) )
1025 tk->b_muxed = true;
1026 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
1027 p_demux->out );
1029 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1031 tk->b_asf = true;
1032 if( p_sys->p_out_asf == NULL )
1033 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
1034 p_demux->out );;
1036 else if( !strcmp( sub->codecName(), "DV" ) )
1038 tk->b_muxed = true;
1039 tk->b_discard_trunc = true;
1040 tk->p_out_muxed = stream_DemuxNew( p_demux, "rawdv",
1041 p_demux->out );
1044 else if( !strcmp( sub->mediumName(), "text" ) )
1046 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1048 if( !strcmp( sub->codecName(), "T140" ) )
1050 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1054 if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
1056 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1059 if( sub->rtcpInstance() != NULL )
1061 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1064 if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
1066 /* Append */
1067 p_sys->track = (live_track_t**)xrealloc( p_sys->track,
1068 sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
1069 p_sys->track[p_sys->i_track++] = tk;
1071 else
1073 /* BUG ??? */
1074 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1075 es_format_Clean( &tk->fmt );
1076 free( tk );
1080 delete iter;
1081 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1083 /* Retrieve the starttime if possible */
1084 p_sys->i_npt_start = p_sys->ms->playStartTime();
1086 /* Retrieve the duration if possible */
1087 p_sys->i_npt_length = p_sys->ms->playEndTime();
1089 /* */
1090 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1092 /* */
1093 p_sys->b_no_data = true;
1094 p_sys->i_no_data_ti = 0;
1096 return i_return;
1099 /*****************************************************************************
1100 * Play: starts the actual playback of the stream
1101 *****************************************************************************/
1102 static int Play( demux_t *p_demux )
1104 demux_sys_t *p_sys = p_demux->p_sys;
1106 if( p_sys->rtsp )
1108 /* The PLAY */
1109 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->i_npt_start, -1, 1 );
1111 if( !wait_Live555_response(p_demux) )
1113 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1114 return VLC_EGENERIC;
1117 /* Retrieve the timeout value and set up a timeout prevention thread */
1118 p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
1119 if( p_sys->i_timeout <= 0 )
1120 p_sys->i_timeout = 60; /* default value from RFC2326 */
1122 /* start timeout-thread only if GET_PARAMETER is supported by the server */
1123 if( !p_sys->p_timeout && p_sys->b_get_param )
1125 msg_Dbg( p_demux, "We have a timeout of %d seconds", p_sys->i_timeout );
1126 p_sys->p_timeout = (timeout_thread_t *)malloc( sizeof(timeout_thread_t) );
1127 if( p_sys->p_timeout )
1129 memset( p_sys->p_timeout, 0, sizeof(timeout_thread_t) );
1130 p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
1131 if( vlc_clone( &p_sys->p_timeout->handle, TimeoutPrevention,
1132 p_sys->p_timeout, VLC_THREAD_PRIORITY_LOW ) )
1134 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1135 free( p_sys->p_timeout );
1136 p_sys->p_timeout = NULL;
1138 else
1139 msg_Dbg( p_demux, "spawned timeout thread" );
1141 else
1142 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1145 p_sys->i_pcr = 0;
1147 /* Retrieve the starttime if possible */
1148 p_sys->i_npt_start = p_sys->ms->playStartTime();
1149 if( p_sys->ms->playEndTime() > 0 )
1150 p_sys->i_npt_length = p_sys->ms->playEndTime();
1152 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1153 return VLC_SUCCESS;
1157 /*****************************************************************************
1158 * Demux:
1159 *****************************************************************************/
1160 static int Demux( demux_t *p_demux )
1162 demux_sys_t *p_sys = p_demux->p_sys;
1163 TaskToken task;
1165 bool b_send_pcr = true;
1166 int64_t i_pcr = 0;
1167 int i;
1169 /* Check if we need to send the server a Keep-A-Live signal */
1170 if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
1172 char *psz_bye = NULL;
1173 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms, NULL, psz_bye );
1174 p_sys->b_timeout_call = false;
1177 for( i = 0; i < p_sys->i_track; i++ )
1179 live_track_t *tk = p_sys->track[i];
1181 if( tk->b_asf || tk->b_muxed )
1182 b_send_pcr = false;
1183 #if 0
1184 if( i_pcr == 0 )
1186 i_pcr = tk->i_pts;
1188 else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
1190 i_pcr = tk->i_pts ;
1192 #endif
1194 if( p_sys->i_pcr > 0 )
1196 if( b_send_pcr )
1197 es_out_Control( p_demux->out, ES_OUT_SET_PCR, 1 + p_sys->i_pcr );
1200 /* First warn we want to read data */
1201 p_sys->event = 0;
1202 for( i = 0; i < p_sys->i_track; i++ )
1204 live_track_t *tk = p_sys->track[i];
1206 if( tk->waiting == 0 )
1208 tk->waiting = 1;
1209 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1210 StreamRead, tk, StreamClose, tk );
1213 /* Create a task that will be called if we wait more than 300ms */
1214 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
1216 /* Do the read */
1217 p_sys->scheduler->doEventLoop( &p_sys->event );
1219 /* remove the task */
1220 p_sys->scheduler->unscheduleDelayedTask( task );
1222 /* Check for gap in pts value */
1223 for( i = 0; i < p_sys->i_track; i++ )
1225 live_track_t *tk = p_sys->track[i];
1227 if( !tk->b_muxed && !tk->b_rtcp_sync &&
1228 tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1230 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1232 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1233 tk->b_rtcp_sync = true;
1234 /* reset PCR */
1235 tk->i_pts = VLC_TS_INVALID;
1236 tk->i_npt = 0.;
1237 p_sys->i_pcr = 0;
1238 p_sys->i_npt = 0.;
1239 i_pcr = 0;
1243 if( p_sys->b_multicast && p_sys->b_no_data &&
1244 ( p_sys->i_no_data_ti > 120 ) )
1246 /* FIXME Make this configurable
1247 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1248 return 0;
1251 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1252 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1254 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1255 var_GetBool( p_demux, "rtsp-http" );
1257 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1259 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1260 if( RollOverTcp( p_demux ) )
1262 msg_Err( p_demux, "TCP rollover failed, aborting" );
1263 return 0;
1265 return 1;
1267 msg_Err( p_demux, "no data received in 10s, aborting" );
1268 return 0;
1270 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1271 ( p_sys->i_no_data_ti > 34 ) )
1273 /* EOF ? */
1274 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1275 return 0;
1277 return p_sys->b_error ? 0 : 1;
1280 /*****************************************************************************
1281 * Control:
1282 *****************************************************************************/
1283 static int Control( demux_t *p_demux, int i_query, va_list args )
1285 demux_sys_t *p_sys = p_demux->p_sys;
1286 int64_t *pi64, i64;
1287 double *pf, f;
1288 bool *pb, *pb2;
1289 int *pi_int;
1291 switch( i_query )
1293 case DEMUX_GET_TIME:
1294 pi64 = (int64_t*)va_arg( args, int64_t * );
1295 if( p_sys->i_npt > 0 )
1297 *pi64 = (int64_t)(p_sys->i_npt * 1000000.);
1298 return VLC_SUCCESS;
1300 return VLC_EGENERIC;
1302 case DEMUX_GET_LENGTH:
1303 pi64 = (int64_t*)va_arg( args, int64_t * );
1304 if( p_sys->i_npt_length > 0 )
1306 *pi64 = (int64_t)((double)p_sys->i_npt_length * 1000000.0);
1307 return VLC_SUCCESS;
1309 return VLC_EGENERIC;
1311 case DEMUX_GET_POSITION:
1312 pf = (double*)va_arg( args, double* );
1313 if( (p_sys->i_npt_length > 0) && (p_sys->i_npt > 0) )
1315 *pf = ( (double)p_sys->i_npt / (double)p_sys->i_npt_length );
1316 return VLC_SUCCESS;
1318 return VLC_EGENERIC;
1320 case DEMUX_SET_POSITION:
1321 case DEMUX_SET_TIME:
1322 if( p_sys->rtsp && (p_sys->i_npt_length > 0) )
1324 int i;
1325 float time;
1327 if( (i_query == DEMUX_SET_TIME) && (p_sys->i_npt > 0) )
1329 i64 = (int64_t)va_arg( args, int64_t );
1330 time = (float)((double)i64 / (double)1000000.0); /* in second */
1332 else if( i_query == DEMUX_SET_TIME )
1333 return VLC_EGENERIC;
1334 else
1336 f = (double)va_arg( args, double );
1337 time = f * (double)p_sys->i_npt_length; /* in second */
1340 if( p_sys->b_paused )
1342 p_sys->f_seek_request = time;
1343 return VLC_SUCCESS;
1346 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1348 if( !wait_Live555_response( p_demux ) )
1350 msg_Err( p_demux, "PAUSE before seek failed %s",
1351 p_sys->env->getResultMsg() );
1352 return VLC_EGENERIC;
1355 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1357 if( !wait_Live555_response( p_demux ) )
1359 msg_Err( p_demux, "seek PLAY failed %s",
1360 p_sys->env->getResultMsg() );
1361 return VLC_EGENERIC;
1363 p_sys->i_pcr = 0;
1365 /* Retrieve RTP-Info values */
1366 for( i = 0; i < p_sys->i_track; i++ )
1368 p_sys->track[i]->b_rtcp_sync = false;
1369 p_sys->track[i]->i_pts = VLC_TS_INVALID;
1372 /* Retrieve the starttime if possible */
1373 p_sys->i_npt = p_sys->i_npt_start = p_sys->ms->playStartTime();
1375 /* Retrieve the duration if possible */
1376 if( p_sys->ms->playEndTime() > 0 )
1377 p_sys->i_npt_length = p_sys->ms->playEndTime();
1379 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1380 return VLC_SUCCESS;
1382 return VLC_EGENERIC;
1384 /* Special for access_demux */
1385 case DEMUX_CAN_PAUSE:
1386 case DEMUX_CAN_SEEK:
1387 pb = (bool*)va_arg( args, bool * );
1388 if( p_sys->rtsp && p_sys->i_npt_length > 0 )
1389 /* Not always true, but will be handled in SET_PAUSE_STATE */
1390 *pb = true;
1391 else
1392 *pb = false;
1393 return VLC_SUCCESS;
1395 case DEMUX_CAN_CONTROL_PACE:
1396 pb = (bool*)va_arg( args, bool * );
1398 #if 1 /* Disable for now until we have a clock synchro algo
1399 * which works with something else than MPEG over UDP */
1400 *pb = false;
1401 #else
1402 *pb = true;
1403 #endif
1404 return VLC_SUCCESS;
1406 case DEMUX_CAN_CONTROL_RATE:
1407 pb = (bool*)va_arg( args, bool * );
1408 pb2 = (bool*)va_arg( args, bool * );
1410 *pb = (p_sys->rtsp != NULL) &&
1411 (p_sys->i_npt_length > 0) &&
1412 ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1413 !var_GetBool( p_demux, "rtsp-wmserver" ) );
1414 *pb2 = false;
1415 return VLC_SUCCESS;
1417 case DEMUX_SET_RATE:
1419 double f_scale, f_old_scale;
1421 if( !p_sys->rtsp || (p_sys->i_npt_length <= 0) ||
1422 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1423 var_GetBool( p_demux, "rtsp-wmserver" ) )
1424 return VLC_EGENERIC;
1426 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1427 * supports Scale:
1429 * "[...] should try to approximate the viewing rate, but
1430 * may restrict the range of scale values that it supports.
1431 * The response MUST contain the actual scale value chosen
1432 * by the server."
1434 * Scale = 1 indicates normal play
1435 * Scale > 1 indicates fast forward
1436 * Scale < 1 && Scale > 0 indicates slow motion
1437 * Scale < 0 value indicates rewind
1440 pi_int = (int*)va_arg( args, int * );
1441 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1442 f_old_scale = p_sys->ms->scale();
1444 /* Passing -1 for the start and end time will mean liveMedia won't
1445 * create a Range: section for the RTSP message. The server should
1446 * pick up from the current position */
1447 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1449 if( !wait_Live555_response( p_demux ) )
1451 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1452 p_sys->env->getResultMsg() );
1453 return VLC_EGENERIC;
1456 if( p_sys->ms->scale() == f_old_scale )
1458 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1459 p_sys->ms->scale() );
1460 return VLC_EGENERIC;
1463 /* ReSync the stream */
1464 p_sys->i_npt_start = 0;
1465 p_sys->i_pcr = 0;
1466 p_sys->i_npt = 0.0;
1468 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1469 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1470 return VLC_SUCCESS;
1473 case DEMUX_SET_PAUSE_STATE:
1475 bool b_pause = (bool)va_arg( args, int );
1476 if( p_sys->rtsp == NULL )
1477 return VLC_EGENERIC;
1479 if( b_pause == p_sys->b_paused )
1480 return VLC_SUCCESS;
1481 if( b_pause )
1482 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1483 else
1484 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1485 -1.0f, p_sys->ms->scale() );
1487 if( !wait_Live555_response( p_demux ) )
1489 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1490 return VLC_EGENERIC;
1492 p_sys->f_seek_request = -1;
1493 p_sys->b_paused = b_pause;
1495 /* When we Pause, we'll need the TimeoutPrevention thread to
1496 * handle sending the "Keep Alive" message to the server.
1497 * Unfortunately Live555 isn't thread safe and so can't
1498 * do this normally while the main Demux thread is handling
1499 * a live stream. We end up with the Timeout thread blocking
1500 * waiting for a response from the server. So when we PAUSE
1501 * we set a flag that the TimeoutPrevention function will check
1502 * and if it's set, it will trigger the GET_PARAMETER message */
1503 if( p_sys->b_paused && p_sys->p_timeout != NULL )
1504 p_sys->p_timeout->b_handle_keep_alive = true;
1505 else if( !p_sys->b_paused && p_sys->p_timeout != NULL )
1506 p_sys->p_timeout->b_handle_keep_alive = false;
1508 if( !p_sys->b_paused )
1510 for( int i = 0; i < p_sys->i_track; i++ )
1512 live_track_t *tk = p_sys->track[i];
1513 tk->b_rtcp_sync = false;
1514 tk->i_pts = VLC_TS_INVALID;
1515 p_sys->i_pcr = 0;
1516 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1520 /* Reset data received counter */
1521 p_sys->i_no_data_ti = 0;
1523 /* Retrieve the starttime if possible */
1524 p_sys->i_npt_start = p_sys->ms->playStartTime();
1526 /* Retrieve the duration if possible */
1527 if( p_sys->ms->playEndTime() )
1528 p_sys->i_npt_length = p_sys->ms->playEndTime();
1530 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1531 return VLC_SUCCESS;
1533 case DEMUX_GET_TITLE_INFO:
1534 case DEMUX_SET_TITLE:
1535 case DEMUX_SET_SEEKPOINT:
1536 return VLC_EGENERIC;
1538 case DEMUX_GET_PTS_DELAY:
1539 pi64 = (int64_t*)va_arg( args, int64_t * );
1540 *pi64 = var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1541 return VLC_SUCCESS;
1543 default:
1544 return VLC_EGENERIC;
1548 /*****************************************************************************
1549 * RollOverTcp: reopen the rtsp into TCP mode
1550 * XXX: ugly, a lot of code are duplicated from Open()
1551 * This should REALLY be fixed
1552 *****************************************************************************/
1553 static int RollOverTcp( demux_t *p_demux )
1555 demux_sys_t *p_sys = p_demux->p_sys;
1556 int i, i_return;
1558 var_SetBool( p_demux, "rtsp-tcp", true );
1560 /* We close the old RTSP session */
1561 for( i = 0; i < p_sys->i_track; i++ )
1563 live_track_t *tk = p_sys->track[i];
1565 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
1566 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1567 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1568 es_format_Clean( &tk->fmt );
1569 free( tk->p_buffer );
1570 free( tk );
1572 if( p_sys->i_track ) free( p_sys->track );
1573 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
1575 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1576 Medium::close( p_sys->ms );
1577 RTSPClient::close( p_sys->rtsp );
1579 p_sys->ms = NULL;
1580 p_sys->rtsp = NULL;
1581 p_sys->track = NULL;
1582 p_sys->i_track = 0;
1583 p_sys->b_no_data = true;
1584 p_sys->i_no_data_ti = 0;
1585 p_sys->p_out_asf = NULL;
1587 /* Reopen rtsp client */
1588 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1590 msg_Err( p_demux, "Failed to connect with rtsp://%s",
1591 p_sys->psz_path );
1592 goto error;
1595 if( p_sys->p_sdp == NULL )
1597 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1598 goto error;
1601 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1603 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1604 goto error;
1607 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1608 goto error;
1610 return VLC_SUCCESS;
1612 error:
1613 return VLC_EGENERIC;
1617 /*****************************************************************************
1619 *****************************************************************************/
1620 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1621 bool b_marker,
1622 const uint8_t *p_data, unsigned i_size )
1624 const unsigned i_packet_size = p_demux->p_sys->asfh.i_min_data_packet_size;
1625 block_t *p_list = NULL;
1627 while( i_size >= 4 )
1629 unsigned i_flags = p_data[0];
1630 unsigned i_length_offset = (p_data[1] << 16) |
1631 (p_data[2] << 8) |
1632 (p_data[3] );
1633 bool b_key = i_flags & 0x80;
1634 bool b_length = i_flags & 0x40;
1635 bool b_relative_ts = i_flags & 0x20;
1636 bool b_duration = i_flags & 0x10;
1637 bool b_location_id = i_flags & 0x08;
1639 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1640 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1641 unsigned i_header_size = 4;
1642 if( b_relative_ts )
1643 i_header_size += 4;
1644 if( b_duration )
1645 i_header_size += 4;
1646 if( b_location_id )
1647 i_header_size += 4;
1649 if( i_header_size > i_size )
1651 msg_Warn( p_demux, "Invalid header size" );
1652 break;
1655 /* XXX
1656 * When b_length is true, the streams I found do not seems to respect
1657 * the documentation.
1658 * From them, I have failed to find which choice between '__MIN()' or
1659 * 'i_length_offset - i_header_size' is the right one.
1661 unsigned i_payload;
1662 if( b_length )
1663 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1664 else
1665 i_payload = i_size - i_header_size;
1667 if( !tk->p_asf_block )
1669 tk->p_asf_block = block_New( p_demux, i_packet_size );
1670 if( !tk->p_asf_block )
1671 break;
1672 tk->p_asf_block->i_buffer = 0;
1674 unsigned i_offset = b_length ? 0 : i_length_offset;
1675 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1677 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1678 tk->p_asf_block->i_buffer += i_payload;
1679 if( b_marker )
1681 /* We have a complete packet */
1682 tk->p_asf_block->i_buffer = i_packet_size;
1683 block_ChainAppend( &p_list, tk->p_asf_block );
1684 tk->p_asf_block = NULL;
1687 else
1689 /* Reset on broken stream */
1690 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1691 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1692 tk->p_asf_block->i_buffer = 0;
1695 /* */
1696 p_data += i_header_size + i_payload;
1697 i_size -= i_header_size + i_payload;
1699 return p_list;
1702 /*****************************************************************************
1704 *****************************************************************************/
1705 static void StreamRead( void *p_private, unsigned int i_size,
1706 unsigned int i_truncated_bytes, struct timeval pts,
1707 unsigned int duration )
1709 live_track_t *tk = (live_track_t*)p_private;
1710 demux_t *p_demux = tk->p_demux;
1711 demux_sys_t *p_sys = p_demux->p_sys;
1712 block_t *p_block;
1714 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1716 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1717 (int64_t)pts.tv_usec;
1719 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1720 i_pts &= INT64_C(0x00ffffffffffffff);
1722 /* Retrieve NPT for this pts */
1723 tk->i_npt = tk->sub->getNormalPlayTime(pts);
1725 if( tk->b_quicktime && tk->p_es == NULL )
1727 QuickTimeGenericRTPSource *qtRTPSource =
1728 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1729 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1730 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1732 if( tk->fmt.i_cat == VIDEO_ES ) {
1733 if( qtState.sdAtomSize < 16 + 32 )
1735 /* invalid */
1736 p_sys->event = 0xff;
1737 tk->waiting = 0;
1738 return;
1740 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1741 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1742 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1744 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1746 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1747 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1748 + qtRTPSource->qtState.sdAtomSize;
1749 while (pos+8 < endpos) {
1750 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1751 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1752 if( memcmp(pos+4, "avcC", 4) == 0 &&
1753 atomLength > 8 &&
1754 atomLength <= INT_MAX )
1756 tk->fmt.i_extra = atomLength-8;
1757 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1758 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1759 break;
1761 pos += atomLength;
1764 else
1766 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1767 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1768 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1771 else {
1772 if( qtState.sdAtomSize < 4 )
1774 /* invalid */
1775 p_sys->event = 0xff;
1776 tk->waiting = 0;
1777 return;
1779 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1781 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1784 #if 0
1785 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1786 i_size,
1787 pts.tv_sec * 1000000LL + pts.tv_usec );
1788 #endif
1790 /* grow buffer if it looks like buffer is too small, but don't eat
1791 * up all the memory on strange streams */
1792 if( i_truncated_bytes > 0 )
1794 if( tk->i_buffer < 2000000 )
1796 void *p_tmp;
1797 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1798 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1799 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1800 if( p_tmp == NULL )
1802 msg_Warn( p_demux, "realloc failed" );
1804 else
1806 tk->p_buffer = (uint8_t*)p_tmp;
1807 tk->i_buffer *= 2;
1811 if( tk->b_discard_trunc )
1813 p_sys->event = 0xff;
1814 tk->waiting = 0;
1815 return;
1819 assert( i_size <= tk->i_buffer );
1821 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1822 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1824 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1826 p_block = block_New( p_demux, i_size + 1 );
1827 p_block->p_buffer[0] = amrSource->lastFrameHeader();
1828 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1830 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1832 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1833 uint32_t header = h261Source->lastSpecialHeader();
1834 p_block = block_New( p_demux, i_size + 4 );
1835 memcpy( p_block->p_buffer, &header, 4 );
1836 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1838 if( tk->sub->rtpSource()->curPacketMarkerBit() )
1839 p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1841 else if( tk->fmt.i_codec == VLC_CODEC_H264 )
1843 if( (tk->p_buffer[0] & 0x1f) >= 24 )
1844 msg_Warn( p_demux, "unsupported NAL type for H264" );
1846 /* Normal NAL type */
1847 p_block = block_New( p_demux, i_size + 4 );
1848 p_block->p_buffer[0] = 0x00;
1849 p_block->p_buffer[1] = 0x00;
1850 p_block->p_buffer[2] = 0x00;
1851 p_block->p_buffer[3] = 0x01;
1852 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1854 else if( tk->b_asf )
1856 p_block = StreamParseAsf( p_demux, tk,
1857 tk->sub->rtpSource()->curPacketMarkerBit(),
1858 tk->p_buffer, i_size );
1860 else
1862 p_block = block_New( p_demux, i_size );
1863 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1866 if( p_sys->i_pcr < i_pts )
1868 p_sys->i_pcr = i_pts;
1871 /* Update our global npt value */
1872 if( tk->i_npt > 0 && tk->i_npt > p_sys->i_npt && tk->i_npt < p_sys->i_npt_length)
1873 p_sys->i_npt = tk->i_npt;
1875 if( p_block )
1877 if( !tk->b_muxed && !tk->b_asf )
1879 if( i_pts != tk->i_pts )
1880 p_block->i_pts = VLC_TS_0 + i_pts;
1881 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
1882 p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? VLC_TS_INVALID : (VLC_TS_0 + i_pts);
1885 if( tk->b_muxed )
1886 stream_DemuxSend( tk->p_out_muxed, p_block );
1887 else if( tk->b_asf )
1888 stream_DemuxSend( p_sys->p_out_asf, p_block );
1889 else
1890 es_out_Send( p_demux->out, tk->p_es, p_block );
1893 /* warn that's ok */
1894 p_sys->event = 0xff;
1896 /* we have read data */
1897 tk->waiting = 0;
1898 p_demux->p_sys->b_no_data = false;
1899 p_demux->p_sys->i_no_data_ti = 0;
1901 if( i_pts > 0 && !tk->b_muxed )
1903 tk->i_pts = i_pts;
1907 /*****************************************************************************
1909 *****************************************************************************/
1910 static void StreamClose( void *p_private )
1912 live_track_t *tk = (live_track_t*)p_private;
1913 demux_t *p_demux = tk->p_demux;
1914 demux_sys_t *p_sys = p_demux->p_sys;
1916 msg_Dbg( p_demux, "StreamClose" );
1918 p_sys->event = 0xff;
1919 p_sys->b_error = true;
1923 /*****************************************************************************
1925 *****************************************************************************/
1926 static void TaskInterrupt( void *p_private )
1928 demux_t *p_demux = (demux_t*)p_private;
1930 p_demux->p_sys->i_no_data_ti++;
1932 /* Avoid lock */
1933 p_demux->p_sys->event = 0xff;
1936 /*****************************************************************************
1938 *****************************************************************************/
1939 static void* TimeoutPrevention( void *p_data )
1941 timeout_thread_t *p_timeout = (timeout_thread_t *)p_data;
1943 for( ;; )
1945 /* Voodoo (= no) thread safety here! *Ahem* */
1946 if( p_timeout->b_handle_keep_alive )
1948 char *psz_bye = NULL;
1949 int canc = vlc_savecancel ();
1951 p_timeout->p_sys->rtsp->sendGetParameterCommand( *p_timeout->p_sys->ms, NULL, psz_bye );
1952 vlc_restorecancel (canc);
1954 p_timeout->p_sys->b_timeout_call = !p_timeout->b_handle_keep_alive;
1956 msleep (((int64_t)p_timeout->p_sys->i_timeout - 2) * CLOCK_FREQ);
1958 assert(0); /* dead code */
1961 /*****************************************************************************
1963 *****************************************************************************/
1964 static int ParseASF( demux_t *p_demux )
1966 demux_sys_t *p_sys = p_demux->p_sys;
1968 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1969 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1970 char *psz_end;
1971 block_t *p_header;
1973 /* Parse the asf header */
1974 if( psz_asf == NULL )
1975 return VLC_EGENERIC;
1977 psz_asf += strlen( psz_marker );
1978 psz_asf = strdup( psz_asf ); /* Duplicate it */
1979 psz_end = strchr( psz_asf, '\n' );
1981 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1982 *psz_end-- = '\0';
1984 if( psz_asf >= psz_end )
1986 free( psz_asf );
1987 return VLC_EGENERIC;
1990 /* Always smaller */
1991 p_header = block_New( p_demux, psz_end - psz_asf );
1992 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
1993 p_header->i_buffer, psz_asf );
1994 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
1995 if( p_header->i_buffer <= 0 )
1997 free( psz_asf );
1998 return VLC_EGENERIC;
2001 /* Parse it to get packet size */
2002 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2004 /* Send it to demuxer */
2005 stream_DemuxSend( p_sys->p_out_asf, p_header );
2007 free( psz_asf );
2008 return VLC_SUCCESS;
2012 static unsigned char* parseH264ConfigStr( char const* configStr,
2013 unsigned int& configSize )
2015 char *dup, *psz;
2016 size_t i_records = 1;
2018 configSize = 0;
2020 if( configStr == NULL || *configStr == '\0' )
2021 return NULL;
2023 psz = dup = strdup( configStr );
2025 /* Count the number of commas */
2026 for( psz = dup; *psz != '\0'; ++psz )
2028 if( *psz == ',')
2030 ++i_records;
2031 *psz = '\0';
2035 size_t configMax = 5*strlen(dup);
2036 unsigned char *cfg = new unsigned char[configMax];
2037 psz = dup;
2038 for( size_t i = 0; i < i_records; ++i )
2040 cfg[configSize++] = 0x00;
2041 cfg[configSize++] = 0x00;
2042 cfg[configSize++] = 0x00;
2043 cfg[configSize++] = 0x01;
2045 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2046 configMax-configSize, psz );
2047 psz += strlen(psz)+1;
2050 free( dup );
2051 return cfg;