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>
55 # include <winsock2.h>
58 #include <UsageEnvironment.hh>
59 #include <BasicUsageEnvironment.hh>
60 #include <GroupsockHelper.hh>
61 #include <liveMedia.hh>
64 #include "../access/mms/asf.h" /* Who said ugly ? */
69 /*****************************************************************************
71 *****************************************************************************/
72 static int Open ( vlc_object_t * );
73 static void Close( vlc_object_t * );
75 #define CACHING_TEXT N_("Caching value (ms)")
76 #define CACHING_LONGTEXT N_( \
77 "Allows you to modify the default caching value for RTSP streams. This " \
78 "value should be set in millisecond units." )
80 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
81 #define KASENNA_LONGTEXT N_( "Kasenna servers use an old and nonstandard " \
82 "dialect of RTSP. With this parameter VLC will try this dialect, but "\
83 "then it cannot connect to normal RTSP servers." )
85 #define WMSERVER_TEXT N_("WMServer RTSP dialect")
86 #define WMSERVER_LONGTEXT N_("WMServer uses an unstandard dialect " \
87 "of RTSP. Selecting this parameter will tell VLC to assume some " \
88 "options contrary to RFC 2326 guidelines.")
90 #define USER_TEXT N_("RTSP user name")
91 #define USER_LONGTEXT N_("Sets the username for the connection, " \
92 "if no username or password are set in the url.")
93 #define PASS_TEXT N_("RTSP password")
94 #define PASS_LONGTEXT N_("Sets the password for the connection, " \
95 "if no username or password are set in the url.")
98 set_description( N_("RTP/RTSP/SDP demuxer (using Live555)" ) )
99 set_capability( "demux", 50 )
100 set_shortname( "RTP/RTSP")
101 set_callbacks( Open, Close )
102 add_shortcut( "live" )
103 add_shortcut( "livedotcom" )
104 set_category( CAT_INPUT )
105 set_subcategory( SUBCAT_INPUT_DEMUX )
108 set_description( N_("RTSP/RTP access and demux") )
109 add_shortcut( "rtsp" )
110 add_shortcut( "pnm" )
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 block_t *p_asf_block;
168 bool b_discard_trunc;
169 stream_t *p_out_muxed; /* for muxed stream */
172 unsigned int i_buffer;
181 struct timeout_thread_t
185 bool b_handle_keep_alive;
190 char *p_sdp; /* XXX mallocated */
191 char *psz_path; /* URL-encoded path */
195 TaskScheduler *scheduler;
196 UsageEnvironment *env ;
201 live_track_t **track; /* XXX mallocated */
209 int64_t i_pcr; /* The clock */
214 /* timeout thread information */
215 int i_timeout; /* session timeout value in seconds */
216 bool b_timeout_call;/* mark to send an RTSP call to prevent server timeout */
217 timeout_thread_t *p_timeout; /* the actual thread that makes sure we don't timeout */
221 bool b_multicast; /* if one of the tracks is multicasted */
222 bool b_no_data; /* if we never received any data */
223 int i_no_data_ti; /* consecutive number of TaskInterrupt */
227 bool b_get_param; /* Does the server support GET_PARAMETER */
228 bool b_paused; /* Are we paused? */
231 float f_seek_request;/* In case we receive a seek request while paused*/
234 static int Demux ( demux_t * );
235 static int Control( demux_t *, int, va_list );
237 static int Connect ( demux_t * );
238 static int SessionsSetup( demux_t * );
239 static int Play ( demux_t *);
240 static int ParseASF ( demux_t * );
241 static int RollOverTcp ( demux_t * );
243 static void StreamRead ( void *, unsigned int, unsigned int,
244 struct timeval, unsigned int );
245 static void StreamClose ( void * );
246 static void TaskInterrupt( void * );
248 static void* TimeoutPrevention( void * );
250 static unsigned char* parseH264ConfigStr( char const* configStr,
251 unsigned int& configSize );
253 /*****************************************************************************
255 *****************************************************************************/
256 static int Open ( vlc_object_t *p_this )
258 demux_t *p_demux = (demux_t*)p_this;
259 demux_sys_t *p_sys = NULL;
262 int i_error = VLC_EGENERIC;
266 /* See if it looks like a SDP
267 v, o, s fields are mandatory and in this order */
268 const uint8_t *p_peek;
269 if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
271 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
272 memcmp( p_peek, "v=0\n", 4 ) &&
273 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
278 var_Create( p_demux, "rtsp-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
280 p_demux->pf_demux = Demux;
281 p_demux->pf_control= Control;
282 p_demux->p_sys = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
283 if( !p_sys ) return VLC_ENOMEM;
286 p_sys->scheduler = NULL;
294 p_sys->i_npt_start = 0.;
295 p_sys->i_npt_length = 0.;
296 p_sys->p_out_asf = NULL;
297 p_sys->b_no_data = true;
298 p_sys->i_no_data_ti = 0;
299 p_sys->p_timeout = NULL;
300 p_sys->i_timeout = 0;
301 p_sys->b_timeout_call = false;
302 p_sys->b_multicast = false;
303 p_sys->b_real = false;
304 p_sys->psz_path = strdup( p_demux->psz_path );
305 p_sys->b_force_mcast = var_CreateGetBool( p_demux, "rtsp-mcast" );
306 p_sys->b_get_param = false;
307 p_sys->b_paused = false;
308 p_sys->f_seek_request = -1;
309 p_sys->b_error = false;
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) )
357 msg_Err( p_demux, "failed to read SDP" );
364 if( i_read < i_sdp_max - i_sdp - 1 )
371 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
373 p_sys->p_sdp = (char*)p_sdp;
375 else if( ( p_demux->s == NULL ) &&
376 !strcasecmp( p_demux->psz_access, "sdp" ) )
378 /* sdp:// link from SAP */
379 p_sys->p_sdp = strdup( p_sys->psz_path );
381 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
383 msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
387 if( p_sys->p_sdp == NULL )
389 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
390 i_error = VLC_ENOMEM;
394 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
396 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
400 if( p_sys->b_real ) goto error;
402 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
405 if( p_sys->p_out_asf && ParseASF( p_demux ) )
407 msg_Err( p_demux, "cannot find a usable asf header" );
408 /* TODO Clean tracks */
412 if( p_sys->i_track <= 0 )
422 /*****************************************************************************
424 *****************************************************************************/
425 static void Close( vlc_object_t *p_this )
427 demux_t *p_demux = (demux_t*)p_this;
428 demux_sys_t *p_sys = p_demux->p_sys;
431 for( i = 0; i < p_sys->i_track; i++ )
433 live_track_t *tk = p_sys->track[i];
435 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
436 es_format_Clean( &tk->fmt );
437 free( tk->p_buffer );
441 if( p_sys->i_track ) free( p_sys->track );
442 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
443 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->teardownMediaSession( *p_sys->ms );
444 if( p_sys->p_timeout )
446 vlc_cancel( p_sys->p_timeout->handle );
447 vlc_join( p_sys->p_timeout->handle, NULL );
448 free( p_sys->p_timeout );
450 if( p_sys->ms ) Medium::close( p_sys->ms );
451 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
452 if( p_sys->env ) p_sys->env->reclaim();
453 delete p_sys->scheduler;
454 free( p_sys->p_sdp );
455 free( p_sys->psz_path );
457 vlc_UrlClean( &p_sys->url );
462 static inline const char *strempty( const char *s ) { return s?s:""; }
463 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
465 /*****************************************************************************
466 * Connect: connects to the RTSP server to setup the session DESCRIBE
467 *****************************************************************************/
468 static int Connect( demux_t *p_demux )
470 demux_sys_t *p_sys = p_demux->p_sys;
471 Authenticator authenticator;
472 char *psz_user = NULL;
473 char *psz_pwd = NULL;
474 char *psz_url = NULL;
475 char *psz_options = NULL;
478 int i_ret = VLC_SUCCESS;
480 /* Create the url using the port number if available */
481 if( p_sys->url.i_port == 0 )
483 p_sys->url.i_port = 554;
484 if( asprintf( &psz_url, "rtsp://%s", p_sys->psz_path ) == -1 )
489 if( asprintf( &psz_url, "rtsp://%s:%d%s", p_sys->url.psz_host,
491 strempty( p_sys->url.psz_path ) ) == -1 )
495 /* Get the user name and password */
496 if( p_sys->url.psz_username || p_sys->url.psz_password )
498 psz_user = strdup( strempty( p_sys->url.psz_username ) );
499 psz_pwd = strdup( strempty( p_sys->url.psz_password ) );
503 psz_user = var_CreateGetString( p_demux, "rtsp-user" );
504 psz_pwd = var_CreateGetString( p_demux, "rtsp-pwd" );
508 if( !vlc_object_alive (p_demux) )
510 i_ret = VLC_EGENERIC;
514 if( var_CreateGetBool( p_demux, "rtsp-http" ) )
515 i_http_port = var_CreateGetInteger( p_demux, "rtsp-http-port" );
517 if( ( p_sys->rtsp = RTSPClient::createNew( *p_sys->env,
518 var_CreateGetInteger( p_demux, "verbose" ) > 1,
519 "VLC media player", i_http_port ) ) == NULL )
521 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
522 p_sys->env->getResultMsg() );
523 i_ret = VLC_EGENERIC;
527 /* Kasenna enables KeepAlive by analysing the User-Agent string.
528 * Appending _KA to the string should be enough to enable this feature,
529 * however, there is a bug where the _KA doesn't get parsed from the
530 * default User-Agent as created by VLC/Live555 code. This is probably due
531 * to spaces in the string or the string being too long. Here we override
532 * the default string with a more compact version.
534 if( var_CreateGetBool( p_demux, "rtsp-kasenna" ))
536 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
540 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
543 { /* i_timeout hack scope */
544 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1223337600
545 const int i_timeout = var_CreateGetInteger(p_demux, "ipv4-timeout") / 1000;
546 psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
547 &authenticator, i_timeout );
549 psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
552 if( psz_options == NULL && authenticator.realm() != NULL )
554 // try again, with the realm set this time
555 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1223337600
556 psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
557 &authenticator, i_timeout );
559 psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
564 p_sys->b_get_param = (bool)strstr( psz_options, "GET_PARAMETER" );
565 delete [] psz_options;
567 if( var_CreateGetBool( p_demux, "rtsp-wmserver" ) )
568 p_sys->b_get_param = true;
570 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1223337600
571 p_sdp = p_sys->rtsp->describeWithPassword( psz_url, psz_user, psz_pwd,
572 var_GetBool( p_demux, "rtsp-kasenna" ), i_timeout );
574 p_sdp = p_sys->rtsp->describeWithPassword( psz_url, psz_user, psz_pwd,
575 var_GetBool( p_demux, "rtsp-kasenna" ) );
577 } /* i_timeout scope end */
581 /* failure occurred */
583 const char *psz_error = p_sys->env->getResultMsg();
585 if( var_GetBool( p_demux, "rtsp-http" ) )
586 sscanf( psz_error, "%*s %*s HTTP GET %*s HTTP/%*u.%*u %3u %*s",
590 const char *psz_tmp = strstr( psz_error, "RTSP" );
592 sscanf( psz_tmp, "RTSP/%*s%3u", &i_code );
596 msg_Dbg( p_demux, "DESCRIBE failed with %d: %s", i_code, psz_error );
600 msg_Dbg( p_demux, "authentication failed" );
604 dialog_Login( p_demux, &psz_user, &psz_pwd,
605 _("RTSP authentication"), "%s",
606 _("Please enter a valid login name and a password.") );
607 if( psz_user != NULL && psz_pwd != NULL )
609 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
613 else if( (i_code != 0) && !var_GetBool( p_demux, "rtsp-http" ) )
615 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
616 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
617 var_SetBool( p_demux, "rtsp-http", true );
618 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
624 msg_Dbg( p_demux, "connection timeout" );
625 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
628 i_ret = VLC_EGENERIC;
631 free( p_sys->p_sdp );
633 if( p_sdp ) p_sys->p_sdp = strdup( (char*)p_sdp );
637 /* malloc-ated copy */
645 /*****************************************************************************
646 * SessionsSetup: prepares the subsessions and does the SETUP
647 *****************************************************************************/
648 static int SessionsSetup( demux_t *p_demux )
650 demux_sys_t *p_sys = p_demux->p_sys;
651 MediaSubsessionIterator *iter = NULL;
652 MediaSubsession *sub = NULL;
654 bool b_rtsp_tcp = false;
656 int i_return = VLC_SUCCESS;
657 unsigned int i_buffer = 0;
658 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
660 b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
661 var_GetBool( p_demux, "rtsp-http" );
662 i_client_port = var_CreateGetInteger( p_demux, "rtp-client-port" );
664 /* Create the session from the SDP */
665 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
667 msg_Err( p_demux, "Could not create the RTSP Session: %s",
668 p_sys->env->getResultMsg() );
672 /* Initialise each media subsession */
673 iter = new MediaSubsessionIterator( *p_sys->ms );
674 while( ( sub = iter->next() ) != NULL )
679 if( !vlc_object_alive (p_demux) )
685 /* Value taken from mplayer */
686 if( !strcmp( sub->mediumName(), "audio" ) )
688 else if( !strcmp( sub->mediumName(), "video" ) )
690 else if( !strcmp( sub->mediumName(), "text" ) )
694 if( i_client_port != -1 )
696 sub->setClientPortNum( i_client_port );
700 if( strcasestr( sub->codecName(), "REAL" ) )
702 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
703 p_sys->b_real = true; /* This is a problem, we'll handle it later */
707 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
708 bInit = sub->initiate( 0 );
710 bInit = sub->initiate();
714 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
715 sub->mediumName(), sub->codecName(),
716 p_sys->env->getResultMsg() );
720 if( sub->rtpSource() != NULL )
722 int fd = sub->rtpSource()->RTPgs()->socketNum();
724 /* Increase the buffer size */
726 increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
728 /* Increase the RTP reorder timebuffer just a bit */
729 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
731 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
734 /* Issue the SETUP */
737 if( !p_sys->rtsp->setupMediaSubsession( *sub, False,
738 toBool( b_rtsp_tcp ),
739 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) ) )
741 /* if we get an unsupported transport error, toggle TCP
742 * use and try again */
743 if( !strstr(p_sys->env->getResultMsg(),
744 "461 Unsupported Transport")
745 || !p_sys->rtsp->setupMediaSubsession( *sub, False,
746 toBool( b_rtsp_tcp ), False ) )
748 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
749 sub->mediumName(), sub->codecName(),
750 p_sys->env->getResultMsg() );
756 /* Check if we will receive data from this subsession for
758 if( sub->readSource() == NULL ) continue;
759 if( !p_sys->b_multicast )
761 /* We need different rollover behaviour for multicast */
762 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
765 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
771 tk->p_demux = p_demux;
774 tk->b_quicktime = false;
776 tk->p_asf_block = NULL;
778 tk->b_discard_trunc = false;
779 tk->p_out_muxed = NULL;
781 tk->b_rtcp_sync = false;
782 tk->i_pts = VLC_TS_INVALID;
784 tk->i_buffer = 65536;
785 tk->p_buffer = (uint8_t *)malloc( 65536 );
793 /* Value taken from mplayer */
794 if( !strcmp( sub->mediumName(), "audio" ) )
796 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
797 tk->fmt.audio.i_channels = sub->numChannels();
798 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
800 if( !strcmp( sub->codecName(), "MPA" ) ||
801 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
802 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
804 tk->fmt.i_codec = VLC_CODEC_MPGA;
805 tk->fmt.audio.i_rate = 0;
807 else if( !strcmp( sub->codecName(), "AC3" ) )
809 tk->fmt.i_codec = VLC_CODEC_A52;
810 tk->fmt.audio.i_rate = 0;
812 else if( !strcmp( sub->codecName(), "L16" ) )
814 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
815 tk->fmt.audio.i_bitspersample = 16;
817 else if( !strcmp( sub->codecName(), "L8" ) )
819 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
820 tk->fmt.audio.i_bitspersample = 8;
822 else if( !strcmp( sub->codecName(), "PCMU" ) )
824 tk->fmt.i_codec = VLC_CODEC_MULAW;
826 else if( !strcmp( sub->codecName(), "PCMA" ) )
828 tk->fmt.i_codec = VLC_CODEC_ALAW;
830 else if( !strncmp( sub->codecName(), "G726", 4 ) )
832 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
833 tk->fmt.audio.i_rate = 8000;
834 tk->fmt.audio.i_channels = 1;
835 if( !strcmp( sub->codecName()+5, "40" ) )
836 tk->fmt.i_bitrate = 40000;
837 else if( !strcmp( sub->codecName()+5, "32" ) )
838 tk->fmt.i_bitrate = 32000;
839 else if( !strcmp( sub->codecName()+5, "24" ) )
840 tk->fmt.i_bitrate = 24000;
841 else if( !strcmp( sub->codecName()+5, "16" ) )
842 tk->fmt.i_bitrate = 16000;
844 else if( !strcmp( sub->codecName(), "AMR" ) )
846 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
848 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
850 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
852 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
854 unsigned int i_extra;
857 tk->fmt.i_codec = VLC_CODEC_MP4A;
859 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
862 tk->fmt.i_extra = i_extra;
863 tk->fmt.p_extra = xmalloc( i_extra );
864 memcpy( tk->fmt.p_extra, p_extra, i_extra );
867 /* Because the "faad" decoder does not handle the LATM
868 * data length field at the start of each returned LATM
869 * frame, tell the RTP source to omit it. */
870 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
872 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
874 unsigned int i_extra;
877 tk->fmt.i_codec = VLC_CODEC_MP4A;
879 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
882 tk->fmt.i_extra = i_extra;
883 tk->fmt.p_extra = xmalloc( i_extra );
884 memcpy( tk->fmt.p_extra, p_extra, i_extra );
888 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
891 if( p_sys->p_out_asf == NULL )
892 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
895 else if( !strcmp( sub->codecName(), "X-QT" ) ||
896 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
898 tk->b_quicktime = true;
900 else if( !strcmp( sub->codecName(), "SPEEX" ) )
902 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
903 if ( sub->rtpTimestampFrequency() )
904 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
907 msg_Warn( p_demux,"Using 8kHz as default sample rate." );
908 tk->fmt.audio.i_rate = 8000;
912 else if( !strcmp( sub->mediumName(), "video" ) )
914 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
915 if( !strcmp( sub->codecName(), "MPV" ) )
917 tk->fmt.i_codec = VLC_CODEC_MPGV;
919 else if( !strcmp( sub->codecName(), "H263" ) ||
920 !strcmp( sub->codecName(), "H263-1998" ) ||
921 !strcmp( sub->codecName(), "H263-2000" ) )
923 tk->fmt.i_codec = VLC_CODEC_H263;
925 else if( !strcmp( sub->codecName(), "H261" ) )
927 tk->fmt.i_codec = VLC_CODEC_H261;
929 else if( !strcmp( sub->codecName(), "H264" ) )
931 unsigned int i_extra = 0;
932 uint8_t *p_extra = NULL;
934 tk->fmt.i_codec = VLC_CODEC_H264;
935 tk->fmt.b_packetized = false;
937 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
940 tk->fmt.i_extra = i_extra;
941 tk->fmt.p_extra = xmalloc( i_extra );
942 memcpy( tk->fmt.p_extra, p_extra, i_extra );
947 else if( !strcmp( sub->codecName(), "JPEG" ) )
949 tk->fmt.i_codec = VLC_CODEC_MJPG;
951 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
953 unsigned int i_extra;
956 tk->fmt.i_codec = VLC_CODEC_MP4V;
958 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
961 tk->fmt.i_extra = i_extra;
962 tk->fmt.p_extra = xmalloc( i_extra );
963 memcpy( tk->fmt.p_extra, p_extra, i_extra );
967 else if( !strcmp( sub->codecName(), "X-QT" ) ||
968 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
969 !strcmp( sub->codecName(), "X-QDM" ) ||
970 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
971 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
973 tk->b_quicktime = true;
975 else if( !strcmp( sub->codecName(), "MP2T" ) )
978 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
980 else if( !strcmp( sub->codecName(), "MP2P" ) ||
981 !strcmp( sub->codecName(), "MP1S" ) )
984 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
987 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
990 if( p_sys->p_out_asf == NULL )
991 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
994 else if( !strcmp( sub->codecName(), "DV" ) )
997 tk->b_discard_trunc = true;
998 tk->p_out_muxed = stream_DemuxNew( p_demux, "rawdv",
1002 else if( !strcmp( sub->mediumName(), "text" ) )
1004 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1006 if( !strcmp( sub->codecName(), "T140" ) )
1008 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1012 if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
1014 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1017 if( sub->rtcpInstance() != NULL )
1019 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1022 if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
1025 p_sys->track = (live_track_t**)xrealloc( p_sys->track,
1026 sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
1027 p_sys->track[p_sys->i_track++] = tk;
1032 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1033 es_format_Clean( &tk->fmt );
1039 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1041 /* Retrieve the starttime if possible */
1042 p_sys->i_npt_start = p_sys->ms->playStartTime();
1044 /* Retrieve the duration if possible */
1045 p_sys->i_npt_length = p_sys->ms->playEndTime();
1048 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1051 p_sys->b_no_data = true;
1052 p_sys->i_no_data_ti = 0;
1057 /*****************************************************************************
1058 * Play: starts the actual playback of the stream
1059 *****************************************************************************/
1060 static int Play( demux_t *p_demux )
1062 demux_sys_t *p_sys = p_demux->p_sys;
1067 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, p_sys->i_npt_start, -1, 1 ) )
1069 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1070 return VLC_EGENERIC;
1073 /* Retrieve the timeout value and set up a timeout prevention thread */
1074 p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
1075 if( p_sys->i_timeout <= 0 )
1076 p_sys->i_timeout = 60; /* default value from RFC2326 */
1078 /* start timeout-thread only if GET_PARAMETER is supported by the server */
1079 if( !p_sys->p_timeout && p_sys->b_get_param )
1081 msg_Dbg( p_demux, "We have a timeout of %d seconds", p_sys->i_timeout );
1082 p_sys->p_timeout = (timeout_thread_t *)malloc( sizeof(timeout_thread_t) );
1083 if( p_sys->p_timeout )
1085 memset( p_sys->p_timeout, 0, sizeof(timeout_thread_t) );
1086 p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
1087 if( vlc_clone( &p_sys->p_timeout->handle, TimeoutPrevention,
1088 p_sys->p_timeout, VLC_THREAD_PRIORITY_LOW ) )
1090 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1091 free( p_sys->p_timeout );
1092 p_sys->p_timeout = NULL;
1095 msg_Dbg( p_demux, "spawned timeout thread" );
1098 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1103 /* Retrieve the starttime if possible */
1104 p_sys->i_npt_start = p_sys->ms->playStartTime();
1105 if( p_sys->ms->playEndTime() > 0 )
1106 p_sys->i_npt_length = p_sys->ms->playEndTime();
1108 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1113 /*****************************************************************************
1115 *****************************************************************************/
1116 static int Demux( demux_t *p_demux )
1118 demux_sys_t *p_sys = p_demux->p_sys;
1121 bool b_send_pcr = true;
1125 /* Check if we need to send the server a Keep-A-Live signal */
1126 if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
1128 char *psz_bye = NULL;
1129 p_sys->rtsp->getMediaSessionParameter( *p_sys->ms, NULL, psz_bye );
1130 p_sys->b_timeout_call = false;
1133 for( i = 0; i < p_sys->i_track; i++ )
1135 live_track_t *tk = p_sys->track[i];
1137 if( tk->b_asf || tk->b_muxed )
1144 else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
1150 if( p_sys->i_pcr > 0 )
1153 es_out_Control( p_demux->out, ES_OUT_SET_PCR, 1 + p_sys->i_pcr );
1156 /* First warn we want to read data */
1158 for( i = 0; i < p_sys->i_track; i++ )
1160 live_track_t *tk = p_sys->track[i];
1162 if( tk->waiting == 0 )
1165 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1166 StreamRead, tk, StreamClose, tk );
1169 /* Create a task that will be called if we wait more than 300ms */
1170 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
1173 p_sys->scheduler->doEventLoop( &p_sys->event );
1175 /* remove the task */
1176 p_sys->scheduler->unscheduleDelayedTask( task );
1178 /* Check for gap in pts value */
1179 for( i = 0; i < p_sys->i_track; i++ )
1181 live_track_t *tk = p_sys->track[i];
1183 if( !tk->b_muxed && !tk->b_rtcp_sync &&
1184 tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1186 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1188 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1189 tk->b_rtcp_sync = true;
1191 tk->i_pts = VLC_TS_INVALID;
1199 if( p_sys->b_multicast && p_sys->b_no_data &&
1200 ( p_sys->i_no_data_ti > 120 ) )
1202 /* FIXME Make this configurable
1203 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1207 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1208 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1210 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1211 var_GetBool( p_demux, "rtsp-http" );
1213 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1215 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1216 if( RollOverTcp( p_demux ) )
1218 msg_Err( p_demux, "TCP rollover failed, aborting" );
1223 msg_Err( p_demux, "no data received in 10s, aborting" );
1226 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1227 ( p_sys->i_no_data_ti > 34 ) )
1230 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1233 return p_sys->b_error ? 0 : 1;
1236 /*****************************************************************************
1238 *****************************************************************************/
1239 static int Control( demux_t *p_demux, int i_query, va_list args )
1241 demux_sys_t *p_sys = p_demux->p_sys;
1249 case DEMUX_GET_TIME:
1250 pi64 = (int64_t*)va_arg( args, int64_t * );
1251 if( p_sys->i_npt > 0 )
1253 *pi64 = (int64_t)(p_sys->i_npt * 1000000.);
1256 return VLC_EGENERIC;
1258 case DEMUX_GET_LENGTH:
1259 pi64 = (int64_t*)va_arg( args, int64_t * );
1260 if( p_sys->i_npt_length > 0 )
1262 *pi64 = (int64_t)((double)p_sys->i_npt_length * 1000000.0);
1265 return VLC_EGENERIC;
1267 case DEMUX_GET_POSITION:
1268 pf = (double*)va_arg( args, double* );
1269 if( (p_sys->i_npt_length > 0) && (p_sys->i_npt > 0) )
1271 *pf = ( (double)p_sys->i_npt / (double)p_sys->i_npt_length );
1274 return VLC_EGENERIC;
1276 case DEMUX_SET_POSITION:
1277 case DEMUX_SET_TIME:
1278 if( p_sys->rtsp && (p_sys->i_npt_length > 0) )
1283 if( (i_query == DEMUX_SET_TIME) && (p_sys->i_npt > 0) )
1285 i64 = (int64_t)va_arg( args, int64_t );
1286 time = (float)((double)i64 / (double)1000000.0); /* in second */
1288 else if( i_query == DEMUX_SET_TIME )
1289 return VLC_EGENERIC;
1292 f = (double)va_arg( args, double );
1293 time = f * (double)p_sys->i_npt_length; /* in second */
1296 if( p_sys->b_paused )
1298 p_sys->f_seek_request = time;
1302 if( !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) )
1304 msg_Err( p_demux, "PAUSE before seek failed %s",
1305 p_sys->env->getResultMsg() );
1306 return VLC_EGENERIC;
1308 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, time, -1, 1 ) )
1310 msg_Err( p_demux, "seek PLAY failed %s",
1311 p_sys->env->getResultMsg() );
1312 return VLC_EGENERIC;
1316 /* Retrieve RTP-Info values */
1317 for( i = 0; i < p_sys->i_track; i++ )
1319 p_sys->track[i]->b_rtcp_sync = false;
1320 p_sys->track[i]->i_pts = VLC_TS_INVALID;
1323 /* Retrieve the starttime if possible */
1324 p_sys->i_npt = p_sys->i_npt_start = p_sys->ms->playStartTime();
1326 /* Retrieve the duration if possible */
1327 if( p_sys->ms->playEndTime() > 0 )
1328 p_sys->i_npt_length = p_sys->ms->playEndTime();
1330 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1333 return VLC_EGENERIC;
1335 /* Special for access_demux */
1336 case DEMUX_CAN_PAUSE:
1337 case DEMUX_CAN_SEEK:
1338 pb = (bool*)va_arg( args, bool * );
1339 if( p_sys->rtsp && p_sys->i_npt_length > 0 )
1340 /* Not always true, but will be handled in SET_PAUSE_STATE */
1346 case DEMUX_CAN_CONTROL_PACE:
1347 pb = (bool*)va_arg( args, bool * );
1349 #if 1 /* Disable for now until we have a clock synchro algo
1350 * which works with something else than MPEG over UDP */
1357 case DEMUX_CAN_CONTROL_RATE:
1358 pb = (bool*)va_arg( args, bool * );
1359 pb2 = (bool*)va_arg( args, bool * );
1361 *pb = (p_sys->rtsp != NULL) &&
1362 (p_sys->i_npt_length > 0) &&
1363 ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1364 !var_GetBool( p_demux, "rtsp-wmserver" ) );
1368 case DEMUX_SET_RATE:
1370 double f_scale, f_old_scale;
1372 if( !p_sys->rtsp || (p_sys->i_npt_length <= 0) ||
1373 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1374 var_GetBool( p_demux, "rtsp-wmserver" ) )
1375 return VLC_EGENERIC;
1377 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1380 * "[...] should try to approximate the viewing rate, but
1381 * may restrict the range of scale values that it supports.
1382 * The response MUST contain the actual scale value chosen
1385 * Scale = 1 indicates normal play
1386 * Scale > 1 indicates fast forward
1387 * Scale < 1 && Scale > 0 indicates slow motion
1388 * Scale < 0 value indicates rewind
1391 pi_int = (int*)va_arg( args, int * );
1392 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1393 f_old_scale = p_sys->ms->scale();
1395 /* Passing -1 for the start and end time will mean liveMedia won't
1396 * create a Range: section for the RTSP message. The server should
1397 * pick up from the current position */
1398 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, -1, -1, f_scale ) )
1400 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1401 p_sys->env->getResultMsg() );
1402 return VLC_EGENERIC;
1405 if( p_sys->ms->scale() == f_old_scale )
1407 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1408 p_sys->ms->scale() );
1409 return VLC_EGENERIC;
1412 /* ReSync the stream */
1413 p_sys->i_npt_start = 0;
1417 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1418 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1422 case DEMUX_SET_PAUSE_STATE:
1424 bool b_pause = (bool)va_arg( args, int );
1425 if( p_sys->rtsp == NULL )
1426 return VLC_EGENERIC;
1428 if( b_pause == p_sys->b_paused )
1430 if( ( b_pause && !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) ) ||
1431 ( !b_pause && !p_sys->rtsp->playMediaSession( *p_sys->ms,
1432 p_sys->f_seek_request, -1.0f, p_sys->ms->scale() ) ) )
1434 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1435 return VLC_EGENERIC;
1437 p_sys->f_seek_request = -1;
1438 p_sys->b_paused = b_pause;
1440 /* When we Pause, we'll need the TimeoutPrevention thread to
1441 * handle sending the "Keep Alive" message to the server.
1442 * Unfortunately Live555 isn't thread safe and so can't
1443 * do this normally while the main Demux thread is handling
1444 * a live stream. We end up with the Timeout thread blocking
1445 * waiting for a response from the server. So when we PAUSE
1446 * we set a flag that the TimeoutPrevention function will check
1447 * and if it's set, it will trigger the GET_PARAMETER message */
1448 if( p_sys->b_paused && p_sys->p_timeout != NULL )
1449 p_sys->p_timeout->b_handle_keep_alive = true;
1450 else if( !p_sys->b_paused && p_sys->p_timeout != NULL )
1451 p_sys->p_timeout->b_handle_keep_alive = false;
1453 if( !p_sys->b_paused )
1455 for( int i = 0; i < p_sys->i_track; i++ )
1457 live_track_t *tk = p_sys->track[i];
1458 tk->b_rtcp_sync = false;
1459 tk->i_pts = VLC_TS_INVALID;
1461 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1465 /* Reset data received counter */
1466 p_sys->i_no_data_ti = 0;
1468 /* Retrieve the starttime if possible */
1469 p_sys->i_npt_start = p_sys->ms->playStartTime();
1471 /* Retrieve the duration if possible */
1472 if( p_sys->ms->playEndTime() )
1473 p_sys->i_npt_length = p_sys->ms->playEndTime();
1475 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1478 case DEMUX_GET_TITLE_INFO:
1479 case DEMUX_SET_TITLE:
1480 case DEMUX_SET_SEEKPOINT:
1481 return VLC_EGENERIC;
1483 case DEMUX_GET_PTS_DELAY:
1484 pi64 = (int64_t*)va_arg( args, int64_t * );
1485 *pi64 = (int64_t)var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1489 return VLC_EGENERIC;
1493 /*****************************************************************************
1494 * RollOverTcp: reopen the rtsp into TCP mode
1495 * XXX: ugly, a lot of code are duplicated from Open()
1496 * This should REALLY be fixed
1497 *****************************************************************************/
1498 static int RollOverTcp( demux_t *p_demux )
1500 demux_sys_t *p_sys = p_demux->p_sys;
1503 var_SetBool( p_demux, "rtsp-tcp", true );
1505 /* We close the old RTSP session */
1506 for( i = 0; i < p_sys->i_track; i++ )
1508 live_track_t *tk = p_sys->track[i];
1510 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
1511 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1512 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1513 es_format_Clean( &tk->fmt );
1514 free( tk->p_buffer );
1517 if( p_sys->i_track ) free( p_sys->track );
1518 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
1520 p_sys->rtsp->teardownMediaSession( *p_sys->ms );
1521 Medium::close( p_sys->ms );
1522 RTSPClient::close( p_sys->rtsp );
1526 p_sys->track = NULL;
1528 p_sys->b_no_data = true;
1529 p_sys->i_no_data_ti = 0;
1530 p_sys->p_out_asf = NULL;
1532 /* Reopen rtsp client */
1533 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1535 msg_Err( p_demux, "Failed to connect with rtsp://%s",
1540 if( p_sys->p_sdp == NULL )
1542 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1546 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1548 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1552 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1558 return VLC_EGENERIC;
1562 /*****************************************************************************
1564 *****************************************************************************/
1565 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1567 const uint8_t *p_data, unsigned i_size )
1569 const unsigned i_packet_size = p_demux->p_sys->asfh.i_min_data_packet_size;
1570 block_t *p_list = NULL;
1572 while( i_size >= 4 )
1574 unsigned i_flags = p_data[0];
1575 unsigned i_length_offset = (p_data[1] << 16) |
1578 bool b_key = i_flags & 0x80;
1579 bool b_length = i_flags & 0x40;
1580 bool b_relative_ts = i_flags & 0x20;
1581 bool b_duration = i_flags & 0x10;
1582 bool b_location_id = i_flags & 0x08;
1584 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1585 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1586 unsigned i_header_size = 4;
1594 if( i_header_size > i_size )
1596 msg_Warn( p_demux, "Invalid header size" );
1601 * When b_length is true, the streams I found do not seems to respect
1602 * the documentation.
1603 * From them, I have failed to find which choice between '__MIN()' or
1604 * 'i_length_offset - i_header_size' is the right one.
1608 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1610 i_payload = i_size - i_header_size;
1612 if( !tk->p_asf_block )
1614 tk->p_asf_block = block_New( p_demux, i_packet_size );
1615 if( !tk->p_asf_block )
1617 tk->p_asf_block->i_buffer = 0;
1619 unsigned i_offset = b_length ? 0 : i_length_offset;
1620 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1622 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1623 tk->p_asf_block->i_buffer += i_payload;
1626 /* We have a complete packet */
1627 tk->p_asf_block->i_buffer = i_packet_size;
1628 block_ChainAppend( &p_list, tk->p_asf_block );
1629 tk->p_asf_block = NULL;
1634 /* Reset on broken stream */
1635 msg_Err( p_demux, "Broken packet detected (%d vs %d or %d + %d vs %d)",
1636 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1637 tk->p_asf_block->i_buffer = 0;
1641 p_data += i_header_size + i_payload;
1642 i_size -= i_header_size + i_payload;
1647 /*****************************************************************************
1649 *****************************************************************************/
1650 static void StreamRead( void *p_private, unsigned int i_size,
1651 unsigned int i_truncated_bytes, struct timeval pts,
1652 unsigned int duration )
1654 live_track_t *tk = (live_track_t*)p_private;
1655 demux_t *p_demux = tk->p_demux;
1656 demux_sys_t *p_sys = p_demux->p_sys;
1659 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1661 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1662 (int64_t)pts.tv_usec;
1664 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1665 i_pts &= INT64_C(0x00ffffffffffffff);
1667 /* Retrieve NPT for this pts */
1668 tk->i_npt = tk->sub->getNormalPlayTime(pts);
1670 if( tk->b_quicktime && tk->p_es == NULL )
1672 QuickTimeGenericRTPSource *qtRTPSource =
1673 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1674 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1675 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1677 if( tk->fmt.i_cat == VIDEO_ES ) {
1678 if( qtState.sdAtomSize < 16 + 32 )
1681 p_sys->event = 0xff;
1685 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1686 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1687 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1689 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1691 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1692 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1693 + qtRTPSource->qtState.sdAtomSize;
1694 while (pos+8 < endpos) {
1695 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1696 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1697 if( memcmp(pos+4, "avcC", 4) == 0 &&
1699 atomLength <= INT_MAX )
1701 tk->fmt.i_extra = atomLength-8;
1702 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1703 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1711 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1712 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1713 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1717 if( qtState.sdAtomSize < 4 )
1720 p_sys->event = 0xff;
1724 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1726 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1730 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1732 pts.tv_sec * 1000000LL + pts.tv_usec );
1735 /* grow buffer if it looks like buffer is too small, but don't eat
1736 * up all the memory on strange streams */
1737 if( i_truncated_bytes > 0 )
1739 if( tk->i_buffer < 2000000 )
1742 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1743 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1744 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1747 msg_Warn( p_demux, "realloc failed" );
1751 tk->p_buffer = (uint8_t*)p_tmp;
1756 if( tk->b_discard_trunc )
1758 p_sys->event = 0xff;
1764 assert( i_size <= tk->i_buffer );
1766 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1767 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1769 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1771 p_block = block_New( p_demux, i_size + 1 );
1772 p_block->p_buffer[0] = amrSource->lastFrameHeader();
1773 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1775 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1777 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1778 uint32_t header = h261Source->lastSpecialHeader();
1779 p_block = block_New( p_demux, i_size + 4 );
1780 memcpy( p_block->p_buffer, &header, 4 );
1781 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1783 if( tk->sub->rtpSource()->curPacketMarkerBit() )
1784 p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1786 else if( tk->fmt.i_codec == VLC_CODEC_H264 )
1788 if( (tk->p_buffer[0] & 0x1f) >= 24 )
1789 msg_Warn( p_demux, "unsupported NAL type for H264" );
1791 /* Normal NAL type */
1792 p_block = block_New( p_demux, i_size + 4 );
1793 p_block->p_buffer[0] = 0x00;
1794 p_block->p_buffer[1] = 0x00;
1795 p_block->p_buffer[2] = 0x00;
1796 p_block->p_buffer[3] = 0x01;
1797 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1799 else if( tk->b_asf )
1801 p_block = StreamParseAsf( p_demux, tk,
1802 tk->sub->rtpSource()->curPacketMarkerBit(),
1803 tk->p_buffer, i_size );
1807 p_block = block_New( p_demux, i_size );
1808 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1811 if( p_sys->i_pcr < i_pts )
1813 p_sys->i_pcr = i_pts;
1816 /* Update our global npt value */
1817 if( tk->i_npt > 0 && tk->i_npt > p_sys->i_npt && tk->i_npt < p_sys->i_npt_length)
1818 p_sys->i_npt = tk->i_npt;
1822 if( !tk->b_muxed && !tk->b_asf )
1824 if( i_pts != tk->i_pts )
1825 p_block->i_pts = VLC_TS_0 + i_pts;
1826 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
1827 p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? VLC_TS_INVALID : (VLC_TS_0 + i_pts);
1831 stream_DemuxSend( tk->p_out_muxed, p_block );
1832 else if( tk->b_asf )
1833 stream_DemuxSend( p_sys->p_out_asf, p_block );
1835 es_out_Send( p_demux->out, tk->p_es, p_block );
1838 /* warn that's ok */
1839 p_sys->event = 0xff;
1841 /* we have read data */
1843 p_demux->p_sys->b_no_data = false;
1844 p_demux->p_sys->i_no_data_ti = 0;
1846 if( i_pts > 0 && !tk->b_muxed )
1852 /*****************************************************************************
1854 *****************************************************************************/
1855 static void StreamClose( void *p_private )
1857 live_track_t *tk = (live_track_t*)p_private;
1858 demux_t *p_demux = tk->p_demux;
1859 demux_sys_t *p_sys = p_demux->p_sys;
1861 msg_Dbg( p_demux, "StreamClose" );
1863 p_sys->event = 0xff;
1864 p_sys->b_error = true;
1868 /*****************************************************************************
1870 *****************************************************************************/
1871 static void TaskInterrupt( void *p_private )
1873 demux_t *p_demux = (demux_t*)p_private;
1875 p_demux->p_sys->i_no_data_ti++;
1878 p_demux->p_sys->event = 0xff;
1881 /*****************************************************************************
1883 *****************************************************************************/
1884 static void* TimeoutPrevention( void *p_data )
1886 timeout_thread_t *p_timeout = (timeout_thread_t *)p_data;
1890 /* Voodoo (= no) thread safety here! *Ahem* */
1891 if( p_timeout->b_handle_keep_alive )
1893 char *psz_bye = NULL;
1894 int canc = vlc_savecancel ();
1896 p_timeout->p_sys->rtsp->getMediaSessionParameter( *p_timeout->p_sys->ms, NULL, psz_bye );
1897 vlc_restorecancel (canc);
1899 p_timeout->p_sys->b_timeout_call = !p_timeout->b_handle_keep_alive;
1901 msleep (((int64_t)p_timeout->p_sys->i_timeout - 2) * CLOCK_FREQ);
1903 assert(0); /* dead code */
1906 /*****************************************************************************
1908 *****************************************************************************/
1909 static int ParseASF( demux_t *p_demux )
1911 demux_sys_t *p_sys = p_demux->p_sys;
1913 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1914 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1918 /* Parse the asf header */
1919 if( psz_asf == NULL )
1920 return VLC_EGENERIC;
1922 psz_asf += strlen( psz_marker );
1923 psz_asf = strdup( psz_asf ); /* Duplicate it */
1924 psz_end = strchr( psz_asf, '\n' );
1926 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1929 if( psz_asf >= psz_end )
1932 return VLC_EGENERIC;
1935 /* Always smaller */
1936 p_header = block_New( p_demux, psz_end - psz_asf );
1937 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
1938 p_header->i_buffer, psz_asf );
1939 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
1940 if( p_header->i_buffer <= 0 )
1943 return VLC_EGENERIC;
1946 /* Parse it to get packet size */
1947 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
1949 /* Send it to demuxer */
1950 stream_DemuxSend( p_sys->p_out_asf, p_header );
1957 static unsigned char* parseH264ConfigStr( char const* configStr,
1958 unsigned int& configSize )
1961 size_t i_records = 1;
1965 if( configStr == NULL || *configStr == '\0' )
1968 psz = dup = strdup( configStr );
1970 /* Count the number of commas */
1971 for( psz = dup; *psz != '\0'; ++psz )
1980 size_t configMax = 5*strlen(dup);
1981 unsigned char *cfg = new unsigned char[configMax];
1983 for( size_t i = 0; i < i_records; ++i )
1985 cfg[configSize++] = 0x00;
1986 cfg[configSize++] = 0x00;
1987 cfg[configSize++] = 0x00;
1988 cfg[configSize++] = 0x01;
1990 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
1991 configMax-configSize, psz );
1992 psz += strlen(psz)+1;