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
10 * Sébastien Escudier <sebastien-devel celeos eu>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
32 * Note: config.h may include inttypes.h, so make sure we define this option
34 #define __STDC_CONSTANT_MACROS 1
42 #include <vlc_common.h>
43 #include <vlc_plugin.h>
44 #include <vlc_input.h>
45 #include <vlc_demux.h>
46 #include <vlc_dialog.h>
48 #include <vlc_strings.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", "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", "pnm", "sdp", "live", "livedotcom" )
110 set_capability( "access_demux", 0 )
111 set_callbacks( Open, Close )
112 add_bool( "rtsp-tcp", false, NULL,
113 N_("Use RTP over RTSP (TCP)"),
114 N_("Use RTP over RTSP (TCP)"), true )
116 add_integer( "rtp-client-port", -1, NULL,
118 N_("Port to use for the RTP source of the session"), true )
119 add_bool( "rtsp-mcast", false, NULL,
120 N_("Force multicast RTP via RTSP"),
121 N_("Force multicast RTP via RTSP"), true )
123 add_bool( "rtsp-http", false, NULL,
124 N_("Tunnel RTSP and RTP over HTTP"),
125 N_("Tunnel RTSP and RTP over HTTP"), true )
127 add_integer( "rtsp-http-port", 80, NULL,
128 N_("HTTP tunnel port"),
129 N_("Port to use for tunneling the RTSP/RTP over HTTP."),
131 add_integer("rtsp-caching", 4 * DEFAULT_PTS_DELAY / 1000, NULL,
132 CACHING_TEXT, CACHING_LONGTEXT, true )
134 add_bool( "rtsp-kasenna", false, NULL, KASENNA_TEXT,
135 KASENNA_LONGTEXT, true )
137 add_bool( "rtsp-wmserver", false, NULL, WMSERVER_TEXT,
138 WMSERVER_LONGTEXT, true)
140 add_string( "rtsp-user", NULL, NULL, USER_TEXT,
141 USER_LONGTEXT, true )
143 add_password( "rtsp-pwd", NULL, NULL, PASS_TEXT,
144 PASS_LONGTEXT, true )
149 /*****************************************************************************
151 *****************************************************************************/
156 MediaSubsession *sub;
164 block_t *p_asf_block;
165 bool b_discard_trunc;
166 stream_t *p_out_muxed; /* for muxed stream */
169 unsigned int i_buffer;
178 struct timeout_thread_t
182 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 int i_live555_ret; /* live555 callback return code */
231 float f_seek_request;/* In case we receive a seek request while paused*/
235 class RTSPClientVlc : public RTSPClient
238 RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
239 char const* applicationName, portNumBits tunnelOverHTTPPortNum,
240 demux_sys_t *p_sys) :
241 RTSPClient( env, rtspURL, verbosityLevel, applicationName,
242 tunnelOverHTTPPortNum )
249 static int Demux ( demux_t * );
250 static int Control( demux_t *, int, va_list );
252 static int Connect ( demux_t * );
253 static int SessionsSetup( demux_t * );
254 static int Play ( demux_t *);
255 static int ParseASF ( demux_t * );
256 static int RollOverTcp ( demux_t * );
258 static void StreamRead ( void *, unsigned int, unsigned int,
259 struct timeval, unsigned int );
260 static void StreamClose ( void * );
261 static void TaskInterrupt( void * );
263 static void* TimeoutPrevention( void * );
265 static unsigned char* parseH264ConfigStr( char const* configStr,
266 unsigned int& configSize );
268 /*****************************************************************************
270 *****************************************************************************/
271 static int Open ( vlc_object_t *p_this )
273 demux_t *p_demux = (demux_t*)p_this;
274 demux_sys_t *p_sys = NULL;
277 int i_error = VLC_EGENERIC;
281 /* See if it looks like a SDP
282 v, o, s fields are mandatory and in this order */
283 const uint8_t *p_peek;
284 if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
286 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
287 memcmp( p_peek, "v=0\n", 4 ) &&
288 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
293 var_Create( p_demux, "rtsp-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
295 p_demux->pf_demux = Demux;
296 p_demux->pf_control= Control;
297 p_demux->p_sys = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
298 if( !p_sys ) return VLC_ENOMEM;
301 p_sys->scheduler = NULL;
309 p_sys->i_npt_start = 0.;
310 p_sys->i_npt_length = 0.;
311 p_sys->p_out_asf = NULL;
312 p_sys->b_no_data = true;
313 p_sys->i_no_data_ti = 0;
314 p_sys->p_timeout = NULL;
315 p_sys->i_timeout = 0;
316 p_sys->b_timeout_call = false;
317 p_sys->b_multicast = false;
318 p_sys->b_real = false;
319 p_sys->psz_path = strdup( p_demux->psz_location );
320 p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
321 p_sys->b_get_param = false;
322 p_sys->b_paused = false;
323 p_sys->f_seek_request = -1;
324 p_sys->b_error = false;
325 p_sys->i_live555_ret = 0;
327 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
328 vlc_UrlParse( &p_sys->url, p_sys->psz_path, 0 );
330 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
332 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
335 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
337 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
341 if( strcasecmp( p_demux->psz_access, "sdp" ) )
343 char *p = p_sys->psz_path;
344 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
347 if( p_demux->s != NULL )
349 /* Gather the complete sdp file */
351 int i_sdp_max = 1000;
352 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
356 i_error = VLC_ENOMEM;
362 int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
363 i_sdp_max - i_sdp - 1 );
365 if( !vlc_object_alive (p_demux) )
373 msg_Err( p_demux, "failed to read SDP" );
380 if( i_read < i_sdp_max - i_sdp - 1 )
387 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
389 p_sys->p_sdp = (char*)p_sdp;
391 else if( ( p_demux->s == NULL ) &&
392 !strcasecmp( p_demux->psz_access, "sdp" ) )
394 /* sdp:// link from SAP */
395 p_sys->p_sdp = strdup( p_sys->psz_path );
397 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
399 msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
403 if( p_sys->p_sdp == NULL )
405 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
406 i_error = VLC_ENOMEM;
410 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
412 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
416 if( p_sys->b_real ) goto error;
418 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
421 if( p_sys->p_out_asf && ParseASF( p_demux ) )
423 msg_Err( p_demux, "cannot find a usable asf header" );
424 /* TODO Clean tracks */
428 if( p_sys->i_track <= 0 )
438 /*****************************************************************************
440 *****************************************************************************/
441 static void Close( vlc_object_t *p_this )
443 demux_t *p_demux = (demux_t*)p_this;
444 demux_sys_t *p_sys = p_demux->p_sys;
446 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
447 if( p_sys->ms ) Medium::close( p_sys->ms );
448 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
449 if( p_sys->env ) p_sys->env->reclaim();
451 for( int i = 0; i < p_sys->i_track; i++ )
453 live_track_t *tk = p_sys->track[i];
455 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
456 es_format_Clean( &tk->fmt );
457 free( tk->p_buffer );
461 if( p_sys->i_track ) free( p_sys->track );
462 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
463 if( p_sys->p_timeout )
465 vlc_cancel( p_sys->p_timeout->handle );
466 vlc_join( p_sys->p_timeout->handle, NULL );
467 free( p_sys->p_timeout );
469 delete p_sys->scheduler;
470 free( p_sys->p_sdp );
471 free( p_sys->psz_path );
473 vlc_UrlClean( &p_sys->url );
478 static inline const char *strempty( const char *s ) { return s?s:""; }
479 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
481 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
483 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
484 demux_sys_t *p_sys = client_vlc->p_sys;
485 delete []result_string;
486 p_sys->i_live555_ret = result_code;
487 p_sys->b_error = p_sys->i_live555_ret != 0;
491 /* return true if the RTSP command succeeded */
492 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
495 demux_sys_t * p_sys = p_demux->p_sys;
499 /* Create a task that will be called if we wait more than timeout ms */
500 task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000, TaskInterrupt,
504 p_sys->b_error = true;
505 p_sys->i_live555_ret = 0;
506 p_sys->scheduler->doEventLoop( &p_sys->event );
507 //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
510 /* remove the task */
511 p_sys->scheduler->unscheduleDelayedTask( task );
513 return !p_sys->b_error;
516 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
517 char* result_string )
519 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
520 demux_sys_t *p_sys = client_vlc->p_sys;
521 char* sdpDescription = result_string;
522 p_sys->i_live555_ret = result_code;
523 if ( result_code != 0 )
525 delete[] sdpDescription;
528 free( p_sys->p_sdp );
532 p_sys->p_sdp = strdup( sdpDescription );
533 delete[] sdpDescription;
535 p_sys->b_error = false;
539 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
540 char* result_string )
542 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
543 demux_sys_t *p_sys = client_vlc->p_sys;
544 p_sys->i_live555_ret = result_code;
545 if ( result_code != 0 )
547 p_sys->b_error = true;
552 p_sys->b_get_param = (bool)strstr( result_string, "GET_PARAMETER" );
553 client->sendDescribeCommand( continueAfterDESCRIBE );
555 delete[] result_string;
558 /*****************************************************************************
559 * Connect: connects to the RTSP server to setup the session DESCRIBE
560 *****************************************************************************/
561 static int Connect( demux_t *p_demux )
563 demux_sys_t *p_sys = p_demux->p_sys;
564 Authenticator authenticator;
565 char *psz_user = NULL;
566 char *psz_pwd = NULL;
567 char *psz_url = NULL;
568 char *psz_options = NULL;
571 int i_ret = VLC_SUCCESS;
572 const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
574 /* Get the user name and password */
575 if( p_sys->url.psz_username || p_sys->url.psz_password )
577 /* Create the URL by stripping away the username/password part */
578 if( p_sys->url.i_port == 0 )
579 p_sys->url.i_port = 554;
580 if( asprintf( &psz_url, "rtsp://%s:%d%s",
581 strempty( p_sys->url.psz_host ),
583 strempty( p_sys->url.psz_path ) ) == -1 )
586 psz_user = strdup( strempty( p_sys->url.psz_username ) );
587 psz_pwd = strdup( strempty( p_sys->url.psz_password ) );
591 if( asprintf( &psz_url, "rtsp://%s", p_sys->psz_path ) == -1 )
594 psz_user = var_InheritString( p_demux, "rtsp-user" );
595 psz_pwd = var_InheritString( p_demux, "rtsp-pwd" );
599 if( !vlc_object_alive (p_demux) )
601 i_ret = VLC_EGENERIC;
605 if( var_InheritBool( p_demux, "rtsp-http" ) )
606 i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
608 p_sys->rtsp = new RTSPClientVlc( *p_sys->env, psz_url,
609 var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
610 "LibVLC/"VERSION, i_http_port, p_sys );
613 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
614 p_sys->env->getResultMsg() );
615 i_ret = VLC_EGENERIC;
619 /* Kasenna enables KeepAlive by analysing the User-Agent string.
620 * Appending _KA to the string should be enough to enable this feature,
621 * however, there is a bug where the _KA doesn't get parsed from the
622 * default User-Agent as created by VLC/Live555 code. This is probably due
623 * to spaces in the string or the string being too long. Here we override
624 * the default string with a more compact version.
626 if( var_InheritBool( p_demux, "rtsp-kasenna" ))
628 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
632 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
634 p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
636 if( !wait_Live555_response( p_demux, i_timeout ) )
638 int i_code = p_sys->i_live555_ret;
641 msg_Dbg( p_demux, "authentication failed" );
645 dialog_Login( p_demux, &psz_user, &psz_pwd,
646 _("RTSP authentication"), "%s",
647 _("Please enter a valid login name and a password.") );
648 if( psz_user != NULL && psz_pwd != NULL )
650 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
654 else if( (i_code > 0) && !var_GetBool( p_demux, "rtsp-http" ) )
656 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
657 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
658 var_SetBool( p_demux, "rtsp-http", true );
659 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
666 msg_Dbg( p_demux, "connection timeout" );
667 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
670 i_ret = VLC_EGENERIC;
674 /* malloc-ated copy */
682 /*****************************************************************************
683 * SessionsSetup: prepares the subsessions and does the SETUP
684 *****************************************************************************/
685 static int SessionsSetup( demux_t *p_demux )
687 demux_sys_t *p_sys = p_demux->p_sys;
688 MediaSubsessionIterator *iter = NULL;
689 MediaSubsession *sub = NULL;
691 bool b_rtsp_tcp = false;
693 int i_return = VLC_SUCCESS;
694 unsigned int i_buffer = 0;
695 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
697 b_rtsp_tcp = var_InheritBool( p_demux, "rtsp-tcp" ) ||
698 var_InheritBool( p_demux, "rtsp-http" );
699 i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
701 /* Create the session from the SDP */
702 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
704 msg_Err( p_demux, "Could not create the RTSP Session: %s",
705 p_sys->env->getResultMsg() );
709 /* Initialise each media subsession */
710 iter = new MediaSubsessionIterator( *p_sys->ms );
711 while( ( sub = iter->next() ) != NULL )
716 if( !vlc_object_alive (p_demux) )
722 /* Value taken from mplayer */
723 if( !strcmp( sub->mediumName(), "audio" ) )
725 else if( !strcmp( sub->mediumName(), "video" ) )
727 else if( !strcmp( sub->mediumName(), "text" ) )
731 if( i_client_port != -1 )
733 sub->setClientPortNum( i_client_port );
737 if( strcasestr( sub->codecName(), "REAL" ) )
739 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
740 p_sys->b_real = true; /* This is a problem, we'll handle it later */
744 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
745 bInit = sub->initiate( 0 );
747 bInit = sub->initiate();
751 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
752 sub->mediumName(), sub->codecName(),
753 p_sys->env->getResultMsg() );
757 if( sub->rtpSource() != NULL )
759 int fd = sub->rtpSource()->RTPgs()->socketNum();
761 /* Increase the buffer size */
763 increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
765 /* Increase the RTP reorder timebuffer just a bit */
766 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
768 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
771 /* Issue the SETUP */
774 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
775 toBool( b_rtsp_tcp ),
776 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
777 if( !wait_Live555_response( p_demux ) )
779 /* if we get an unsupported transport error, toggle TCP
780 * use and try again */
781 if( p_sys->i_live555_ret == 461 )
782 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
783 toBool( b_rtsp_tcp ), False );
784 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
786 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
787 sub->mediumName(), sub->codecName(),
788 p_sys->env->getResultMsg() );
794 /* Check if we will receive data from this subsession for
796 if( sub->readSource() == NULL ) continue;
797 if( !p_sys->b_multicast )
799 /* We need different rollover behaviour for multicast */
800 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
803 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
809 tk->p_demux = p_demux;
812 tk->b_quicktime = false;
814 tk->p_asf_block = NULL;
816 tk->b_discard_trunc = false;
817 tk->p_out_muxed = NULL;
819 tk->b_rtcp_sync = false;
820 tk->i_pts = VLC_TS_INVALID;
822 tk->i_buffer = 65536;
823 tk->p_buffer = (uint8_t *)malloc( 65536 );
831 /* Value taken from mplayer */
832 if( !strcmp( sub->mediumName(), "audio" ) )
834 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
835 tk->fmt.audio.i_channels = sub->numChannels();
836 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
838 if( !strcmp( sub->codecName(), "MPA" ) ||
839 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
840 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
842 tk->fmt.i_codec = VLC_CODEC_MPGA;
843 tk->fmt.audio.i_rate = 0;
845 else if( !strcmp( sub->codecName(), "AC3" ) )
847 tk->fmt.i_codec = VLC_CODEC_A52;
848 tk->fmt.audio.i_rate = 0;
850 else if( !strcmp( sub->codecName(), "L16" ) )
852 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
853 tk->fmt.audio.i_bitspersample = 16;
855 else if( !strcmp( sub->codecName(), "L8" ) )
857 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
858 tk->fmt.audio.i_bitspersample = 8;
860 else if( !strcmp( sub->codecName(), "PCMU" ) )
862 tk->fmt.i_codec = VLC_CODEC_MULAW;
864 else if( !strcmp( sub->codecName(), "PCMA" ) )
866 tk->fmt.i_codec = VLC_CODEC_ALAW;
868 else if( !strncmp( sub->codecName(), "G726", 4 ) )
870 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
871 tk->fmt.audio.i_rate = 8000;
872 tk->fmt.audio.i_channels = 1;
873 if( !strcmp( sub->codecName()+5, "40" ) )
874 tk->fmt.i_bitrate = 40000;
875 else if( !strcmp( sub->codecName()+5, "32" ) )
876 tk->fmt.i_bitrate = 32000;
877 else if( !strcmp( sub->codecName()+5, "24" ) )
878 tk->fmt.i_bitrate = 24000;
879 else if( !strcmp( sub->codecName()+5, "16" ) )
880 tk->fmt.i_bitrate = 16000;
882 else if( !strcmp( sub->codecName(), "AMR" ) )
884 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
886 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
888 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
890 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
892 unsigned int i_extra;
895 tk->fmt.i_codec = VLC_CODEC_MP4A;
897 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
900 tk->fmt.i_extra = i_extra;
901 tk->fmt.p_extra = xmalloc( i_extra );
902 memcpy( tk->fmt.p_extra, p_extra, i_extra );
905 /* Because the "faad" decoder does not handle the LATM
906 * data length field at the start of each returned LATM
907 * frame, tell the RTP source to omit it. */
908 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
910 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
912 unsigned int i_extra;
915 tk->fmt.i_codec = VLC_CODEC_MP4A;
917 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
920 tk->fmt.i_extra = i_extra;
921 tk->fmt.p_extra = xmalloc( i_extra );
922 memcpy( tk->fmt.p_extra, p_extra, i_extra );
926 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
929 if( p_sys->p_out_asf == NULL )
930 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
933 else if( !strcmp( sub->codecName(), "X-QT" ) ||
934 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
936 tk->b_quicktime = true;
938 else if( !strcmp( sub->codecName(), "SPEEX" ) )
940 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
941 if ( sub->rtpTimestampFrequency() )
942 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
945 msg_Warn( p_demux,"Using 8kHz as default sample rate." );
946 tk->fmt.audio.i_rate = 8000;
950 else if( !strcmp( sub->mediumName(), "video" ) )
952 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
953 if( !strcmp( sub->codecName(), "MPV" ) )
955 tk->fmt.i_codec = VLC_CODEC_MPGV;
956 tk->fmt.b_packetized = false;
958 else if( !strcmp( sub->codecName(), "H263" ) ||
959 !strcmp( sub->codecName(), "H263-1998" ) ||
960 !strcmp( sub->codecName(), "H263-2000" ) )
962 tk->fmt.i_codec = VLC_CODEC_H263;
964 else if( !strcmp( sub->codecName(), "H261" ) )
966 tk->fmt.i_codec = VLC_CODEC_H261;
968 else if( !strcmp( sub->codecName(), "H264" ) )
970 unsigned int i_extra = 0;
971 uint8_t *p_extra = NULL;
973 tk->fmt.i_codec = VLC_CODEC_H264;
974 tk->fmt.b_packetized = false;
976 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
979 tk->fmt.i_extra = i_extra;
980 tk->fmt.p_extra = xmalloc( i_extra );
981 memcpy( tk->fmt.p_extra, p_extra, i_extra );
986 else if( !strcmp( sub->codecName(), "JPEG" ) )
988 tk->fmt.i_codec = VLC_CODEC_MJPG;
990 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
992 unsigned int i_extra;
995 tk->fmt.i_codec = VLC_CODEC_MP4V;
997 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1000 tk->fmt.i_extra = i_extra;
1001 tk->fmt.p_extra = xmalloc( i_extra );
1002 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1006 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1007 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1008 !strcmp( sub->codecName(), "X-QDM" ) ||
1009 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1010 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1012 tk->b_quicktime = true;
1014 else if( !strcmp( sub->codecName(), "MP2T" ) )
1017 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
1019 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1020 !strcmp( sub->codecName(), "MP1S" ) )
1023 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
1026 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1029 if( p_sys->p_out_asf == NULL )
1030 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
1033 else if( !strcmp( sub->codecName(), "DV" ) )
1036 tk->b_discard_trunc = true;
1037 tk->p_out_muxed = stream_DemuxNew( p_demux, "rawdv",
1041 else if( !strcmp( sub->mediumName(), "text" ) )
1043 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1045 if( !strcmp( sub->codecName(), "T140" ) )
1047 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1051 if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
1053 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1056 if( sub->rtcpInstance() != NULL )
1058 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1061 if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
1064 p_sys->track = (live_track_t**)xrealloc( p_sys->track,
1065 sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
1066 p_sys->track[p_sys->i_track++] = tk;
1071 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1072 es_format_Clean( &tk->fmt );
1078 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1080 /* Retrieve the starttime if possible */
1081 p_sys->i_npt_start = p_sys->ms->playStartTime();
1083 /* Retrieve the duration if possible */
1084 p_sys->i_npt_length = p_sys->ms->playEndTime();
1087 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1090 p_sys->b_no_data = true;
1091 p_sys->i_no_data_ti = 0;
1096 /*****************************************************************************
1097 * Play: starts the actual playback of the stream
1098 *****************************************************************************/
1099 static int Play( demux_t *p_demux )
1101 demux_sys_t *p_sys = p_demux->p_sys;
1106 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->i_npt_start, -1, 1 );
1108 if( !wait_Live555_response(p_demux) )
1110 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1111 return VLC_EGENERIC;
1114 /* Retrieve the timeout value and set up a timeout prevention thread */
1115 p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
1116 if( p_sys->i_timeout <= 0 )
1117 p_sys->i_timeout = 60; /* default value from RFC2326 */
1119 /* start timeout-thread only if GET_PARAMETER is supported by the server */
1120 if( !p_sys->p_timeout && p_sys->b_get_param )
1122 msg_Dbg( p_demux, "We have a timeout of %d seconds", p_sys->i_timeout );
1123 p_sys->p_timeout = (timeout_thread_t *)malloc( sizeof(timeout_thread_t) );
1124 if( p_sys->p_timeout )
1126 memset( p_sys->p_timeout, 0, sizeof(timeout_thread_t) );
1127 p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
1128 if( vlc_clone( &p_sys->p_timeout->handle, TimeoutPrevention,
1129 p_sys->p_timeout, VLC_THREAD_PRIORITY_LOW ) )
1131 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1132 free( p_sys->p_timeout );
1133 p_sys->p_timeout = NULL;
1136 msg_Dbg( p_demux, "spawned timeout thread" );
1139 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1144 /* Retrieve the starttime if possible */
1145 p_sys->i_npt_start = p_sys->ms->playStartTime();
1146 if( p_sys->ms->playEndTime() > 0 )
1147 p_sys->i_npt_length = p_sys->ms->playEndTime();
1149 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1154 /*****************************************************************************
1156 *****************************************************************************/
1157 static int Demux( demux_t *p_demux )
1159 demux_sys_t *p_sys = p_demux->p_sys;
1162 bool b_send_pcr = true;
1166 /* Check if we need to send the server a Keep-A-Live signal */
1167 if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
1169 char *psz_bye = NULL;
1170 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms, NULL, psz_bye );
1171 p_sys->b_timeout_call = false;
1174 for( i = 0; i < p_sys->i_track; i++ )
1176 live_track_t *tk = p_sys->track[i];
1178 if( tk->b_asf || tk->b_muxed )
1185 else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
1191 if( p_sys->i_pcr > 0 )
1194 es_out_Control( p_demux->out, ES_OUT_SET_PCR, 1 + p_sys->i_pcr );
1197 /* First warn we want to read data */
1199 for( i = 0; i < p_sys->i_track; i++ )
1201 live_track_t *tk = p_sys->track[i];
1203 if( tk->waiting == 0 )
1206 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1207 StreamRead, tk, StreamClose, tk );
1210 /* Create a task that will be called if we wait more than 300ms */
1211 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
1214 p_sys->scheduler->doEventLoop( &p_sys->event );
1216 /* remove the task */
1217 p_sys->scheduler->unscheduleDelayedTask( task );
1219 /* Check for gap in pts value */
1220 for( i = 0; i < p_sys->i_track; i++ )
1222 live_track_t *tk = p_sys->track[i];
1224 if( !tk->b_muxed && !tk->b_rtcp_sync &&
1225 tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1227 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1229 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1230 tk->b_rtcp_sync = true;
1232 tk->i_pts = VLC_TS_INVALID;
1240 if( p_sys->b_multicast && p_sys->b_no_data &&
1241 ( p_sys->i_no_data_ti > 120 ) )
1243 /* FIXME Make this configurable
1244 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1248 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1249 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1251 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1252 var_GetBool( p_demux, "rtsp-http" );
1254 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1256 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1257 if( RollOverTcp( p_demux ) )
1259 msg_Err( p_demux, "TCP rollover failed, aborting" );
1264 msg_Err( p_demux, "no data received in 10s, aborting" );
1267 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1268 ( p_sys->i_no_data_ti > 34 ) )
1271 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1274 return p_sys->b_error ? 0 : 1;
1277 /*****************************************************************************
1279 *****************************************************************************/
1280 static int Control( demux_t *p_demux, int i_query, va_list args )
1282 demux_sys_t *p_sys = p_demux->p_sys;
1290 case DEMUX_GET_TIME:
1291 pi64 = (int64_t*)va_arg( args, int64_t * );
1292 if( p_sys->i_npt > 0 )
1294 *pi64 = (int64_t)(p_sys->i_npt * 1000000.);
1297 return VLC_EGENERIC;
1299 case DEMUX_GET_LENGTH:
1300 pi64 = (int64_t*)va_arg( args, int64_t * );
1301 if( p_sys->i_npt_length > 0 )
1303 *pi64 = (int64_t)((double)p_sys->i_npt_length * 1000000.0);
1306 return VLC_EGENERIC;
1308 case DEMUX_GET_POSITION:
1309 pf = (double*)va_arg( args, double* );
1310 if( (p_sys->i_npt_length > 0) && (p_sys->i_npt > 0) )
1312 *pf = ( (double)p_sys->i_npt / (double)p_sys->i_npt_length );
1315 return VLC_EGENERIC;
1317 case DEMUX_SET_POSITION:
1318 case DEMUX_SET_TIME:
1319 if( p_sys->rtsp && (p_sys->i_npt_length > 0) )
1324 if( (i_query == DEMUX_SET_TIME) && (p_sys->i_npt > 0) )
1326 i64 = (int64_t)va_arg( args, int64_t );
1327 time = (float)((double)i64 / (double)1000000.0); /* in second */
1329 else if( i_query == DEMUX_SET_TIME )
1330 return VLC_EGENERIC;
1333 f = (double)va_arg( args, double );
1334 time = f * (double)p_sys->i_npt_length; /* in second */
1337 if( p_sys->b_paused )
1339 p_sys->f_seek_request = time;
1343 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1345 if( !wait_Live555_response( p_demux ) )
1347 msg_Err( p_demux, "PAUSE before seek failed %s",
1348 p_sys->env->getResultMsg() );
1349 return VLC_EGENERIC;
1352 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1354 if( !wait_Live555_response( p_demux ) )
1356 msg_Err( p_demux, "seek PLAY failed %s",
1357 p_sys->env->getResultMsg() );
1358 return VLC_EGENERIC;
1362 /* Retrieve RTP-Info values */
1363 for( i = 0; i < p_sys->i_track; i++ )
1365 p_sys->track[i]->b_rtcp_sync = false;
1366 p_sys->track[i]->i_pts = VLC_TS_INVALID;
1369 /* Retrieve the starttime if possible */
1370 p_sys->i_npt = p_sys->i_npt_start = p_sys->ms->playStartTime();
1372 /* Retrieve the duration if possible */
1373 if( p_sys->ms->playEndTime() > 0 )
1374 p_sys->i_npt_length = p_sys->ms->playEndTime();
1376 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1379 return VLC_EGENERIC;
1381 /* Special for access_demux */
1382 case DEMUX_CAN_PAUSE:
1383 case DEMUX_CAN_SEEK:
1384 pb = (bool*)va_arg( args, bool * );
1385 if( p_sys->rtsp && p_sys->i_npt_length > 0 )
1386 /* Not always true, but will be handled in SET_PAUSE_STATE */
1392 case DEMUX_CAN_CONTROL_PACE:
1393 pb = (bool*)va_arg( args, bool * );
1395 #if 1 /* Disable for now until we have a clock synchro algo
1396 * which works with something else than MPEG over UDP */
1403 case DEMUX_CAN_CONTROL_RATE:
1404 pb = (bool*)va_arg( args, bool * );
1405 pb2 = (bool*)va_arg( args, bool * );
1407 *pb = (p_sys->rtsp != NULL) &&
1408 (p_sys->i_npt_length > 0) &&
1409 ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1410 !var_GetBool( p_demux, "rtsp-wmserver" ) );
1414 case DEMUX_SET_RATE:
1416 double f_scale, f_old_scale;
1418 if( !p_sys->rtsp || (p_sys->i_npt_length <= 0) ||
1419 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1420 var_GetBool( p_demux, "rtsp-wmserver" ) )
1421 return VLC_EGENERIC;
1423 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1426 * "[...] should try to approximate the viewing rate, but
1427 * may restrict the range of scale values that it supports.
1428 * The response MUST contain the actual scale value chosen
1431 * Scale = 1 indicates normal play
1432 * Scale > 1 indicates fast forward
1433 * Scale < 1 && Scale > 0 indicates slow motion
1434 * Scale < 0 value indicates rewind
1437 pi_int = (int*)va_arg( args, int * );
1438 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1439 f_old_scale = p_sys->ms->scale();
1441 /* Passing -1 for the start and end time will mean liveMedia won't
1442 * create a Range: section for the RTSP message. The server should
1443 * pick up from the current position */
1444 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1446 if( !wait_Live555_response( p_demux ) )
1448 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1449 p_sys->env->getResultMsg() );
1450 return VLC_EGENERIC;
1453 if( p_sys->ms->scale() == f_old_scale )
1455 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1456 p_sys->ms->scale() );
1457 return VLC_EGENERIC;
1460 /* ReSync the stream */
1461 p_sys->i_npt_start = 0;
1465 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1466 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1470 case DEMUX_SET_PAUSE_STATE:
1472 bool b_pause = (bool)va_arg( args, int );
1473 if( p_sys->rtsp == NULL )
1474 return VLC_EGENERIC;
1476 if( b_pause == p_sys->b_paused )
1479 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1481 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1482 -1.0f, p_sys->ms->scale() );
1484 if( !wait_Live555_response( p_demux ) )
1486 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1487 return VLC_EGENERIC;
1489 p_sys->f_seek_request = -1;
1490 p_sys->b_paused = b_pause;
1492 /* When we Pause, we'll need the TimeoutPrevention thread to
1493 * handle sending the "Keep Alive" message to the server.
1494 * Unfortunately Live555 isn't thread safe and so can't
1495 * do this normally while the main Demux thread is handling
1496 * a live stream. We end up with the Timeout thread blocking
1497 * waiting for a response from the server. So when we PAUSE
1498 * we set a flag that the TimeoutPrevention function will check
1499 * and if it's set, it will trigger the GET_PARAMETER message */
1500 if( p_sys->b_paused && p_sys->p_timeout != NULL )
1501 p_sys->p_timeout->b_handle_keep_alive = true;
1502 else if( !p_sys->b_paused && p_sys->p_timeout != NULL )
1503 p_sys->p_timeout->b_handle_keep_alive = false;
1505 if( !p_sys->b_paused )
1507 for( int i = 0; i < p_sys->i_track; i++ )
1509 live_track_t *tk = p_sys->track[i];
1510 tk->b_rtcp_sync = false;
1511 tk->i_pts = VLC_TS_INVALID;
1513 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1517 /* Reset data received counter */
1518 p_sys->i_no_data_ti = 0;
1520 /* Retrieve the starttime if possible */
1521 p_sys->i_npt_start = p_sys->ms->playStartTime();
1523 /* Retrieve the duration if possible */
1524 if( p_sys->ms->playEndTime() )
1525 p_sys->i_npt_length = p_sys->ms->playEndTime();
1527 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1530 case DEMUX_GET_TITLE_INFO:
1531 case DEMUX_SET_TITLE:
1532 case DEMUX_SET_SEEKPOINT:
1533 return VLC_EGENERIC;
1535 case DEMUX_GET_PTS_DELAY:
1536 pi64 = (int64_t*)va_arg( args, int64_t * );
1537 *pi64 = var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1541 return VLC_EGENERIC;
1545 /*****************************************************************************
1546 * RollOverTcp: reopen the rtsp into TCP mode
1547 * XXX: ugly, a lot of code are duplicated from Open()
1548 * This should REALLY be fixed
1549 *****************************************************************************/
1550 static int RollOverTcp( demux_t *p_demux )
1552 demux_sys_t *p_sys = p_demux->p_sys;
1555 var_SetBool( p_demux, "rtsp-tcp", true );
1557 /* We close the old RTSP session */
1558 for( i = 0; i < p_sys->i_track; i++ )
1560 live_track_t *tk = p_sys->track[i];
1562 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
1563 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1564 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1565 es_format_Clean( &tk->fmt );
1566 free( tk->p_buffer );
1569 if( p_sys->i_track ) free( p_sys->track );
1570 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
1572 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1573 Medium::close( p_sys->ms );
1574 RTSPClient::close( p_sys->rtsp );
1578 p_sys->track = NULL;
1580 p_sys->b_no_data = true;
1581 p_sys->i_no_data_ti = 0;
1582 p_sys->p_out_asf = NULL;
1584 /* Reopen rtsp client */
1585 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1587 msg_Err( p_demux, "Failed to connect with rtsp://%s",
1592 if( p_sys->p_sdp == NULL )
1594 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1598 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1600 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1604 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1610 return VLC_EGENERIC;
1614 /*****************************************************************************
1616 *****************************************************************************/
1617 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1619 const uint8_t *p_data, unsigned i_size )
1621 const unsigned i_packet_size = p_demux->p_sys->asfh.i_min_data_packet_size;
1622 block_t *p_list = NULL;
1624 while( i_size >= 4 )
1626 unsigned i_flags = p_data[0];
1627 unsigned i_length_offset = (p_data[1] << 16) |
1630 bool b_key = i_flags & 0x80;
1631 bool b_length = i_flags & 0x40;
1632 bool b_relative_ts = i_flags & 0x20;
1633 bool b_duration = i_flags & 0x10;
1634 bool b_location_id = i_flags & 0x08;
1636 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1637 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1638 unsigned i_header_size = 4;
1646 if( i_header_size > i_size )
1648 msg_Warn( p_demux, "Invalid header size" );
1653 * When b_length is true, the streams I found do not seems to respect
1654 * the documentation.
1655 * From them, I have failed to find which choice between '__MIN()' or
1656 * 'i_length_offset - i_header_size' is the right one.
1660 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1662 i_payload = i_size - i_header_size;
1664 if( !tk->p_asf_block )
1666 tk->p_asf_block = block_New( p_demux, i_packet_size );
1667 if( !tk->p_asf_block )
1669 tk->p_asf_block->i_buffer = 0;
1671 unsigned i_offset = b_length ? 0 : i_length_offset;
1672 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1674 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1675 tk->p_asf_block->i_buffer += i_payload;
1678 /* We have a complete packet */
1679 tk->p_asf_block->i_buffer = i_packet_size;
1680 block_ChainAppend( &p_list, tk->p_asf_block );
1681 tk->p_asf_block = NULL;
1686 /* Reset on broken stream */
1687 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1688 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1689 tk->p_asf_block->i_buffer = 0;
1693 p_data += i_header_size + i_payload;
1694 i_size -= i_header_size + i_payload;
1699 /*****************************************************************************
1701 *****************************************************************************/
1702 static void StreamRead( void *p_private, unsigned int i_size,
1703 unsigned int i_truncated_bytes, struct timeval pts,
1704 unsigned int duration )
1706 live_track_t *tk = (live_track_t*)p_private;
1707 demux_t *p_demux = tk->p_demux;
1708 demux_sys_t *p_sys = p_demux->p_sys;
1711 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1713 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1714 (int64_t)pts.tv_usec;
1716 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1717 i_pts &= INT64_C(0x00ffffffffffffff);
1719 /* Retrieve NPT for this pts */
1720 tk->i_npt = tk->sub->getNormalPlayTime(pts);
1722 if( tk->b_quicktime && tk->p_es == NULL )
1724 QuickTimeGenericRTPSource *qtRTPSource =
1725 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1726 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1727 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1729 if( tk->fmt.i_cat == VIDEO_ES ) {
1730 if( qtState.sdAtomSize < 16 + 32 )
1733 p_sys->event = 0xff;
1737 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1738 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1739 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1741 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1743 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1744 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1745 + qtRTPSource->qtState.sdAtomSize;
1746 while (pos+8 < endpos) {
1747 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1748 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1749 if( memcmp(pos+4, "avcC", 4) == 0 &&
1751 atomLength <= INT_MAX )
1753 tk->fmt.i_extra = atomLength-8;
1754 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1755 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1763 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1764 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1765 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1769 if( qtState.sdAtomSize < 4 )
1772 p_sys->event = 0xff;
1776 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1778 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1782 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1784 pts.tv_sec * 1000000LL + pts.tv_usec );
1787 /* grow buffer if it looks like buffer is too small, but don't eat
1788 * up all the memory on strange streams */
1789 if( i_truncated_bytes > 0 )
1791 if( tk->i_buffer < 2000000 )
1794 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1795 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1796 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1799 msg_Warn( p_demux, "realloc failed" );
1803 tk->p_buffer = (uint8_t*)p_tmp;
1808 if( tk->b_discard_trunc )
1810 p_sys->event = 0xff;
1816 assert( i_size <= tk->i_buffer );
1818 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1819 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1821 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1823 p_block = block_New( p_demux, i_size + 1 );
1824 p_block->p_buffer[0] = amrSource->lastFrameHeader();
1825 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1827 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1829 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1830 uint32_t header = h261Source->lastSpecialHeader();
1831 p_block = block_New( p_demux, i_size + 4 );
1832 memcpy( p_block->p_buffer, &header, 4 );
1833 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1835 if( tk->sub->rtpSource()->curPacketMarkerBit() )
1836 p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1838 else if( tk->fmt.i_codec == VLC_CODEC_H264 )
1840 if( (tk->p_buffer[0] & 0x1f) >= 24 )
1841 msg_Warn( p_demux, "unsupported NAL type for H264" );
1843 /* Normal NAL type */
1844 p_block = block_New( p_demux, i_size + 4 );
1845 p_block->p_buffer[0] = 0x00;
1846 p_block->p_buffer[1] = 0x00;
1847 p_block->p_buffer[2] = 0x00;
1848 p_block->p_buffer[3] = 0x01;
1849 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1851 else if( tk->b_asf )
1853 p_block = StreamParseAsf( p_demux, tk,
1854 tk->sub->rtpSource()->curPacketMarkerBit(),
1855 tk->p_buffer, i_size );
1859 p_block = block_New( p_demux, i_size );
1860 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1863 if( p_sys->i_pcr < i_pts )
1865 p_sys->i_pcr = i_pts;
1868 /* Update our global npt value */
1869 if( tk->i_npt > 0 && tk->i_npt > p_sys->i_npt && tk->i_npt < p_sys->i_npt_length)
1870 p_sys->i_npt = tk->i_npt;
1874 if( !tk->b_muxed && !tk->b_asf )
1876 if( i_pts != tk->i_pts )
1877 p_block->i_pts = VLC_TS_0 + i_pts;
1878 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
1879 p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? VLC_TS_INVALID : (VLC_TS_0 + i_pts);
1883 stream_DemuxSend( tk->p_out_muxed, p_block );
1884 else if( tk->b_asf )
1885 stream_DemuxSend( p_sys->p_out_asf, p_block );
1887 es_out_Send( p_demux->out, tk->p_es, p_block );
1890 /* warn that's ok */
1891 p_sys->event = 0xff;
1893 /* we have read data */
1895 p_demux->p_sys->b_no_data = false;
1896 p_demux->p_sys->i_no_data_ti = 0;
1898 if( i_pts > 0 && !tk->b_muxed )
1904 /*****************************************************************************
1906 *****************************************************************************/
1907 static void StreamClose( void *p_private )
1909 live_track_t *tk = (live_track_t*)p_private;
1910 demux_t *p_demux = tk->p_demux;
1911 demux_sys_t *p_sys = p_demux->p_sys;
1913 msg_Dbg( p_demux, "StreamClose" );
1915 p_sys->event = 0xff;
1916 p_sys->b_error = true;
1920 /*****************************************************************************
1922 *****************************************************************************/
1923 static void TaskInterrupt( void *p_private )
1925 demux_t *p_demux = (demux_t*)p_private;
1927 p_demux->p_sys->i_no_data_ti++;
1930 p_demux->p_sys->event = 0xff;
1933 /*****************************************************************************
1935 *****************************************************************************/
1936 static void* TimeoutPrevention( void *p_data )
1938 timeout_thread_t *p_timeout = (timeout_thread_t *)p_data;
1942 /* Voodoo (= no) thread safety here! *Ahem* */
1943 if( p_timeout->b_handle_keep_alive )
1945 char *psz_bye = NULL;
1946 int canc = vlc_savecancel ();
1948 p_timeout->p_sys->rtsp->sendGetParameterCommand( *p_timeout->p_sys->ms, NULL, psz_bye );
1949 vlc_restorecancel (canc);
1951 p_timeout->p_sys->b_timeout_call = !p_timeout->b_handle_keep_alive;
1953 msleep (((int64_t)p_timeout->p_sys->i_timeout - 2) * CLOCK_FREQ);
1955 assert(0); /* dead code */
1958 /*****************************************************************************
1960 *****************************************************************************/
1961 static int ParseASF( demux_t *p_demux )
1963 demux_sys_t *p_sys = p_demux->p_sys;
1965 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1966 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1970 /* Parse the asf header */
1971 if( psz_asf == NULL )
1972 return VLC_EGENERIC;
1974 psz_asf += strlen( psz_marker );
1975 psz_asf = strdup( psz_asf ); /* Duplicate it */
1976 psz_end = strchr( psz_asf, '\n' );
1978 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1981 if( psz_asf >= psz_end )
1984 return VLC_EGENERIC;
1987 /* Always smaller */
1988 p_header = block_New( p_demux, psz_end - psz_asf );
1989 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
1990 p_header->i_buffer, psz_asf );
1991 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
1992 if( p_header->i_buffer <= 0 )
1995 return VLC_EGENERIC;
1998 /* Parse it to get packet size */
1999 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2001 /* Send it to demuxer */
2002 stream_DemuxSend( p_sys->p_out_asf, p_header );
2009 static unsigned char* parseH264ConfigStr( char const* configStr,
2010 unsigned int& configSize )
2013 size_t i_records = 1;
2017 if( configStr == NULL || *configStr == '\0' )
2020 psz = dup = strdup( configStr );
2022 /* Count the number of commas */
2023 for( psz = dup; *psz != '\0'; ++psz )
2032 size_t configMax = 5*strlen(dup);
2033 unsigned char *cfg = new unsigned char[configMax];
2035 for( size_t i = 0; i < i_records; ++i )
2037 cfg[configSize++] = 0x00;
2038 cfg[configSize++] = 0x00;
2039 cfg[configSize++] = 0x00;
2040 cfg[configSize++] = 0x01;
2042 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2043 configMax-configSize, psz );
2044 psz += strlen(psz)+1;