1 /*****************************************************************************
2 * live555.cpp : LIVE555 Streaming Media support.
3 *****************************************************************************
4 * Copyright (C) 2003-2007 the VideoLAN team
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
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24 *****************************************************************************/
26 /*****************************************************************************
28 *****************************************************************************/
31 * Note: config.h may include inttypes.h, so make sure we define this option
33 #define __STDC_CONSTANT_MACROS 1
41 #include <vlc_common.h>
42 #include <vlc_plugin.h>
43 #include <vlc_input.h>
44 #include <vlc_demux.h>
45 #include <vlc_dialog.h>
47 #include <vlc_strings.h>
48 #include <vlc_memory.h>
56 # include <winsock2.h>
59 #include <UsageEnvironment.hh>
60 #include <BasicUsageEnvironment.hh>
61 #include <GroupsockHelper.hh>
62 #include <liveMedia.hh>
65 #include "../access/mms/asf.h" /* Who said ugly ? */
70 /*****************************************************************************
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.")
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" )
104 add_shortcut( "livedotcom" )
105 set_category( CAT_INPUT )
106 set_subcategory( SUBCAT_INPUT_DEMUX )
109 set_description( N_("RTSP/RTP access and demux") )
110 add_shortcut( "rtsp" )
111 add_shortcut( "sdp" )
112 add_shortcut( "live" )
113 add_shortcut( "livedotcom" )
114 set_capability( "access_demux", 0 )
115 set_callbacks( Open, Close )
116 add_bool( "rtsp-tcp", false, NULL,
117 N_("Use RTP over RTSP (TCP)"),
118 N_("Use RTP over RTSP (TCP)"), true )
120 add_integer( "rtp-client-port", -1, NULL,
122 N_("Port to use for the RTP source of the session"), true )
123 add_bool( "rtsp-mcast", false, NULL,
124 N_("Force multicast RTP via RTSP"),
125 N_("Force multicast RTP via RTSP"), true )
127 add_bool( "rtsp-http", false, NULL,
128 N_("Tunnel RTSP and RTP over HTTP"),
129 N_("Tunnel RTSP and RTP over HTTP"), true )
131 add_integer( "rtsp-http-port", 80, NULL,
132 N_("HTTP tunnel port"),
133 N_("Port to use for tunneling the RTSP/RTP over HTTP."),
135 add_integer("rtsp-caching", 4 * DEFAULT_PTS_DELAY / 1000, NULL,
136 CACHING_TEXT, CACHING_LONGTEXT, true )
138 add_bool( "rtsp-kasenna", false, NULL, KASENNA_TEXT,
139 KASENNA_LONGTEXT, true )
140 add_bool( "rtsp-wmserver", false, NULL, WMSERVER_TEXT,
141 WMSERVER_LONGTEXT, true)
143 add_string( "rtsp-user", NULL, NULL, USER_TEXT,
144 USER_LONGTEXT, true )
146 add_password( "rtsp-pwd", NULL, NULL, PASS_TEXT,
147 PASS_LONGTEXT, true )
152 /*****************************************************************************
154 *****************************************************************************/
159 MediaSubsession *sub;
167 bool b_discard_trunc;
168 stream_t *p_out_muxed; /* for muxed stream */
171 unsigned int i_buffer;
180 struct timeout_thread_t
184 bool b_handle_keep_alive;
189 char *p_sdp; /* XXX mallocated */
190 char *psz_path; /* URL-encoded path */
194 TaskScheduler *scheduler;
195 UsageEnvironment *env ;
200 live_track_t **track; /* XXX mallocated */
208 int64_t i_pcr; /* The clock */
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 */
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 */
226 bool b_get_param; /* Does the server support GET_PARAMETER */
227 bool b_paused; /* Are we paused? */
229 float f_seek_request;/* In case we receive a seek request while paused*/
232 static int Demux ( demux_t * );
233 static int Control( demux_t *, int, va_list );
235 static int Connect ( demux_t * );
236 static int SessionsSetup( demux_t * );
237 static int Play ( demux_t *);
238 static int ParseASF ( demux_t * );
239 static int RollOverTcp ( demux_t * );
241 static void StreamRead ( void *, unsigned int, unsigned int,
242 struct timeval, unsigned int );
243 static void StreamClose ( void * );
244 static void TaskInterrupt( void * );
246 static void* TimeoutPrevention( void * );
248 static unsigned char* parseH264ConfigStr( char const* configStr,
249 unsigned int& configSize );
251 /*****************************************************************************
253 *****************************************************************************/
254 static int Open ( vlc_object_t *p_this )
256 demux_t *p_demux = (demux_t*)p_this;
257 demux_sys_t *p_sys = NULL;
260 int i_error = VLC_EGENERIC;
264 /* See if it looks like a SDP
265 v, o, s fields are mandatory and in this order */
266 const uint8_t *p_peek;
267 if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
269 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
270 memcmp( p_peek, "v=0\n", 4 ) &&
271 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
278 var_Create( p_demux, "rtsp-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
281 p_demux->pf_demux = Demux;
282 p_demux->pf_control= Control;
283 p_demux->p_sys = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
284 if( !p_sys ) return VLC_ENOMEM;
287 p_sys->scheduler = NULL;
295 p_sys->i_npt_start = 0.;
296 p_sys->i_npt_length = 0.;
297 p_sys->p_out_asf = NULL;
298 p_sys->b_no_data = true;
299 p_sys->i_no_data_ti = 0;
300 p_sys->p_timeout = NULL;
301 p_sys->i_timeout = 0;
302 p_sys->b_timeout_call = false;
303 p_sys->b_multicast = false;
304 p_sys->b_real = false;
305 p_sys->psz_path = strdup( p_demux->psz_path );
306 p_sys->b_force_mcast = var_CreateGetBool( p_demux, "rtsp-mcast" );
307 p_sys->b_get_param = false;
308 p_sys->b_paused = false;
309 p_sys->f_seek_request = -1;
311 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
312 vlc_UrlParse( &p_sys->url, p_sys->psz_path, 0 );
314 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
316 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
319 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
321 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
325 if( strcasecmp( p_demux->psz_access, "sdp" ) )
327 char *p = p_sys->psz_path;
328 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
331 if( p_demux->s != NULL )
333 /* Gather the complete sdp file */
335 int i_sdp_max = 1000;
336 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
340 i_error = VLC_ENOMEM;
346 int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
347 i_sdp_max - i_sdp - 1 );
349 if( !vlc_object_alive (p_demux) || p_demux->b_error )
357 msg_Err( p_demux, "failed to read SDP" );
364 if( i_read < i_sdp_max - i_sdp - 1 )
371 p_sdp = (uint8_t*)realloc_or_free( p_sdp, i_sdp_max );
374 p_sys->p_sdp = (char*)p_sdp;
376 else if( ( p_demux->s == NULL ) &&
377 !strcasecmp( p_demux->psz_access, "sdp" ) )
379 /* sdp:// link from SAP */
380 p_sys->p_sdp = strdup( p_sys->psz_path );
382 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
384 msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
388 if( p_sys->p_sdp == NULL )
390 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
391 i_error = VLC_ENOMEM;
395 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
397 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
401 if( p_sys->b_real ) goto error;
403 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
406 if( p_sys->p_out_asf && ParseASF( p_demux ) )
408 msg_Err( p_demux, "cannot find a usable asf header" );
409 /* TODO Clean tracks */
413 if( p_sys->i_track <= 0 )
423 /*****************************************************************************
425 *****************************************************************************/
426 static void Close( vlc_object_t *p_this )
428 demux_t *p_demux = (demux_t*)p_this;
429 demux_sys_t *p_sys = p_demux->p_sys;
432 for( i = 0; i < p_sys->i_track; i++ )
434 live_track_t *tk = p_sys->track[i];
436 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
437 es_format_Clean( &tk->fmt );
438 free( tk->p_buffer );
442 if( p_sys->i_track ) free( p_sys->track );
443 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
444 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->teardownMediaSession( *p_sys->ms );
445 if( p_sys->p_timeout )
447 vlc_cancel( p_sys->p_timeout->handle );
448 vlc_join( p_sys->p_timeout->handle, NULL );
449 free( p_sys->p_timeout );
451 if( p_sys->ms ) Medium::close( p_sys->ms );
452 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
453 if( p_sys->env ) p_sys->env->reclaim();
454 delete p_sys->scheduler;
455 free( p_sys->p_sdp );
456 free( p_sys->psz_path );
458 vlc_UrlClean( &p_sys->url );
463 static inline const char *strempty( const char *s ) { return s?s:""; }
464 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
466 /*****************************************************************************
467 * Connect: connects to the RTSP server to setup the session DESCRIBE
468 *****************************************************************************/
469 static int Connect( demux_t *p_demux )
471 demux_sys_t *p_sys = p_demux->p_sys;
472 Authenticator authenticator;
473 bool b_firstpass = true;
474 char *psz_user = NULL;
475 char *psz_pwd = NULL;
476 char *psz_url = NULL;
477 char *psz_options = NULL;
480 int i_ret = VLC_SUCCESS;
482 /* Create the url using the port number if available */
483 if( p_sys->url.i_port == 0 )
485 p_sys->url.i_port = 554;
486 if( asprintf( &psz_url, "rtsp://%s", p_sys->psz_path ) == -1 )
491 if( asprintf( &psz_url, "rtsp://%s:%d%s", p_sys->url.psz_host,
492 p_sys->url.i_port, p_sys->url.psz_path ) == -1 )
496 /* Get the user name and password */
497 if( p_sys->url.psz_username || p_sys->url.psz_password )
499 psz_user = strdup( strempty( p_sys->url.psz_username ) );
500 psz_pwd = strdup( strempty( p_sys->url.psz_password ) );
504 psz_user = var_CreateGetString( p_demux, "rtsp-user" );
505 psz_pwd = var_CreateGetString( p_demux, "rtsp-pwd" );
509 if( !vlc_object_alive (p_demux) || p_demux->b_error )
511 i_ret = VLC_EGENERIC;
515 if( var_CreateGetBool( p_demux, "rtsp-http" ) )
516 i_http_port = var_CreateGetInteger( p_demux, "rtsp-http-port" );
518 if( ( p_sys->rtsp = RTSPClient::createNew( *p_sys->env,
519 var_CreateGetInteger( p_demux, "verbose" ) > 1,
520 "VLC media player", i_http_port ) ) == NULL )
522 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
523 p_sys->env->getResultMsg() );
524 i_ret = VLC_EGENERIC;
528 /* Kasenna enables KeepAlive by analysing the User-Agent string.
529 * Appending _KA to the string should be enough to enable this feature,
530 * however, there is a bug where the _KA doesn't get parsed from the
531 * default User-Agent as created by VLC/Live555 code. This is probably due
532 * to spaces in the string or the string being too long. Here we override
533 * the default string with a more compact version.
535 if( var_CreateGetBool( p_demux, "rtsp-kasenna" ))
537 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
541 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
544 { /* i_timeout hack scope */
545 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1223337600
546 const int i_timeout = var_CreateGetInteger(p_demux, "ipv4-timeout") / 1000;
547 psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
548 &authenticator, i_timeout );
550 psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
553 if( psz_options == NULL && authenticator.realm() != NULL )
555 // try again, with the realm set this time
556 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1223337600
557 psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
558 &authenticator, i_timeout );
560 psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
565 p_sys->b_get_param = (bool)strstr( psz_options, "GET_PARAMETER" );
566 delete [] psz_options;
568 if( var_CreateGetBool( p_demux, "rtsp-wmserver" ) )
569 p_sys->b_get_param = true;
571 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1223337600
572 p_sdp = p_sys->rtsp->describeWithPassword( psz_url, psz_user, psz_pwd,
573 var_GetBool( p_demux, "rtsp-kasenna" ), i_timeout );
575 p_sdp = p_sys->rtsp->describeWithPassword( psz_url, psz_user, psz_pwd,
576 var_GetBool( p_demux, "rtsp-kasenna" ) );
578 } /* i_timeout scope end */
582 /* failure occurred */
584 const char *psz_error = p_sys->env->getResultMsg();
586 if( var_GetBool( p_demux, "rtsp-http" ) )
587 sscanf( psz_error, "%*s %*s HTTP GET %*s HTTP/%*u.%*u %3u %*s",
591 const char *psz_tmp = strstr( psz_error, "RTSP" );
593 sscanf( psz_tmp, "RTSP/%*s%3u", &i_code );
597 msg_Dbg( p_demux, "DESCRIBE failed with %d: %s", i_code, psz_error );
600 { /* describeURL always returns an "RTSP/1.0 401 Unauthorized" the
601 * first time. This is a workaround to avoid asking for a
602 * user/passwd the first time the code passess here. */
609 msg_Dbg( p_demux, "authentication failed" );
613 dialog_Login( p_demux, &psz_user, &psz_pwd,
614 _("RTSP authentication"), "%s",
615 _("Please enter a valid login name and a password.") );
616 if( psz_user != NULL && psz_pwd != NULL )
618 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
622 else if( (i_code != 0) && !var_GetBool( p_demux, "rtsp-http" ) )
624 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
625 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
626 var_SetBool( p_demux, "rtsp-http", true );
627 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
633 msg_Dbg( p_demux, "connection timeout" );
634 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
637 i_ret = VLC_EGENERIC;
640 free( p_sys->p_sdp );
642 if( p_sdp ) p_sys->p_sdp = strdup( (char*)p_sdp );
646 /* malloc-ated copy */
654 /*****************************************************************************
655 * SessionsSetup: prepares the subsessions and does the SETUP
656 *****************************************************************************/
657 static int SessionsSetup( demux_t *p_demux )
659 demux_sys_t *p_sys = p_demux->p_sys;
660 MediaSubsessionIterator *iter = NULL;
661 MediaSubsession *sub = NULL;
663 bool b_rtsp_tcp = false;
665 int i_return = VLC_SUCCESS;
666 unsigned int i_buffer = 0;
667 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
669 b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
670 var_GetBool( p_demux, "rtsp-http" );
671 i_client_port = var_CreateGetInteger( p_demux, "rtp-client-port" );
673 /* Create the session from the SDP */
674 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
676 msg_Err( p_demux, "Could not create the RTSP Session: %s",
677 p_sys->env->getResultMsg() );
681 /* Initialise each media subsession */
682 iter = new MediaSubsessionIterator( *p_sys->ms );
683 while( ( sub = iter->next() ) != NULL )
688 if( !vlc_object_alive (p_demux) || p_demux->b_error )
694 /* Value taken from mplayer */
695 if( !strcmp( sub->mediumName(), "audio" ) )
697 else if( !strcmp( sub->mediumName(), "video" ) )
699 else if( !strcmp( sub->mediumName(), "text" ) )
703 if( i_client_port != -1 )
705 sub->setClientPortNum( i_client_port );
709 if( strcasestr( sub->codecName(), "REAL" ) )
711 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
712 p_sys->b_real = true; /* This is a problem, we'll handle it later */
716 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
717 bInit = sub->initiate( 4 ); /* Constant ? */
719 bInit = sub->initiate();
723 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
724 sub->mediumName(), sub->codecName(),
725 p_sys->env->getResultMsg() );
729 if( sub->rtpSource() != NULL )
731 int fd = sub->rtpSource()->RTPgs()->socketNum();
733 /* Increase the buffer size */
735 increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
737 /* Increase the RTP reorder timebuffer just a bit */
738 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
740 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
743 /* Issue the SETUP */
746 if( !p_sys->rtsp->setupMediaSubsession( *sub, False,
747 toBool( b_rtsp_tcp ),
748 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) ) )
750 /* if we get an unsupported transport error, toggle TCP
751 * use and try again */
752 if( !strstr(p_sys->env->getResultMsg(),
753 "461 Unsupported Transport")
754 || !p_sys->rtsp->setupMediaSubsession( *sub, False,
755 toBool( b_rtsp_tcp ), False ) )
757 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
758 sub->mediumName(), sub->codecName(),
759 p_sys->env->getResultMsg() );
765 /* Check if we will receive data from this subsession for
767 if( sub->readSource() == NULL ) continue;
768 if( !p_sys->b_multicast )
770 /* We need different rollover behaviour for multicast */
771 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
774 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
780 tk->p_demux = p_demux;
783 tk->b_quicktime = false;
786 tk->b_discard_trunc = false;
787 tk->p_out_muxed = NULL;
789 tk->b_rtcp_sync = false;
792 tk->i_buffer = 65536;
793 tk->p_buffer = (uint8_t *)malloc( 65536 );
801 /* Value taken from mplayer */
802 if( !strcmp( sub->mediumName(), "audio" ) )
804 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
805 tk->fmt.audio.i_channels = sub->numChannels();
806 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
808 if( !strcmp( sub->codecName(), "MPA" ) ||
809 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
810 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
812 tk->fmt.i_codec = VLC_CODEC_MPGA;
813 tk->fmt.audio.i_rate = 0;
815 else if( !strcmp( sub->codecName(), "AC3" ) )
817 tk->fmt.i_codec = VLC_CODEC_A52;
818 tk->fmt.audio.i_rate = 0;
820 else if( !strcmp( sub->codecName(), "L16" ) )
822 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
823 tk->fmt.audio.i_bitspersample = 16;
825 else if( !strcmp( sub->codecName(), "L8" ) )
827 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
828 tk->fmt.audio.i_bitspersample = 8;
830 else if( !strcmp( sub->codecName(), "PCMU" ) )
832 tk->fmt.i_codec = VLC_CODEC_MULAW;
834 else if( !strcmp( sub->codecName(), "PCMA" ) )
836 tk->fmt.i_codec = VLC_CODEC_ALAW;
838 else if( !strncmp( sub->codecName(), "G726", 4 ) )
840 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
841 tk->fmt.audio.i_rate = 8000;
842 tk->fmt.audio.i_channels = 1;
843 if( !strcmp( sub->codecName()+5, "40" ) )
844 tk->fmt.i_bitrate = 40000;
845 else if( !strcmp( sub->codecName()+5, "32" ) )
846 tk->fmt.i_bitrate = 32000;
847 else if( !strcmp( sub->codecName()+5, "24" ) )
848 tk->fmt.i_bitrate = 24000;
849 else if( !strcmp( sub->codecName()+5, "16" ) )
850 tk->fmt.i_bitrate = 16000;
852 else if( !strcmp( sub->codecName(), "AMR" ) )
854 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
856 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
858 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
860 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
862 unsigned int i_extra;
865 tk->fmt.i_codec = VLC_CODEC_MP4A;
867 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
870 tk->fmt.i_extra = i_extra;
871 tk->fmt.p_extra = malloc( i_extra );
872 assert( tk->fmt.p_extra );
873 memcpy( tk->fmt.p_extra, p_extra, i_extra );
876 /* Because the "faad" decoder does not handle the LATM
877 * data length field at the start of each returned LATM
878 * frame, tell the RTP source to omit it. */
879 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
881 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
883 unsigned int i_extra;
886 tk->fmt.i_codec = VLC_CODEC_MP4A;
888 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
891 tk->fmt.i_extra = i_extra;
892 tk->fmt.p_extra = malloc( i_extra );
893 assert( tk->fmt.p_extra );
894 memcpy( tk->fmt.p_extra, p_extra, i_extra );
898 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
901 if( p_sys->p_out_asf == NULL )
902 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
905 else if( !strcmp( sub->codecName(), "X-QT" ) ||
906 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
908 tk->b_quicktime = true;
910 else if( !strcmp( sub->codecName(), "SPEEX" ) )
912 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
913 if ( sub->rtpTimestampFrequency() )
914 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
917 msg_Warn( p_demux,"Using 8kHz as default sample rate." );
918 tk->fmt.audio.i_rate = 8000;
922 else if( !strcmp( sub->mediumName(), "video" ) )
924 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
925 if( !strcmp( sub->codecName(), "MPV" ) )
927 tk->fmt.i_codec = VLC_CODEC_MPGV;
929 else if( !strcmp( sub->codecName(), "H263" ) ||
930 !strcmp( sub->codecName(), "H263-1998" ) ||
931 !strcmp( sub->codecName(), "H263-2000" ) )
933 tk->fmt.i_codec = VLC_CODEC_H263;
935 else if( !strcmp( sub->codecName(), "H261" ) )
937 tk->fmt.i_codec = VLC_CODEC_H261;
939 else if( !strcmp( sub->codecName(), "H264" ) )
941 unsigned int i_extra = 0;
942 uint8_t *p_extra = NULL;
944 tk->fmt.i_codec = VLC_CODEC_H264;
945 tk->fmt.b_packetized = false;
947 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
950 tk->fmt.i_extra = i_extra;
951 tk->fmt.p_extra = malloc( i_extra );
952 assert( tk->fmt.p_extra );
953 memcpy( tk->fmt.p_extra, p_extra, i_extra );
958 else if( !strcmp( sub->codecName(), "JPEG" ) )
960 tk->fmt.i_codec = VLC_CODEC_MJPG;
962 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
964 unsigned int i_extra;
967 tk->fmt.i_codec = VLC_CODEC_MP4V;
969 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
972 tk->fmt.i_extra = i_extra;
973 tk->fmt.p_extra = malloc( i_extra );
974 assert( tk->fmt.p_extra );
975 memcpy( tk->fmt.p_extra, p_extra, i_extra );
979 else if( !strcmp( sub->codecName(), "X-QT" ) ||
980 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
981 !strcmp( sub->codecName(), "X-QDM" ) ||
982 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
983 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
985 tk->b_quicktime = true;
987 else if( !strcmp( sub->codecName(), "MP2T" ) )
990 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
992 else if( !strcmp( sub->codecName(), "MP2P" ) ||
993 !strcmp( sub->codecName(), "MP1S" ) )
996 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
999 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1002 if( p_sys->p_out_asf == NULL )
1003 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
1006 else if( !strcmp( sub->codecName(), "DV" ) )
1009 tk->b_discard_trunc = true;
1010 tk->p_out_muxed = stream_DemuxNew( p_demux, "rawdv",
1014 else if( !strcmp( sub->mediumName(), "text" ) )
1016 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1018 if( !strcmp( sub->codecName(), "T140" ) )
1020 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1024 if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
1026 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1029 if( sub->rtcpInstance() != NULL )
1031 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1034 if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
1037 p_sys->track = (live_track_t**)realloc_or_free( p_sys->track,
1038 sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
1039 assert( p_sys->track );
1040 p_sys->track[p_sys->i_track++] = tk;
1045 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1046 es_format_Clean( &tk->fmt );
1052 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1054 /* Retrieve the starttime if possible */
1055 p_sys->i_npt_start = p_sys->ms->playStartTime();
1057 /* Retrieve the duration if possible */
1058 p_sys->i_npt_length = p_sys->ms->playEndTime();
1061 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1064 p_sys->b_no_data = true;
1065 p_sys->i_no_data_ti = 0;
1070 /*****************************************************************************
1071 * Play: starts the actual playback of the stream
1072 *****************************************************************************/
1073 static int Play( demux_t *p_demux )
1075 demux_sys_t *p_sys = p_demux->p_sys;
1080 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, p_sys->i_npt_start, -1, 1 ) )
1082 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1083 return VLC_EGENERIC;
1086 /* Retrieve the timeout value and set up a timeout prevention thread */
1087 p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
1088 if( p_sys->i_timeout <= 0 )
1089 p_sys->i_timeout = 60; /* default value from RFC2326 */
1091 /* start timeout-thread only if GET_PARAMETER is supported by the server */
1092 if( !p_sys->p_timeout && p_sys->b_get_param )
1094 msg_Dbg( p_demux, "We have a timeout of %d seconds", p_sys->i_timeout );
1095 p_sys->p_timeout = (timeout_thread_t *)malloc( sizeof(timeout_thread_t) );
1096 if( p_sys->p_timeout )
1098 memset( p_sys->p_timeout, 0, sizeof(timeout_thread_t) );
1099 p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
1100 if( vlc_clone( &p_sys->p_timeout->handle, TimeoutPrevention,
1101 p_sys->p_timeout, VLC_THREAD_PRIORITY_LOW ) )
1103 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1104 free( p_sys->p_timeout );
1105 p_sys->p_timeout = NULL;
1108 msg_Dbg( p_demux, "spawned timeout thread" );
1111 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1116 /* Retrieve the starttime if possible */
1117 p_sys->i_npt_start = p_sys->ms->playStartTime();
1118 if( p_sys->ms->playEndTime() > 0 )
1119 p_sys->i_npt_length = p_sys->ms->playEndTime();
1121 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1126 /*****************************************************************************
1128 *****************************************************************************/
1129 static int Demux( demux_t *p_demux )
1131 demux_sys_t *p_sys = p_demux->p_sys;
1134 bool b_send_pcr = true;
1138 /* Check if we need to send the server a Keep-A-Live signal */
1139 if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
1141 char *psz_bye = NULL;
1142 p_sys->rtsp->getMediaSessionParameter( *p_sys->ms, NULL, psz_bye );
1143 p_sys->b_timeout_call = false;
1146 for( i = 0; i < p_sys->i_track; i++ )
1148 live_track_t *tk = p_sys->track[i];
1150 if( tk->b_asf || tk->b_muxed )
1157 else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
1163 if( p_sys->i_pcr > 0 )
1166 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
1169 /* First warn we want to read data */
1171 for( i = 0; i < p_sys->i_track; i++ )
1173 live_track_t *tk = p_sys->track[i];
1175 if( tk->waiting == 0 )
1178 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1179 StreamRead, tk, StreamClose, tk );
1182 /* Create a task that will be called if we wait more than 300ms */
1183 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
1186 p_sys->scheduler->doEventLoop( &p_sys->event );
1188 /* remove the task */
1189 p_sys->scheduler->unscheduleDelayedTask( task );
1191 /* Check for gap in pts value */
1192 for( i = 0; i < p_sys->i_track; i++ )
1194 live_track_t *tk = p_sys->track[i];
1196 if( !tk->b_muxed && !tk->b_rtcp_sync &&
1197 tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1199 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1201 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1202 tk->b_rtcp_sync = true;
1212 if( p_sys->b_multicast && p_sys->b_no_data &&
1213 ( p_sys->i_no_data_ti > 120 ) )
1215 /* FIXME Make this configurable
1216 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1220 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1221 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1223 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1224 var_GetBool( p_demux, "rtsp-http" );
1226 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1228 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1229 if( RollOverTcp( p_demux ) )
1231 msg_Err( p_demux, "TCP rollover failed, aborting" );
1236 msg_Err( p_demux, "no data received in 10s, aborting" );
1239 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1240 ( p_sys->i_no_data_ti > 34 ) )
1243 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1246 return p_demux->b_error ? 0 : 1;
1249 /*****************************************************************************
1251 *****************************************************************************/
1252 static int Control( demux_t *p_demux, int i_query, va_list args )
1254 demux_sys_t *p_sys = p_demux->p_sys;
1262 case DEMUX_GET_TIME:
1263 pi64 = (int64_t*)va_arg( args, int64_t * );
1264 if( p_sys->i_npt > 0 )
1266 *pi64 = (int64_t)(p_sys->i_npt * 1000000.);
1269 return VLC_EGENERIC;
1271 case DEMUX_GET_LENGTH:
1272 pi64 = (int64_t*)va_arg( args, int64_t * );
1273 if( p_sys->i_npt_length > 0 )
1275 *pi64 = (int64_t)((double)p_sys->i_npt_length * 1000000.0);
1278 return VLC_EGENERIC;
1280 case DEMUX_GET_POSITION:
1281 pf = (double*)va_arg( args, double* );
1282 if( (p_sys->i_npt_length > 0) && (p_sys->i_npt > 0) )
1284 *pf = ( (double)p_sys->i_npt / (double)p_sys->i_npt_length );
1287 return VLC_EGENERIC;
1289 case DEMUX_SET_POSITION:
1290 case DEMUX_SET_TIME:
1291 if( p_sys->rtsp && (p_sys->i_npt_length > 0) )
1296 if( (i_query == DEMUX_SET_TIME) && (p_sys->i_npt > 0) )
1298 i64 = (int64_t)va_arg( args, int64_t );
1299 time = (float)((double)i64 / (double)1000000.0); /* in second */
1301 else if( i_query == DEMUX_SET_TIME )
1302 return VLC_EGENERIC;
1305 f = (double)va_arg( args, double );
1306 time = f * (double)p_sys->i_npt_length; /* in second */
1309 if( p_sys->b_paused )
1311 p_sys->f_seek_request = time;
1315 if( !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) )
1317 msg_Err( p_demux, "PAUSE before seek failed %s",
1318 p_sys->env->getResultMsg() );
1319 return VLC_EGENERIC;
1321 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, time, -1, 1 ) )
1323 msg_Err( p_demux, "seek PLAY failed %s",
1324 p_sys->env->getResultMsg() );
1325 return VLC_EGENERIC;
1329 /* Retrieve RTP-Info values */
1330 for( i = 0; i < p_sys->i_track; i++ )
1332 p_sys->track[i]->b_rtcp_sync = false;
1333 p_sys->track[i]->i_pts = 0;
1336 /* Retrieve the starttime if possible */
1337 p_sys->i_npt = p_sys->i_npt_start = p_sys->ms->playStartTime();
1339 /* Retrieve the duration if possible */
1340 if( p_sys->ms->playEndTime() > 0 )
1341 p_sys->i_npt_length = p_sys->ms->playEndTime();
1343 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1346 return VLC_EGENERIC;
1348 /* Special for access_demux */
1349 case DEMUX_CAN_PAUSE:
1350 case DEMUX_CAN_SEEK:
1351 pb = (bool*)va_arg( args, bool * );
1352 if( p_sys->rtsp && p_sys->i_npt_length > 0 )
1353 /* Not always true, but will be handled in SET_PAUSE_STATE */
1359 case DEMUX_CAN_CONTROL_PACE:
1360 pb = (bool*)va_arg( args, bool * );
1362 #if 1 /* Disable for now until we have a clock synchro algo
1363 * which works with something else than MPEG over UDP */
1370 case DEMUX_CAN_CONTROL_RATE:
1371 pb = (bool*)va_arg( args, bool * );
1372 pb2 = (bool*)va_arg( args, bool * );
1374 *pb = (p_sys->rtsp != NULL) &&
1375 (p_sys->i_npt_length > 0) &&
1376 ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1377 !var_GetBool( p_demux, "rtsp-wmserver" ) );
1381 case DEMUX_SET_RATE:
1383 double f_scale, f_old_scale;
1385 if( !p_sys->rtsp || (p_sys->i_npt_length <= 0) ||
1386 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1387 var_GetBool( p_demux, "rtsp-wmserver" ) )
1388 return VLC_EGENERIC;
1390 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1393 * "[...] should try to approximate the viewing rate, but
1394 * may restrict the range of scale values that it supports.
1395 * The response MUST contain the actual scale value chosen
1398 * Scale = 1 indicates normal play
1399 * Scale > 1 indicates fast forward
1400 * Scale < 1 && Scale > 0 indicates slow motion
1401 * Scale < 0 value indicates rewind
1404 pi_int = (int*)va_arg( args, int * );
1405 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1406 f_old_scale = p_sys->ms->scale();
1408 /* Passing -1 for the start and end time will mean liveMedia won't
1409 * create a Range: section for the RTSP message. The server should
1410 * pick up from the current position */
1411 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, -1, -1, f_scale ) )
1413 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1414 p_sys->env->getResultMsg() );
1415 return VLC_EGENERIC;
1418 if( p_sys->ms->scale() == f_old_scale )
1420 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1421 p_sys->ms->scale() );
1422 return VLC_EGENERIC;
1425 /* ReSync the stream */
1426 p_sys->i_npt_start = 0;
1430 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1431 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1435 case DEMUX_SET_PAUSE_STATE:
1437 bool b_pause = (bool)va_arg( args, int );
1438 if( p_sys->rtsp == NULL )
1439 return VLC_EGENERIC;
1441 if( b_pause == p_sys->b_paused )
1443 if( ( b_pause && !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) ) ||
1444 ( !b_pause && !p_sys->rtsp->playMediaSession( *p_sys->ms,
1445 p_sys->f_seek_request ) ) )
1447 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1448 return VLC_EGENERIC;
1450 p_sys->f_seek_request = -1;
1451 p_sys->b_paused = b_pause;
1453 /* When we Pause, we'll need the TimeoutPrevention thread to
1454 * handle sending the "Keep Alive" message to the server.
1455 * Unfortunately Live555 isn't thread safe and so can't
1456 * do this normally while the main Demux thread is handling
1457 * a live stream. We end up with the Timeout thread blocking
1458 * waiting for a response from the server. So when we PAUSE
1459 * we set a flag that the TimeoutPrevention function will check
1460 * and if it's set, it will trigger the GET_PARAMETER message */
1461 if( p_sys->b_paused && p_sys->p_timeout != NULL )
1462 p_sys->p_timeout->b_handle_keep_alive = true;
1463 else if( !p_sys->b_paused && p_sys->p_timeout != NULL )
1464 p_sys->p_timeout->b_handle_keep_alive = false;
1466 if( !p_sys->b_paused )
1468 for( int i = 0; i < p_sys->i_track; i++ )
1470 live_track_t *tk = p_sys->track[i];
1471 tk->b_rtcp_sync = false;
1474 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1478 /* Reset data received counter */
1479 p_sys->i_no_data_ti = 0;
1481 /* Retrieve the starttime if possible */
1482 p_sys->i_npt_start = p_sys->ms->playStartTime();
1484 /* Retrieve the duration if possible */
1485 if( p_sys->ms->playEndTime() )
1486 p_sys->i_npt_length = p_sys->ms->playEndTime();
1488 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1491 case DEMUX_GET_TITLE_INFO:
1492 case DEMUX_SET_TITLE:
1493 case DEMUX_SET_SEEKPOINT:
1494 return VLC_EGENERIC;
1496 case DEMUX_GET_PTS_DELAY:
1497 pi64 = (int64_t*)va_arg( args, int64_t * );
1498 *pi64 = (int64_t)var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1502 return VLC_EGENERIC;
1506 /*****************************************************************************
1507 * RollOverTcp: reopen the rtsp into TCP mode
1508 * XXX: ugly, a lot of code are duplicated from Open()
1509 * This should REALLY be fixed
1510 *****************************************************************************/
1511 static int RollOverTcp( demux_t *p_demux )
1513 demux_sys_t *p_sys = p_demux->p_sys;
1516 var_SetBool( p_demux, "rtsp-tcp", true );
1518 /* We close the old RTSP session */
1519 for( i = 0; i < p_sys->i_track; i++ )
1521 live_track_t *tk = p_sys->track[i];
1523 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
1524 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1525 es_format_Clean( &tk->fmt );
1526 free( tk->p_buffer );
1529 if( p_sys->i_track ) free( p_sys->track );
1530 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
1532 p_sys->rtsp->teardownMediaSession( *p_sys->ms );
1533 Medium::close( p_sys->ms );
1534 RTSPClient::close( p_sys->rtsp );
1538 p_sys->track = NULL;
1540 p_sys->b_no_data = true;
1541 p_sys->i_no_data_ti = 0;
1543 /* Reopen rtsp client */
1544 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1546 msg_Err( p_demux, "Failed to connect with rtsp://%s",
1551 if( p_sys->p_sdp == NULL )
1553 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1557 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1559 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1563 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1569 return VLC_EGENERIC;
1573 /*****************************************************************************
1575 *****************************************************************************/
1576 static void StreamRead( void *p_private, unsigned int i_size,
1577 unsigned int i_truncated_bytes, struct timeval pts,
1578 unsigned int duration )
1580 live_track_t *tk = (live_track_t*)p_private;
1581 demux_t *p_demux = tk->p_demux;
1582 demux_sys_t *p_sys = p_demux->p_sys;
1585 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1587 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1588 (int64_t)pts.tv_usec;
1590 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1591 i_pts &= INT64_C(0x00ffffffffffffff);
1593 /* Retrieve NPT for this pts */
1594 tk->i_npt = tk->sub->getNormalPlayTime(pts);
1596 if( tk->b_quicktime && tk->p_es == NULL )
1598 QuickTimeGenericRTPSource *qtRTPSource =
1599 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1600 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1601 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1603 if( tk->fmt.i_cat == VIDEO_ES ) {
1604 if( qtState.sdAtomSize < 16 + 32 )
1607 p_sys->event = 0xff;
1611 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1612 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1613 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1615 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1617 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1618 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1619 + qtRTPSource->qtState.sdAtomSize;
1620 while (pos+8 < endpos) {
1621 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1622 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1623 if( memcmp(pos+4, "avcC", 4) == 0 &&
1625 atomLength <= INT_MAX )
1627 tk->fmt.i_extra = atomLength-8;
1628 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1629 assert( tk->fmt.p_extra );
1630 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1638 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1639 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1640 assert( tk->fmt.p_extra );
1641 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1645 if( qtState.sdAtomSize < 4 )
1648 p_sys->event = 0xff;
1652 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1654 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1658 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1660 pts.tv_sec * 1000000LL + pts.tv_usec );
1663 /* grow buffer if it looks like buffer is too small, but don't eat
1664 * up all the memory on strange streams */
1665 if( i_truncated_bytes > 0 )
1667 if( tk->i_buffer < 2000000 )
1670 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1671 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1672 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1675 msg_Warn( p_demux, "realloc failed" );
1679 tk->p_buffer = (uint8_t*)p_tmp;
1684 if( tk->b_discard_trunc )
1686 p_sys->event = 0xff;
1692 assert( i_size <= tk->i_buffer );
1694 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1695 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1697 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1699 p_block = block_New( p_demux, i_size + 1 );
1700 p_block->p_buffer[0] = amrSource->lastFrameHeader();
1701 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1703 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1705 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1706 uint32_t header = h261Source->lastSpecialHeader();
1707 p_block = block_New( p_demux, i_size + 4 );
1708 memcpy( p_block->p_buffer, &header, 4 );
1709 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1711 if( tk->sub->rtpSource()->curPacketMarkerBit() )
1712 p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1714 else if( tk->fmt.i_codec == VLC_CODEC_H264 )
1716 if( (tk->p_buffer[0] & 0x1f) >= 24 )
1717 msg_Warn( p_demux, "unsupported NAL type for H264" );
1719 /* Normal NAL type */
1720 p_block = block_New( p_demux, i_size + 4 );
1721 p_block->p_buffer[0] = 0x00;
1722 p_block->p_buffer[1] = 0x00;
1723 p_block->p_buffer[2] = 0x00;
1724 p_block->p_buffer[3] = 0x01;
1725 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1727 else if( tk->b_asf )
1729 int i_copy = __MIN( p_sys->asfh.i_min_data_packet_size, (int)i_size );
1730 p_block = block_New( p_demux, p_sys->asfh.i_min_data_packet_size );
1732 memcpy( p_block->p_buffer, tk->p_buffer, i_copy );
1736 p_block = block_New( p_demux, i_size );
1737 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1740 if( p_sys->i_pcr < i_pts )
1742 p_sys->i_pcr = i_pts;
1745 if( (i_pts != tk->i_pts) && (!tk->b_muxed) )
1747 p_block->i_pts = i_pts;
1750 /* Update our global npt value */
1751 if( tk->i_npt > 0 && tk->i_npt > p_sys->i_npt && tk->i_npt < p_sys->i_npt_length)
1752 p_sys->i_npt = tk->i_npt;
1756 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
1757 p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? 0 : i_pts;
1762 stream_DemuxSend( tk->p_out_muxed, p_block );
1764 else if( tk->b_asf )
1766 stream_DemuxSend( p_sys->p_out_asf, p_block );
1770 es_out_Send( p_demux->out, tk->p_es, p_block );
1773 /* warn that's ok */
1774 p_sys->event = 0xff;
1776 /* we have read data */
1778 p_demux->p_sys->b_no_data = false;
1779 p_demux->p_sys->i_no_data_ti = 0;
1781 if( i_pts > 0 && !tk->b_muxed )
1787 /*****************************************************************************
1789 *****************************************************************************/
1790 static void StreamClose( void *p_private )
1792 live_track_t *tk = (live_track_t*)p_private;
1793 demux_t *p_demux = tk->p_demux;
1794 demux_sys_t *p_sys = p_demux->p_sys;
1796 msg_Dbg( p_demux, "StreamClose" );
1798 p_sys->event = 0xff;
1799 p_demux->b_error = true;
1803 /*****************************************************************************
1805 *****************************************************************************/
1806 static void TaskInterrupt( void *p_private )
1808 demux_t *p_demux = (demux_t*)p_private;
1810 p_demux->p_sys->i_no_data_ti++;
1813 p_demux->p_sys->event = 0xff;
1816 /*****************************************************************************
1818 *****************************************************************************/
1819 static void* TimeoutPrevention( void *p_data )
1821 timeout_thread_t *p_timeout = (timeout_thread_t *)p_data;
1825 /* Voodoo (= no) thread safety here! *Ahem* */
1826 if( p_timeout->b_handle_keep_alive )
1828 char *psz_bye = NULL;
1829 int canc = vlc_savecancel ();
1831 p_timeout->p_sys->rtsp->getMediaSessionParameter( *p_timeout->p_sys->ms, NULL, psz_bye );
1832 vlc_restorecancel (canc);
1834 p_timeout->p_sys->b_timeout_call = !p_timeout->b_handle_keep_alive;
1836 msleep (((int64_t)p_timeout->p_sys->i_timeout - 2) * CLOCK_FREQ);
1838 assert(0); /* dead code */
1841 /*****************************************************************************
1843 *****************************************************************************/
1844 static int ParseASF( demux_t *p_demux )
1846 demux_sys_t *p_sys = p_demux->p_sys;
1848 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1849 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1853 /* Parse the asf header */
1854 if( psz_asf == NULL )
1855 return VLC_EGENERIC;
1857 psz_asf += strlen( psz_marker );
1858 psz_asf = strdup( psz_asf ); /* Duplicate it */
1859 psz_end = strchr( psz_asf, '\n' );
1861 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1864 if( psz_asf >= psz_end )
1867 return VLC_EGENERIC;
1870 /* Always smaller */
1871 p_header = block_New( p_demux, psz_end - psz_asf );
1872 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
1873 p_header->i_buffer, psz_asf );
1874 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
1875 if( p_header->i_buffer <= 0 )
1878 return VLC_EGENERIC;
1881 /* Parse it to get packet size */
1882 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
1884 /* Send it to demuxer */
1885 stream_DemuxSend( p_sys->p_out_asf, p_header );
1892 static unsigned char* parseH264ConfigStr( char const* configStr,
1893 unsigned int& configSize )
1896 size_t i_records = 1;
1900 if( configStr == NULL || *configStr == '\0' )
1903 psz = dup = strdup( configStr );
1905 /* Count the number of commas */
1906 for( psz = dup; *psz != '\0'; ++psz )
1915 size_t configMax = 5*strlen(dup);
1916 unsigned char *cfg = new unsigned char[configMax];
1918 for( size_t i = 0; i < i_records; ++i )
1920 cfg[configSize++] = 0x00;
1921 cfg[configSize++] = 0x00;
1922 cfg[configSize++] = 0x00;
1923 cfg[configSize++] = 0x01;
1925 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
1926 configMax-configSize, psz );
1927 psz += strlen(psz)+1;