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>
63 #include <liveMedia_version.hh>
66 #include "../access/mms/asf.h" /* Who said ugly ? */
71 /*****************************************************************************
73 *****************************************************************************/
74 static int Open ( vlc_object_t * );
75 static void Close( vlc_object_t * );
77 #define CACHING_TEXT N_("Caching value (ms)")
78 #define CACHING_LONGTEXT N_( \
79 "Allows you to modify the default caching value for RTSP streams. This " \
80 "value should be set in millisecond units." )
82 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
83 #define KASENNA_LONGTEXT N_( "Kasenna servers use an old and nonstandard " \
84 "dialect of RTSP. With this parameter VLC will try this dialect, but "\
85 "then it cannot connect to normal RTSP servers." )
87 #define WMSERVER_TEXT N_("WMServer RTSP dialect")
88 #define WMSERVER_LONGTEXT N_("WMServer uses an unstandard dialect " \
89 "of RTSP. Selecting this parameter will tell VLC to assume some " \
90 "options contrary to RFC 2326 guidelines.")
92 #define USER_TEXT N_("RTSP user name")
93 #define USER_LONGTEXT N_("Sets the username for the connection, " \
94 "if no username or password are set in the url.")
95 #define PASS_TEXT N_("RTSP password")
96 #define PASS_LONGTEXT N_("Sets the password for the connection, " \
97 "if no username or password are set in the url.")
100 set_description( N_("RTP/RTSP/SDP demuxer (using Live555)" ) )
101 set_capability( "demux", 50 )
102 set_shortname( "RTP/RTSP")
103 set_callbacks( Open, Close )
104 add_shortcut( "live", "livedotcom" )
105 set_category( CAT_INPUT )
106 set_subcategory( SUBCAT_INPUT_DEMUX )
109 set_description( N_("RTSP/RTP access and demux") )
110 add_shortcut( "rtsp", "pnm", "live", "livedotcom" )
111 set_capability( "access_demux", 0 )
112 set_callbacks( Open, Close )
113 add_bool( "rtsp-tcp", false,
114 N_("Use RTP over RTSP (TCP)"),
115 N_("Use RTP over RTSP (TCP)"), true )
117 add_integer( "rtp-client-port", -1,
119 N_("Port to use for the RTP source of the session"), true )
120 add_bool( "rtsp-mcast", false,
121 N_("Force multicast RTP via RTSP"),
122 N_("Force multicast RTP via RTSP"), true )
124 add_bool( "rtsp-http", false,
125 N_("Tunnel RTSP and RTP over HTTP"),
126 N_("Tunnel RTSP and RTP over HTTP"), true )
128 add_integer( "rtsp-http-port", 80,
129 N_("HTTP tunnel port"),
130 N_("Port to use for tunneling the RTSP/RTP over HTTP."),
132 add_integer("rtsp-caching", 4 * DEFAULT_PTS_DELAY / 1000,
133 CACHING_TEXT, CACHING_LONGTEXT, true )
135 add_bool( "rtsp-kasenna", false, KASENNA_TEXT,
136 KASENNA_LONGTEXT, true )
138 add_bool( "rtsp-wmserver", false, WMSERVER_TEXT,
139 WMSERVER_LONGTEXT, true)
141 add_string( "rtsp-user", NULL, USER_TEXT,
142 USER_LONGTEXT, true )
144 add_password( "rtsp-pwd", NULL, PASS_TEXT,
145 PASS_LONGTEXT, true )
150 /*****************************************************************************
152 *****************************************************************************/
157 MediaSubsession *sub;
165 block_t *p_asf_block;
166 bool b_discard_trunc;
167 stream_t *p_out_muxed; /* for muxed stream */
170 unsigned int i_buffer;
179 struct timeout_thread_t
183 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 */
228 bool b_get_param; /* Does the server support GET_PARAMETER */
229 bool b_paused; /* Are we paused? */
231 int i_live555_ret; /* live555 callback return code */
233 float f_seek_request;/* In case we receive a seek request while paused*/
237 class RTSPClientVlc : public RTSPClient
240 RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
241 char const* applicationName, portNumBits tunnelOverHTTPPortNum,
242 demux_sys_t *p_sys) :
243 RTSPClient( env, rtspURL, verbosityLevel, applicationName,
244 tunnelOverHTTPPortNum )
251 static int Demux ( demux_t * );
252 static int Control( demux_t *, int, va_list );
254 static int Connect ( demux_t * );
255 static int SessionsSetup( demux_t * );
256 static int Play ( demux_t *);
257 static int ParseASF ( demux_t * );
258 static int RollOverTcp ( demux_t * );
260 static void StreamRead ( void *, unsigned int, unsigned int,
261 struct timeval, unsigned int );
262 static void StreamClose ( void * );
263 static void TaskInterruptData( void * );
264 static void TaskInterruptRTSP( void * );
266 static void* TimeoutPrevention( void * );
268 static unsigned char* parseH264ConfigStr( char const* configStr,
269 unsigned int& configSize );
271 /*****************************************************************************
273 *****************************************************************************/
274 static int Open ( vlc_object_t *p_this )
276 demux_t *p_demux = (demux_t*)p_this;
277 demux_sys_t *p_sys = NULL;
280 int i_error = VLC_EGENERIC;
284 /* See if it looks like a SDP
285 v, o, s fields are mandatory and in this order */
286 const uint8_t *p_peek;
287 if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
289 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
290 memcmp( p_peek, "v=0\n", 4 ) &&
291 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
296 var_Create( p_demux, "rtsp-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
298 p_demux->pf_demux = Demux;
299 p_demux->pf_control= Control;
300 p_demux->p_sys = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
301 if( !p_sys ) return VLC_ENOMEM;
303 msg_Dbg( p_demux, "version "LIVEMEDIA_LIBRARY_VERSION_STRING );
306 p_sys->scheduler = NULL;
314 p_sys->i_npt_start = 0.;
315 p_sys->i_npt_length = 0.;
316 p_sys->p_out_asf = NULL;
317 p_sys->b_no_data = true;
318 p_sys->i_no_data_ti = 0;
319 p_sys->p_timeout = NULL;
320 p_sys->i_timeout = 0;
321 p_sys->b_timeout_call = false;
322 p_sys->b_multicast = false;
323 p_sys->b_real = false;
324 p_sys->psz_path = strdup( p_demux->psz_location );
325 p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
326 p_sys->b_get_param = false;
327 p_sys->b_paused = false;
328 p_sys->f_seek_request = -1;
329 p_sys->b_error = false;
330 p_sys->i_live555_ret = 0;
332 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
333 vlc_UrlParse( &p_sys->url, p_sys->psz_path, 0 );
335 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
337 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
340 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
342 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
346 if( strcasecmp( p_demux->psz_access, "sdp" ) )
348 char *p = p_sys->psz_path;
349 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
352 if( p_demux->s != NULL )
354 /* Gather the complete sdp file */
356 int i_sdp_max = 1000;
357 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
361 i_error = VLC_ENOMEM;
367 int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
368 i_sdp_max - i_sdp - 1 );
370 if( !vlc_object_alive (p_demux) )
378 msg_Err( p_demux, "failed to read SDP" );
385 if( i_read < i_sdp_max - i_sdp - 1 )
392 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
394 p_sys->p_sdp = (char*)p_sdp;
396 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
398 msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
402 if( p_sys->p_sdp == NULL )
404 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
405 i_error = VLC_ENOMEM;
409 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
411 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
415 if( p_sys->b_real ) goto error;
417 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
420 if( p_sys->p_out_asf && ParseASF( p_demux ) )
422 msg_Err( p_demux, "cannot find a usable asf header" );
423 /* TODO Clean tracks */
427 if( p_sys->i_track <= 0 )
437 /*****************************************************************************
439 *****************************************************************************/
440 static void Close( vlc_object_t *p_this )
442 demux_t *p_demux = (demux_t*)p_this;
443 demux_sys_t *p_sys = p_demux->p_sys;
445 if( p_sys->p_timeout )
447 vlc_cancel( p_sys->p_timeout->handle );
448 vlc_join( p_sys->p_timeout->handle, NULL );
449 free( p_sys->p_timeout );
452 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
453 if( p_sys->ms ) Medium::close( p_sys->ms );
454 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
455 if( p_sys->env ) p_sys->env->reclaim();
457 for( int i = 0; i < p_sys->i_track; i++ )
459 live_track_t *tk = p_sys->track[i];
461 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
462 es_format_Clean( &tk->fmt );
463 free( tk->p_buffer );
467 if( p_sys->i_track ) free( p_sys->track );
468 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
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;
488 p_sys->event_rtsp = 1;
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;
496 p_sys->event_rtsp = 0;
499 /* Create a task that will be called if we wait more than timeout ms */
500 task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000,
504 p_sys->event_rtsp = 0;
505 p_sys->b_error = true;
506 p_sys->i_live555_ret = 0;
507 p_sys->scheduler->doEventLoop( &p_sys->event_rtsp );
508 //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
511 /* remove the task */
512 p_sys->scheduler->unscheduleDelayedTask( task );
514 return !p_sys->b_error;
517 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
518 char* result_string )
520 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
521 demux_sys_t *p_sys = client_vlc->p_sys;
522 p_sys->i_live555_ret = result_code;
523 if ( result_code == 0 )
525 char* sdpDescription = result_string;
526 free( p_sys->p_sdp );
530 p_sys->p_sdp = strdup( sdpDescription );
531 p_sys->b_error = false;
535 p_sys->b_error = true;
536 delete[] result_string;
537 p_sys->event_rtsp = 1;
540 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
541 char* result_string )
543 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
544 demux_sys_t *p_sys = client_vlc->p_sys;
545 p_sys->i_live555_ret = result_code;
546 if ( result_code != 0 )
548 p_sys->b_error = true;
549 p_sys->event_rtsp = 1;
553 p_sys->b_get_param = result_string != NULL && strstr( result_string, "GET_PARAMETER" ) != NULL;
554 client->sendDescribeCommand( continueAfterDESCRIBE );
556 delete[] result_string;
559 /*****************************************************************************
560 * Connect: connects to the RTSP server to setup the session DESCRIBE
561 *****************************************************************************/
562 static int Connect( demux_t *p_demux )
564 demux_sys_t *p_sys = p_demux->p_sys;
565 Authenticator authenticator;
566 char *psz_user = NULL;
567 char *psz_pwd = NULL;
568 char *psz_url = NULL;
569 char *psz_options = NULL;
572 int i_ret = VLC_SUCCESS;
573 const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
575 /* Get the user name and password */
576 if( p_sys->url.psz_username || p_sys->url.psz_password )
578 /* Create the URL by stripping away the username/password part */
579 if( p_sys->url.i_port == 0 )
580 p_sys->url.i_port = 554;
581 if( asprintf( &psz_url, "rtsp://%s:%d%s",
582 strempty( p_sys->url.psz_host ),
584 strempty( p_sys->url.psz_path ) ) == -1 )
587 psz_user = strdup( strempty( p_sys->url.psz_username ) );
588 psz_pwd = strdup( strempty( p_sys->url.psz_password ) );
592 if( asprintf( &psz_url, "rtsp://%s", p_sys->psz_path ) == -1 )
595 psz_user = var_InheritString( p_demux, "rtsp-user" );
596 psz_pwd = var_InheritString( p_demux, "rtsp-pwd" );
600 if( !vlc_object_alive (p_demux) )
602 i_ret = VLC_EGENERIC;
606 if( var_InheritBool( p_demux, "rtsp-http" ) )
607 i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
609 p_sys->rtsp = new RTSPClientVlc( *p_sys->env, psz_url,
610 var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
611 "LibVLC/"VERSION, i_http_port, p_sys );
614 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
615 p_sys->env->getResultMsg() );
616 i_ret = VLC_EGENERIC;
620 /* Kasenna enables KeepAlive by analysing the User-Agent string.
621 * Appending _KA to the string should be enough to enable this feature,
622 * however, there is a bug where the _KA doesn't get parsed from the
623 * default User-Agent as created by VLC/Live555 code. This is probably due
624 * to spaces in the string or the string being too long. Here we override
625 * the default string with a more compact version.
627 if( var_InheritBool( p_demux, "rtsp-kasenna" ))
629 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
633 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
635 p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
637 if( !wait_Live555_response( p_demux, i_timeout ) )
639 int i_code = p_sys->i_live555_ret;
642 msg_Dbg( p_demux, "authentication failed" );
646 dialog_Login( p_demux, &psz_user, &psz_pwd,
647 _("RTSP authentication"), "%s",
648 _("Please enter a valid login name and a password.") );
649 if( psz_user != NULL && psz_pwd != NULL )
651 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
655 else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
657 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
658 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
659 var_SetBool( p_demux, "rtsp-http", true );
660 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
667 msg_Dbg( p_demux, "connection timeout" );
669 msg_Dbg( p_demux, "connection error %d", i_code );
670 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
673 i_ret = VLC_EGENERIC;
677 /* malloc-ated copy */
685 /*****************************************************************************
686 * SessionsSetup: prepares the subsessions and does the SETUP
687 *****************************************************************************/
688 static int SessionsSetup( demux_t *p_demux )
690 demux_sys_t *p_sys = p_demux->p_sys;
691 MediaSubsessionIterator *iter = NULL;
692 MediaSubsession *sub = NULL;
694 bool b_rtsp_tcp = false;
696 int i_return = VLC_SUCCESS;
697 unsigned int i_buffer = 0;
698 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
700 b_rtsp_tcp = var_InheritBool( p_demux, "rtsp-tcp" ) ||
701 var_InheritBool( p_demux, "rtsp-http" );
702 i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
704 /* Create the session from the SDP */
705 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
707 msg_Err( p_demux, "Could not create the RTSP Session: %s",
708 p_sys->env->getResultMsg() );
712 /* Initialise each media subsession */
713 iter = new MediaSubsessionIterator( *p_sys->ms );
714 while( ( sub = iter->next() ) != NULL )
719 if( !vlc_object_alive (p_demux) )
725 /* Value taken from mplayer */
726 if( !strcmp( sub->mediumName(), "audio" ) )
728 else if( !strcmp( sub->mediumName(), "video" ) )
730 else if( !strcmp( sub->mediumName(), "text" ) )
734 if( i_client_port != -1 )
736 sub->setClientPortNum( i_client_port );
740 if( strcasestr( sub->codecName(), "REAL" ) )
742 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
743 p_sys->b_real = true; /* This is a problem, we'll handle it later */
747 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
748 bInit = sub->initiate( 0 );
750 bInit = sub->initiate();
754 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
755 sub->mediumName(), sub->codecName(),
756 p_sys->env->getResultMsg() );
760 if( sub->rtpSource() != NULL )
762 int fd = sub->rtpSource()->RTPgs()->socketNum();
764 /* Increase the buffer size */
766 increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
768 /* Increase the RTP reorder timebuffer just a bit */
769 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
771 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
774 /* Issue the SETUP */
777 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
778 toBool( b_rtsp_tcp ),
779 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
780 if( !wait_Live555_response( p_demux ) )
782 /* if we get an unsupported transport error, toggle TCP
783 * use and try again */
784 if( p_sys->i_live555_ret == 461 )
785 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
786 toBool( b_rtsp_tcp ), False );
787 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
789 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
790 sub->mediumName(), sub->codecName(),
791 p_sys->env->getResultMsg() );
797 /* Check if we will receive data from this subsession for
799 if( sub->readSource() == NULL ) continue;
800 if( !p_sys->b_multicast )
802 /* We need different rollover behaviour for multicast */
803 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
806 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
812 tk->p_demux = p_demux;
815 tk->b_quicktime = false;
817 tk->p_asf_block = NULL;
819 tk->b_discard_trunc = false;
820 tk->p_out_muxed = NULL;
822 tk->b_rtcp_sync = false;
823 tk->i_pts = VLC_TS_INVALID;
825 tk->i_buffer = 65536;
826 tk->p_buffer = (uint8_t *)malloc( 65536 );
834 /* Value taken from mplayer */
835 if( !strcmp( sub->mediumName(), "audio" ) )
837 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
838 tk->fmt.audio.i_channels = sub->numChannels();
839 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
841 if( !strcmp( sub->codecName(), "MPA" ) ||
842 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
843 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
845 tk->fmt.i_codec = VLC_CODEC_MPGA;
846 tk->fmt.audio.i_rate = 0;
848 else if( !strcmp( sub->codecName(), "AC3" ) )
850 tk->fmt.i_codec = VLC_CODEC_A52;
851 tk->fmt.audio.i_rate = 0;
853 else if( !strcmp( sub->codecName(), "L16" ) )
855 tk->fmt.i_codec = VLC_CODEC_S16B;
856 tk->fmt.audio.i_bitspersample = 16;
858 else if( !strcmp( sub->codecName(), "L20" ) )
860 tk->fmt.i_codec = VLC_CODEC_S20B;
861 tk->fmt.audio.i_bitspersample = 20;
863 else if( !strcmp( sub->codecName(), "L24" ) )
865 tk->fmt.i_codec = VLC_CODEC_S24B;
866 tk->fmt.audio.i_bitspersample = 24;
868 else if( !strcmp( sub->codecName(), "L8" ) )
870 tk->fmt.i_codec = VLC_CODEC_U8;
871 tk->fmt.audio.i_bitspersample = 8;
873 else if( !strcmp( sub->codecName(), "DAT12" ) )
875 tk->fmt.i_codec = VLC_CODEC_DAT12;
876 tk->fmt.audio.i_bitspersample = 12;
878 else if( !strcmp( sub->codecName(), "PCMU" ) )
880 tk->fmt.i_codec = VLC_CODEC_MULAW;
881 tk->fmt.audio.i_bitspersample = 8;
883 else if( !strcmp( sub->codecName(), "PCMA" ) )
885 tk->fmt.i_codec = VLC_CODEC_ALAW;
886 tk->fmt.audio.i_bitspersample = 8;
888 else if( !strncmp( sub->codecName(), "G726", 4 ) )
890 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
891 tk->fmt.audio.i_rate = 8000;
892 tk->fmt.audio.i_channels = 1;
893 if( !strcmp( sub->codecName()+5, "40" ) )
894 tk->fmt.i_bitrate = 40000;
895 else if( !strcmp( sub->codecName()+5, "32" ) )
896 tk->fmt.i_bitrate = 32000;
897 else if( !strcmp( sub->codecName()+5, "24" ) )
898 tk->fmt.i_bitrate = 24000;
899 else if( !strcmp( sub->codecName()+5, "16" ) )
900 tk->fmt.i_bitrate = 16000;
902 else if( !strcmp( sub->codecName(), "AMR" ) )
904 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
906 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
908 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
910 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
912 unsigned int i_extra;
915 tk->fmt.i_codec = VLC_CODEC_MP4A;
917 if( ( p_extra = parseStreamMuxConfigStr( 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 );
925 /* Because the "faad" decoder does not handle the LATM
926 * data length field at the start of each returned LATM
927 * frame, tell the RTP source to omit it. */
928 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
930 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
932 unsigned int i_extra;
935 tk->fmt.i_codec = VLC_CODEC_MP4A;
937 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
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 );
946 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
949 if( p_sys->p_out_asf == NULL )
950 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
953 else if( !strcmp( sub->codecName(), "X-QT" ) ||
954 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
956 tk->b_quicktime = true;
958 else if( !strcmp( sub->codecName(), "SPEEX" ) )
960 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
961 if ( sub->rtpTimestampFrequency() )
962 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
965 msg_Warn( p_demux,"Using 8kHz as default sample rate." );
966 tk->fmt.audio.i_rate = 8000;
970 else if( !strcmp( sub->mediumName(), "video" ) )
972 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
973 if( !strcmp( sub->codecName(), "MPV" ) )
975 tk->fmt.i_codec = VLC_CODEC_MPGV;
976 tk->fmt.b_packetized = false;
978 else if( !strcmp( sub->codecName(), "H263" ) ||
979 !strcmp( sub->codecName(), "H263-1998" ) ||
980 !strcmp( sub->codecName(), "H263-2000" ) )
982 tk->fmt.i_codec = VLC_CODEC_H263;
984 else if( !strcmp( sub->codecName(), "H261" ) )
986 tk->fmt.i_codec = VLC_CODEC_H261;
988 else if( !strcmp( sub->codecName(), "H264" ) )
990 unsigned int i_extra = 0;
991 uint8_t *p_extra = NULL;
993 tk->fmt.i_codec = VLC_CODEC_H264;
994 tk->fmt.b_packetized = false;
996 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
999 tk->fmt.i_extra = i_extra;
1000 tk->fmt.p_extra = xmalloc( i_extra );
1001 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1006 else if( !strcmp( sub->codecName(), "JPEG" ) )
1008 tk->fmt.i_codec = VLC_CODEC_MJPG;
1010 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1012 unsigned int i_extra;
1015 tk->fmt.i_codec = VLC_CODEC_MP4V;
1017 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1020 tk->fmt.i_extra = i_extra;
1021 tk->fmt.p_extra = xmalloc( i_extra );
1022 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1026 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1027 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1028 !strcmp( sub->codecName(), "X-QDM" ) ||
1029 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1030 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1032 tk->b_quicktime = true;
1034 else if( !strcmp( sub->codecName(), "MP2T" ) )
1037 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
1039 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1040 !strcmp( sub->codecName(), "MP1S" ) )
1043 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
1046 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1049 if( p_sys->p_out_asf == NULL )
1050 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
1053 else if( !strcmp( sub->codecName(), "DV" ) )
1056 tk->b_discard_trunc = true;
1057 tk->p_out_muxed = stream_DemuxNew( p_demux, "rawdv",
1061 else if( !strcmp( sub->mediumName(), "text" ) )
1063 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1065 if( !strcmp( sub->codecName(), "T140" ) )
1067 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1071 if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
1073 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1076 if( sub->rtcpInstance() != NULL )
1078 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1081 if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
1084 p_sys->track = (live_track_t**)xrealloc( p_sys->track,
1085 sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
1086 p_sys->track[p_sys->i_track++] = tk;
1091 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1092 es_format_Clean( &tk->fmt );
1098 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1100 /* Retrieve the starttime if possible */
1101 p_sys->i_npt_start = p_sys->ms->playStartTime();
1103 /* Retrieve the duration if possible */
1104 p_sys->i_npt_length = p_sys->ms->playEndTime();
1107 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1110 p_sys->b_no_data = true;
1111 p_sys->i_no_data_ti = 0;
1116 /*****************************************************************************
1117 * Play: starts the actual playback of the stream
1118 *****************************************************************************/
1119 static int Play( demux_t *p_demux )
1121 demux_sys_t *p_sys = p_demux->p_sys;
1126 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->i_npt_start, -1, 1 );
1128 if( !wait_Live555_response(p_demux) )
1130 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1131 return VLC_EGENERIC;
1134 /* Retrieve the timeout value and set up a timeout prevention thread */
1135 p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
1136 if( p_sys->i_timeout <= 0 )
1137 p_sys->i_timeout = 60; /* default value from RFC2326 */
1139 /* start timeout-thread only if GET_PARAMETER is supported by the server */
1140 if( !p_sys->p_timeout && p_sys->b_get_param )
1142 msg_Dbg( p_demux, "We have a timeout of %d seconds", p_sys->i_timeout );
1143 p_sys->p_timeout = (timeout_thread_t *)malloc( sizeof(timeout_thread_t) );
1144 if( p_sys->p_timeout )
1146 memset( p_sys->p_timeout, 0, sizeof(timeout_thread_t) );
1147 p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
1148 if( vlc_clone( &p_sys->p_timeout->handle, TimeoutPrevention,
1149 p_sys->p_timeout, VLC_THREAD_PRIORITY_LOW ) )
1151 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1152 free( p_sys->p_timeout );
1153 p_sys->p_timeout = NULL;
1156 msg_Dbg( p_demux, "spawned timeout thread" );
1159 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1164 /* Retrieve the starttime if possible */
1165 p_sys->i_npt_start = p_sys->ms->playStartTime();
1166 if( p_sys->ms->playEndTime() > 0 )
1167 p_sys->i_npt_length = p_sys->ms->playEndTime();
1169 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1174 /*****************************************************************************
1176 *****************************************************************************/
1177 static int Demux( demux_t *p_demux )
1179 demux_sys_t *p_sys = p_demux->p_sys;
1182 bool b_send_pcr = true;
1186 /* Check if we need to send the server a Keep-A-Live signal */
1187 if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
1189 char *psz_bye = NULL;
1190 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms, NULL, psz_bye );
1191 p_sys->b_timeout_call = false;
1194 for( i = 0; i < p_sys->i_track; i++ )
1196 live_track_t *tk = p_sys->track[i];
1198 if( tk->b_asf || tk->b_muxed )
1205 else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
1211 if( p_sys->i_pcr > 0 )
1214 es_out_Control( p_demux->out, ES_OUT_SET_PCR, 1 + p_sys->i_pcr );
1217 /* First warn we want to read data */
1218 p_sys->event_data = 0;
1219 for( i = 0; i < p_sys->i_track; i++ )
1221 live_track_t *tk = p_sys->track[i];
1223 if( tk->waiting == 0 )
1226 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1227 StreamRead, tk, StreamClose, tk );
1230 /* Create a task that will be called if we wait more than 300ms */
1231 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1234 p_sys->scheduler->doEventLoop( &p_sys->event_data );
1236 /* remove the task */
1237 p_sys->scheduler->unscheduleDelayedTask( task );
1239 /* Check for gap in pts value */
1240 for( i = 0; i < p_sys->i_track; i++ )
1242 live_track_t *tk = p_sys->track[i];
1244 if( !tk->b_muxed && !tk->b_rtcp_sync &&
1245 tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1247 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1249 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1250 tk->b_rtcp_sync = true;
1252 tk->i_pts = VLC_TS_INVALID;
1260 if( p_sys->b_multicast && p_sys->b_no_data &&
1261 ( p_sys->i_no_data_ti > 120 ) )
1263 /* FIXME Make this configurable
1264 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1268 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1269 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1271 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1272 var_GetBool( p_demux, "rtsp-http" );
1274 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1276 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1277 if( RollOverTcp( p_demux ) )
1279 msg_Err( p_demux, "TCP rollover failed, aborting" );
1284 msg_Err( p_demux, "no data received in 10s, aborting" );
1287 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1288 ( p_sys->i_no_data_ti > 34 ) )
1291 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1294 return p_sys->b_error ? 0 : 1;
1297 /*****************************************************************************
1299 *****************************************************************************/
1300 static int Control( demux_t *p_demux, int i_query, va_list args )
1302 demux_sys_t *p_sys = p_demux->p_sys;
1310 case DEMUX_GET_TIME:
1311 pi64 = (int64_t*)va_arg( args, int64_t * );
1312 if( p_sys->i_npt > 0 )
1314 *pi64 = (int64_t)(p_sys->i_npt * 1000000.);
1317 return VLC_EGENERIC;
1319 case DEMUX_GET_LENGTH:
1320 pi64 = (int64_t*)va_arg( args, int64_t * );
1321 if( p_sys->i_npt_length > 0 )
1323 *pi64 = (int64_t)((double)p_sys->i_npt_length * 1000000.0);
1326 return VLC_EGENERIC;
1328 case DEMUX_GET_POSITION:
1329 pf = (double*)va_arg( args, double* );
1330 if( (p_sys->i_npt_length > 0) && (p_sys->i_npt > 0) )
1332 *pf = ( (double)p_sys->i_npt / (double)p_sys->i_npt_length );
1335 return VLC_EGENERIC;
1337 case DEMUX_SET_POSITION:
1338 case DEMUX_SET_TIME:
1339 if( p_sys->rtsp && (p_sys->i_npt_length > 0) )
1344 if( (i_query == DEMUX_SET_TIME) && (p_sys->i_npt > 0) )
1346 i64 = (int64_t)va_arg( args, int64_t );
1347 time = (float)((double)i64 / (double)1000000.0); /* in second */
1349 else if( i_query == DEMUX_SET_TIME )
1350 return VLC_EGENERIC;
1353 f = (double)va_arg( args, double );
1354 time = f * (double)p_sys->i_npt_length; /* in second */
1357 if( p_sys->b_paused )
1359 p_sys->f_seek_request = time;
1363 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1365 if( !wait_Live555_response( p_demux ) )
1367 msg_Err( p_demux, "PAUSE before seek failed %s",
1368 p_sys->env->getResultMsg() );
1369 return VLC_EGENERIC;
1372 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1374 if( !wait_Live555_response( p_demux ) )
1376 msg_Err( p_demux, "seek PLAY failed %s",
1377 p_sys->env->getResultMsg() );
1378 return VLC_EGENERIC;
1382 /* Retrieve RTP-Info values */
1383 for( i = 0; i < p_sys->i_track; i++ )
1385 p_sys->track[i]->b_rtcp_sync = false;
1386 p_sys->track[i]->i_pts = VLC_TS_INVALID;
1389 /* Retrieve the starttime if possible */
1390 p_sys->i_npt = p_sys->i_npt_start = p_sys->ms->playStartTime();
1392 /* Retrieve the duration if possible */
1393 if( p_sys->ms->playEndTime() > 0 )
1394 p_sys->i_npt_length = p_sys->ms->playEndTime();
1396 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1399 return VLC_EGENERIC;
1401 /* Special for access_demux */
1402 case DEMUX_CAN_PAUSE:
1403 case DEMUX_CAN_SEEK:
1404 pb = (bool*)va_arg( args, bool * );
1405 if( p_sys->rtsp && p_sys->i_npt_length > 0 )
1406 /* Not always true, but will be handled in SET_PAUSE_STATE */
1412 case DEMUX_CAN_CONTROL_PACE:
1413 pb = (bool*)va_arg( args, bool * );
1415 #if 1 /* Disable for now until we have a clock synchro algo
1416 * which works with something else than MPEG over UDP */
1423 case DEMUX_CAN_CONTROL_RATE:
1424 pb = (bool*)va_arg( args, bool * );
1425 pb2 = (bool*)va_arg( args, bool * );
1427 *pb = (p_sys->rtsp != NULL) &&
1428 (p_sys->i_npt_length > 0) &&
1429 ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1430 !var_GetBool( p_demux, "rtsp-wmserver" ) );
1434 case DEMUX_SET_RATE:
1436 double f_scale, f_old_scale;
1438 if( !p_sys->rtsp || (p_sys->i_npt_length <= 0) ||
1439 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1440 var_GetBool( p_demux, "rtsp-wmserver" ) )
1441 return VLC_EGENERIC;
1443 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1446 * "[...] should try to approximate the viewing rate, but
1447 * may restrict the range of scale values that it supports.
1448 * The response MUST contain the actual scale value chosen
1451 * Scale = 1 indicates normal play
1452 * Scale > 1 indicates fast forward
1453 * Scale < 1 && Scale > 0 indicates slow motion
1454 * Scale < 0 value indicates rewind
1457 pi_int = (int*)va_arg( args, int * );
1458 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1459 f_old_scale = p_sys->ms->scale();
1461 /* Passing -1 for the start and end time will mean liveMedia won't
1462 * create a Range: section for the RTSP message. The server should
1463 * pick up from the current position */
1464 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1466 if( !wait_Live555_response( p_demux ) )
1468 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1469 p_sys->env->getResultMsg() );
1470 return VLC_EGENERIC;
1473 if( p_sys->ms->scale() == f_old_scale )
1475 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1476 p_sys->ms->scale() );
1477 return VLC_EGENERIC;
1480 /* ReSync the stream */
1481 p_sys->i_npt_start = 0;
1485 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1486 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1490 case DEMUX_SET_PAUSE_STATE:
1492 bool b_pause = (bool)va_arg( args, int );
1493 if( p_sys->rtsp == NULL )
1494 return VLC_EGENERIC;
1496 if( b_pause == p_sys->b_paused )
1499 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1501 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1502 -1.0f, p_sys->ms->scale() );
1504 if( !wait_Live555_response( p_demux ) )
1506 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1507 return VLC_EGENERIC;
1509 p_sys->f_seek_request = -1;
1510 p_sys->b_paused = b_pause;
1512 /* When we Pause, we'll need the TimeoutPrevention thread to
1513 * handle sending the "Keep Alive" message to the server.
1514 * Unfortunately Live555 isn't thread safe and so can't
1515 * do this normally while the main Demux thread is handling
1516 * a live stream. We end up with the Timeout thread blocking
1517 * waiting for a response from the server. So when we PAUSE
1518 * we set a flag that the TimeoutPrevention function will check
1519 * and if it's set, it will trigger the GET_PARAMETER message */
1520 if( p_sys->b_paused && p_sys->p_timeout != NULL )
1521 p_sys->p_timeout->b_handle_keep_alive = true;
1522 else if( !p_sys->b_paused && p_sys->p_timeout != NULL )
1523 p_sys->p_timeout->b_handle_keep_alive = false;
1525 if( !p_sys->b_paused )
1527 for( int i = 0; i < p_sys->i_track; i++ )
1529 live_track_t *tk = p_sys->track[i];
1530 tk->b_rtcp_sync = false;
1531 tk->i_pts = VLC_TS_INVALID;
1533 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1537 /* Reset data received counter */
1538 p_sys->i_no_data_ti = 0;
1540 /* Retrieve the starttime if possible */
1541 p_sys->i_npt_start = p_sys->ms->playStartTime();
1543 /* Retrieve the duration if possible */
1544 if( p_sys->ms->playEndTime() )
1545 p_sys->i_npt_length = p_sys->ms->playEndTime();
1547 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1550 case DEMUX_GET_TITLE_INFO:
1551 case DEMUX_SET_TITLE:
1552 case DEMUX_SET_SEEKPOINT:
1553 return VLC_EGENERIC;
1555 case DEMUX_GET_PTS_DELAY:
1556 pi64 = (int64_t*)va_arg( args, int64_t * );
1557 *pi64 = var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1561 return VLC_EGENERIC;
1565 /*****************************************************************************
1566 * RollOverTcp: reopen the rtsp into TCP mode
1567 * XXX: ugly, a lot of code are duplicated from Open()
1568 * This should REALLY be fixed
1569 *****************************************************************************/
1570 static int RollOverTcp( demux_t *p_demux )
1572 demux_sys_t *p_sys = p_demux->p_sys;
1575 var_SetBool( p_demux, "rtsp-tcp", true );
1577 /* We close the old RTSP session */
1578 for( i = 0; i < p_sys->i_track; i++ )
1580 live_track_t *tk = p_sys->track[i];
1582 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
1583 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1584 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1585 es_format_Clean( &tk->fmt );
1586 free( tk->p_buffer );
1589 if( p_sys->i_track ) free( p_sys->track );
1590 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
1592 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1593 Medium::close( p_sys->ms );
1594 RTSPClient::close( p_sys->rtsp );
1598 p_sys->track = NULL;
1600 p_sys->b_no_data = true;
1601 p_sys->i_no_data_ti = 0;
1602 p_sys->p_out_asf = NULL;
1604 /* Reopen rtsp client */
1605 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1607 msg_Err( p_demux, "Failed to connect with rtsp://%s",
1612 if( p_sys->p_sdp == NULL )
1614 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1618 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1620 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1624 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1630 return VLC_EGENERIC;
1634 /*****************************************************************************
1636 *****************************************************************************/
1637 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1639 const uint8_t *p_data, unsigned i_size )
1641 const unsigned i_packet_size = p_demux->p_sys->asfh.i_min_data_packet_size;
1642 block_t *p_list = NULL;
1644 while( i_size >= 4 )
1646 unsigned i_flags = p_data[0];
1647 unsigned i_length_offset = (p_data[1] << 16) |
1650 bool b_key = i_flags & 0x80;
1651 bool b_length = i_flags & 0x40;
1652 bool b_relative_ts = i_flags & 0x20;
1653 bool b_duration = i_flags & 0x10;
1654 bool b_location_id = i_flags & 0x08;
1656 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1657 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1658 unsigned i_header_size = 4;
1666 if( i_header_size > i_size )
1668 msg_Warn( p_demux, "Invalid header size" );
1673 * When b_length is true, the streams I found do not seems to respect
1674 * the documentation.
1675 * From them, I have failed to find which choice between '__MIN()' or
1676 * 'i_length_offset - i_header_size' is the right one.
1680 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1682 i_payload = i_size - i_header_size;
1684 if( !tk->p_asf_block )
1686 tk->p_asf_block = block_New( p_demux, i_packet_size );
1687 if( !tk->p_asf_block )
1689 tk->p_asf_block->i_buffer = 0;
1691 unsigned i_offset = b_length ? 0 : i_length_offset;
1692 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1694 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1695 tk->p_asf_block->i_buffer += i_payload;
1698 /* We have a complete packet */
1699 tk->p_asf_block->i_buffer = i_packet_size;
1700 block_ChainAppend( &p_list, tk->p_asf_block );
1701 tk->p_asf_block = NULL;
1706 /* Reset on broken stream */
1707 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1708 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1709 tk->p_asf_block->i_buffer = 0;
1713 p_data += i_header_size + i_payload;
1714 i_size -= i_header_size + i_payload;
1719 /*****************************************************************************
1721 *****************************************************************************/
1722 static void StreamRead( void *p_private, unsigned int i_size,
1723 unsigned int i_truncated_bytes, struct timeval pts,
1724 unsigned int duration )
1726 live_track_t *tk = (live_track_t*)p_private;
1727 demux_t *p_demux = tk->p_demux;
1728 demux_sys_t *p_sys = p_demux->p_sys;
1731 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1733 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1734 (int64_t)pts.tv_usec;
1736 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1737 i_pts &= INT64_C(0x00ffffffffffffff);
1739 /* Retrieve NPT for this pts */
1740 tk->i_npt = tk->sub->getNormalPlayTime(pts);
1742 if( tk->b_quicktime && tk->p_es == NULL )
1744 QuickTimeGenericRTPSource *qtRTPSource =
1745 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1746 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1747 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1749 if( tk->fmt.i_cat == VIDEO_ES ) {
1750 if( qtState.sdAtomSize < 16 + 32 )
1753 p_sys->event_data = 0xff;
1757 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1758 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1759 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1761 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1763 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1764 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1765 + qtRTPSource->qtState.sdAtomSize;
1766 while (pos+8 < endpos) {
1767 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1768 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1769 if( memcmp(pos+4, "avcC", 4) == 0 &&
1771 atomLength <= INT_MAX )
1773 tk->fmt.i_extra = atomLength-8;
1774 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1775 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1783 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1784 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1785 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1789 if( qtState.sdAtomSize < 4 )
1792 p_sys->event_data = 0xff;
1796 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1798 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1802 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1804 pts.tv_sec * 1000000LL + pts.tv_usec );
1807 /* grow buffer if it looks like buffer is too small, but don't eat
1808 * up all the memory on strange streams */
1809 if( i_truncated_bytes > 0 )
1811 if( tk->i_buffer < 2000000 )
1814 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1815 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1816 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1819 msg_Warn( p_demux, "realloc failed" );
1823 tk->p_buffer = (uint8_t*)p_tmp;
1828 if( tk->b_discard_trunc )
1830 p_sys->event_data = 0xff;
1836 assert( i_size <= tk->i_buffer );
1838 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1839 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1841 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1843 p_block = block_New( p_demux, i_size + 1 );
1844 p_block->p_buffer[0] = amrSource->lastFrameHeader();
1845 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1847 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1849 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1850 uint32_t header = h261Source->lastSpecialHeader();
1851 p_block = block_New( p_demux, i_size + 4 );
1852 memcpy( p_block->p_buffer, &header, 4 );
1853 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1855 if( tk->sub->rtpSource()->curPacketMarkerBit() )
1856 p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1858 else if( tk->fmt.i_codec == VLC_CODEC_H264 )
1860 if( (tk->p_buffer[0] & 0x1f) >= 24 )
1861 msg_Warn( p_demux, "unsupported NAL type for H264" );
1863 /* Normal NAL type */
1864 p_block = block_New( p_demux, i_size + 4 );
1865 p_block->p_buffer[0] = 0x00;
1866 p_block->p_buffer[1] = 0x00;
1867 p_block->p_buffer[2] = 0x00;
1868 p_block->p_buffer[3] = 0x01;
1869 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1871 else if( tk->b_asf )
1873 p_block = StreamParseAsf( p_demux, tk,
1874 tk->sub->rtpSource()->curPacketMarkerBit(),
1875 tk->p_buffer, i_size );
1879 p_block = block_New( p_demux, i_size );
1880 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1883 if( p_sys->i_pcr < i_pts )
1885 p_sys->i_pcr = i_pts;
1888 /* Update our global npt value */
1889 if( tk->i_npt > 0 && tk->i_npt > p_sys->i_npt &&
1890 ( tk->i_npt < p_sys->i_npt_length || p_sys->i_npt_length <= 0 ) )
1891 p_sys->i_npt = tk->i_npt;
1895 if( !tk->b_muxed && !tk->b_asf )
1897 if( i_pts != tk->i_pts )
1898 p_block->i_pts = VLC_TS_0 + i_pts;
1899 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
1900 p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? VLC_TS_INVALID : (VLC_TS_0 + i_pts);
1904 stream_DemuxSend( tk->p_out_muxed, p_block );
1905 else if( tk->b_asf )
1906 stream_DemuxSend( p_sys->p_out_asf, p_block );
1908 es_out_Send( p_demux->out, tk->p_es, p_block );
1911 /* warn that's ok */
1912 p_sys->event_data = 0xff;
1914 /* we have read data */
1916 p_demux->p_sys->b_no_data = false;
1917 p_demux->p_sys->i_no_data_ti = 0;
1919 if( i_pts > 0 && !tk->b_muxed )
1925 /*****************************************************************************
1927 *****************************************************************************/
1928 static void StreamClose( void *p_private )
1930 live_track_t *tk = (live_track_t*)p_private;
1931 demux_t *p_demux = tk->p_demux;
1932 demux_sys_t *p_sys = p_demux->p_sys;
1934 msg_Dbg( p_demux, "StreamClose" );
1936 p_sys->event_rtsp = 0xff;
1937 p_sys->event_data = 0xff;
1938 p_sys->b_error = true;
1942 /*****************************************************************************
1944 *****************************************************************************/
1945 static void TaskInterruptRTSP( void *p_private )
1947 demux_t *p_demux = (demux_t*)p_private;
1950 p_demux->p_sys->event_rtsp = 0xff;
1953 static void TaskInterruptData( void *p_private )
1955 demux_t *p_demux = (demux_t*)p_private;
1957 p_demux->p_sys->i_no_data_ti++;
1960 p_demux->p_sys->event_data = 0xff;
1963 /*****************************************************************************
1965 *****************************************************************************/
1966 static void* TimeoutPrevention( void *p_data )
1968 timeout_thread_t *p_timeout = (timeout_thread_t *)p_data;
1972 /* Voodoo (= no) thread safety here! *Ahem* */
1973 if( p_timeout->b_handle_keep_alive )
1975 char *psz_bye = NULL;
1976 int canc = vlc_savecancel ();
1978 p_timeout->p_sys->rtsp->sendGetParameterCommand( *p_timeout->p_sys->ms, NULL, psz_bye );
1979 vlc_restorecancel (canc);
1981 p_timeout->p_sys->b_timeout_call = !p_timeout->b_handle_keep_alive;
1983 msleep (((int64_t)p_timeout->p_sys->i_timeout - 2) * CLOCK_FREQ);
1985 assert(0); /* dead code */
1988 /*****************************************************************************
1990 *****************************************************************************/
1991 static int ParseASF( demux_t *p_demux )
1993 demux_sys_t *p_sys = p_demux->p_sys;
1995 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1996 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2000 /* Parse the asf header */
2001 if( psz_asf == NULL )
2002 return VLC_EGENERIC;
2004 psz_asf += strlen( psz_marker );
2005 psz_asf = strdup( psz_asf ); /* Duplicate it */
2006 psz_end = strchr( psz_asf, '\n' );
2008 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2011 if( psz_asf >= psz_end )
2014 return VLC_EGENERIC;
2017 /* Always smaller */
2018 p_header = block_New( p_demux, psz_end - psz_asf );
2019 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2020 p_header->i_buffer, psz_asf );
2021 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2022 if( p_header->i_buffer <= 0 )
2025 return VLC_EGENERIC;
2028 /* Parse it to get packet size */
2029 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2031 /* Send it to demuxer */
2032 stream_DemuxSend( p_sys->p_out_asf, p_header );
2039 static unsigned char* parseH264ConfigStr( char const* configStr,
2040 unsigned int& configSize )
2043 size_t i_records = 1;
2047 if( configStr == NULL || *configStr == '\0' )
2050 psz = dup = strdup( configStr );
2052 /* Count the number of commas */
2053 for( psz = dup; *psz != '\0'; ++psz )
2062 size_t configMax = 5*strlen(dup);
2063 unsigned char *cfg = new unsigned char[configMax];
2065 for( size_t i = 0; i < i_records; ++i )
2067 cfg[configSize++] = 0x00;
2068 cfg[configSize++] = 0x00;
2069 cfg[configSize++] = 0x00;
2070 cfg[configSize++] = 0x01;
2072 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2073 configMax-configSize, psz );
2074 psz += strlen(psz)+1;