1 /*****************************************************************************
2 * live555.cpp : LIVE555 Streaming Media support.
3 *****************************************************************************
4 * Copyright (C) 2003-2007 VLC authors and VideoLAN
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 it
13 * under the terms of the GNU Lesser General Public License as published by
14 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public License
23 * along with this program; if not, write to the Free Software Foundation,
24 * Inc., 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
35 #define __STDC_LIMIT_MACROS 1
43 #include <vlc_common.h>
44 #include <vlc_plugin.h>
45 #include <vlc_input.h>
46 #include <vlc_demux.h>
47 #include <vlc_dialog.h>
49 #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>
67 #include "../access/mms/asf.h" /* Who said ugly ? */
72 /*****************************************************************************
74 *****************************************************************************/
75 static int Open ( vlc_object_t * );
76 static void Close( vlc_object_t * );
78 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
79 #define KASENNA_LONGTEXT N_( "Kasenna servers use an old and nonstandard " \
80 "dialect of RTSP. With this parameter VLC will try this dialect, but "\
81 "then it cannot connect to normal RTSP servers." )
83 #define WMSERVER_TEXT N_("WMServer RTSP dialect")
84 #define WMSERVER_LONGTEXT N_("WMServer uses a nonstandard dialect " \
85 "of RTSP. Selecting this parameter will tell VLC to assume some " \
86 "options contrary to RFC 2326 guidelines.")
88 #define USER_TEXT N_("RTSP user name")
89 #define USER_LONGTEXT N_("Sets the username for the connection, " \
90 "if no username or password are set in the url.")
91 #define PASS_TEXT N_("RTSP password")
92 #define PASS_LONGTEXT N_("Sets the password for the connection, " \
93 "if no username or password are set in the url.")
94 #define FRAME_BUFFER_SIZE_TEXT N_("RTSP frame buffer size")
95 #define FRAME_BUFFER_SIZE_LONGTEXT N_("RTSP start frame buffer size of the video " \
96 "track, can be increased in case of broken pictures due " \
97 "to too small buffer.")
98 #define DEFAULT_FRAME_BUFFER_SIZE 100000
101 set_description( N_("RTP/RTSP/SDP demuxer (using Live555)" ) )
102 set_capability( "demux", 50 )
103 set_shortname( "RTP/RTSP")
104 set_callbacks( Open, Close )
105 add_shortcut( "live", "livedotcom" )
106 set_category( CAT_INPUT )
107 set_subcategory( SUBCAT_INPUT_DEMUX )
110 set_description( N_("RTSP/RTP access and demux") )
111 add_shortcut( "rtsp", "pnm", "live", "livedotcom" )
112 set_capability( "access_demux", 0 )
113 set_callbacks( Open, Close )
114 add_bool( "rtsp-tcp", false,
115 N_("Use RTP over RTSP (TCP)"),
116 N_("Use RTP over RTSP (TCP)"), true )
118 add_integer( "rtp-client-port", -1,
120 N_("Port to use for the RTP source of the session"), true )
121 add_bool( "rtsp-mcast", false,
122 N_("Force multicast RTP via RTSP"),
123 N_("Force multicast RTP via RTSP"), true )
125 add_bool( "rtsp-http", false,
126 N_("Tunnel RTSP and RTP over HTTP"),
127 N_("Tunnel RTSP and RTP over HTTP"), true )
129 add_integer( "rtsp-http-port", 80,
130 N_("HTTP tunnel port"),
131 N_("Port to use for tunneling the RTSP/RTP over HTTP."),
133 add_bool( "rtsp-kasenna", false, KASENNA_TEXT,
134 KASENNA_LONGTEXT, true )
136 add_bool( "rtsp-wmserver", false, WMSERVER_TEXT,
137 WMSERVER_LONGTEXT, true)
139 add_string( "rtsp-user", NULL, USER_TEXT,
140 USER_LONGTEXT, true )
142 add_password( "rtsp-pwd", NULL, PASS_TEXT,
143 PASS_LONGTEXT, true )
144 add_integer( "rtsp-frame-buffer-size", DEFAULT_FRAME_BUFFER_SIZE,
145 FRAME_BUFFER_SIZE_TEXT, FRAME_BUFFER_SIZE_LONGTEXT,
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;
181 struct timeout_thread_t
185 bool b_handle_keep_alive;
192 char *p_sdp; /* XXX mallocated */
193 char *psz_path; /* URL-encoded path */
197 TaskScheduler *scheduler;
198 UsageEnvironment *env ;
203 live_track_t **track;
211 int64_t i_pcr; /* The clock */
216 /* timeout thread information */
217 int i_timeout; /* session timeout value in seconds */
218 bool b_timeout_call;/* mark to send an RTSP call to prevent server timeout */
219 timeout_thread_t *p_timeout; /* the actual thread that makes sure we don't timeout */
223 bool b_multicast; /* if one of the tracks is multicasted */
224 bool b_no_data; /* if we never received any data */
225 int i_no_data_ti; /* consecutive number of TaskInterrupt */
230 bool b_get_param; /* Does the server support GET_PARAMETER */
231 bool b_paused; /* Are we paused? */
233 int i_live555_ret; /* live555 callback return code */
235 float f_seek_request;/* In case we receive a seek request while paused*/
239 class RTSPClientVlc : public RTSPClient
242 RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
243 char const* applicationName, portNumBits tunnelOverHTTPPortNum,
244 demux_sys_t *p_sys) :
245 RTSPClient( env, rtspURL, verbosityLevel, applicationName,
246 tunnelOverHTTPPortNum
247 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1373932800
257 static int Demux ( demux_t * );
258 static int Control( demux_t *, int, va_list );
260 static int Connect ( demux_t * );
261 static int SessionsSetup( demux_t * );
262 static int Play ( demux_t *);
263 static int ParseASF ( demux_t * );
264 static int RollOverTcp ( demux_t * );
266 static void StreamRead ( void *, unsigned int, unsigned int,
267 struct timeval, unsigned int );
268 static void StreamClose ( void * );
269 static void TaskInterruptData( void * );
270 static void TaskInterruptRTSP( void * );
272 static void* TimeoutPrevention( void * );
274 static unsigned char* parseH264ConfigStr( char const* configStr,
275 unsigned int& configSize );
276 static unsigned char* parseVorbisConfigStr( char const* configStr,
277 unsigned int& configSize );
279 /*****************************************************************************
281 *****************************************************************************/
282 static int Open ( vlc_object_t *p_this )
284 demux_t *p_demux = (demux_t*)p_this;
285 demux_sys_t *p_sys = NULL;
288 int i_error = VLC_EGENERIC;
292 /* See if it looks like a SDP
293 v, o, s fields are mandatory and in this order */
294 const uint8_t *p_peek;
295 if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
297 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
298 memcmp( p_peek, "v=0\n", 4 ) &&
299 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
305 p_demux->pf_demux = Demux;
306 p_demux->pf_control= Control;
307 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
308 if( !p_sys ) return VLC_ENOMEM;
310 msg_Dbg( p_demux, "version "LIVEMEDIA_LIBRARY_VERSION_STRING );
312 TAB_INIT( p_sys->i_track, p_sys->track );
314 p_sys->f_npt_start = 0.;
315 p_sys->f_npt_length = 0.;
316 p_sys->b_no_data = true;
317 p_sys->psz_path = strdup( p_demux->psz_location );
318 p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
319 p_sys->f_seek_request = -1;
321 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
322 vlc_UrlParse( &p_sys->url, p_sys->psz_path, 0 );
324 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
326 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
329 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
331 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
335 if( strcasecmp( p_demux->psz_access, "sdp" ) )
337 char *p = p_sys->psz_path;
338 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
341 if( p_demux->s != NULL )
343 /* Gather the complete sdp file */
345 int i_sdp_max = 1000;
346 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
350 i_error = VLC_ENOMEM;
356 int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
357 i_sdp_max - i_sdp - 1 );
359 if( !vlc_object_alive (p_demux) )
367 msg_Err( p_demux, "failed to read SDP" );
374 if( i_read < i_sdp_max - i_sdp - 1 )
381 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
383 p_sys->p_sdp = (char*)p_sdp;
385 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
387 msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
391 if( p_sys->p_sdp == NULL )
393 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
394 i_error = VLC_ENOMEM;
398 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
400 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
404 if( p_sys->b_real ) goto error;
406 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
409 if( p_sys->p_out_asf && ParseASF( p_demux ) )
411 msg_Err( p_demux, "cannot find a usable asf header" );
412 /* TODO Clean tracks */
416 if( p_sys->i_track <= 0 )
426 /*****************************************************************************
428 *****************************************************************************/
429 static void Close( vlc_object_t *p_this )
431 demux_t *p_demux = (demux_t*)p_this;
432 demux_sys_t *p_sys = p_demux->p_sys;
434 if( p_sys->p_timeout )
436 vlc_cancel( p_sys->p_timeout->handle );
437 vlc_join( p_sys->p_timeout->handle, NULL );
438 free( p_sys->p_timeout );
441 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
442 if( p_sys->ms ) Medium::close( p_sys->ms );
443 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
444 if( p_sys->env ) p_sys->env->reclaim();
446 for( int i = 0; i < p_sys->i_track; i++ )
448 live_track_t *tk = p_sys->track[i];
450 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
451 es_format_Clean( &tk->fmt );
452 free( tk->p_buffer );
455 TAB_CLEAN( p_sys->i_track, p_sys->track );
456 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
457 delete p_sys->scheduler;
458 free( p_sys->p_sdp );
459 free( p_sys->psz_path );
461 vlc_UrlClean( &p_sys->url );
466 static inline const char *strempty( const char *s ) { return s?s:""; }
467 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
469 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
471 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
472 demux_sys_t *p_sys = client_vlc->p_sys;
473 delete []result_string;
474 p_sys->i_live555_ret = result_code;
475 p_sys->b_error = p_sys->i_live555_ret != 0;
476 p_sys->event_rtsp = 1;
479 /* return true if the RTSP command succeeded */
480 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
483 demux_sys_t * p_sys = p_demux->p_sys;
484 p_sys->event_rtsp = 0;
487 /* Create a task that will be called if we wait more than timeout ms */
488 task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000,
492 p_sys->event_rtsp = 0;
493 p_sys->b_error = true;
494 p_sys->i_live555_ret = 0;
495 p_sys->scheduler->doEventLoop( &p_sys->event_rtsp );
496 //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
499 /* remove the task */
500 p_sys->scheduler->unscheduleDelayedTask( task );
502 return !p_sys->b_error;
505 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
506 char* result_string )
508 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
509 demux_sys_t *p_sys = client_vlc->p_sys;
510 p_sys->i_live555_ret = result_code;
511 if ( result_code == 0 )
513 char* sdpDescription = result_string;
514 free( p_sys->p_sdp );
518 p_sys->p_sdp = strdup( sdpDescription );
519 p_sys->b_error = false;
523 p_sys->b_error = true;
524 delete[] result_string;
525 p_sys->event_rtsp = 1;
528 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
529 char* result_string )
531 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
532 demux_sys_t *p_sys = client_vlc->p_sys;
534 // If OPTIONS fails, assume GET_PARAMETER is not supported but
535 // still continue on with the stream. Some servers (foscam)
536 // return 501/not implemented for OPTIONS.
538 && result_string != NULL
539 && strstr( result_string, "GET_PARAMETER" ) != NULL;
540 client->sendDescribeCommand( continueAfterDESCRIBE );
541 delete[] result_string;
544 /*****************************************************************************
545 * Connect: connects to the RTSP server to setup the session DESCRIBE
546 *****************************************************************************/
547 static int Connect( demux_t *p_demux )
549 demux_sys_t *p_sys = p_demux->p_sys;
550 Authenticator authenticator;
551 char *psz_user = NULL;
552 char *psz_pwd = NULL;
553 char *psz_url = NULL;
555 int i_ret = VLC_SUCCESS;
556 const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
558 /* Get the user name and password */
559 if( p_sys->url.psz_username || p_sys->url.psz_password )
561 /* Create the URL by stripping away the username/password part */
562 if( p_sys->url.i_port == 0 )
563 p_sys->url.i_port = 554;
564 if( asprintf( &psz_url, "rtsp://%s:%d%s",
565 strempty( p_sys->url.psz_host ),
567 strempty( p_sys->url.psz_path ) ) == -1 )
570 psz_user = strdup( strempty( p_sys->url.psz_username ) );
571 psz_pwd = strdup( strempty( p_sys->url.psz_password ) );
575 if( asprintf( &psz_url, "rtsp://%s", p_sys->psz_path ) == -1 )
578 psz_user = var_InheritString( p_demux, "rtsp-user" );
579 psz_pwd = var_InheritString( p_demux, "rtsp-pwd" );
583 if( !vlc_object_alive (p_demux) )
585 i_ret = VLC_EGENERIC;
589 if( var_CreateGetBool( p_demux, "rtsp-http" ) )
590 i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
592 p_sys->rtsp = new RTSPClientVlc( *p_sys->env, psz_url,
593 var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
594 "LibVLC/"VERSION, i_http_port, p_sys );
597 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
598 p_sys->env->getResultMsg() );
599 i_ret = VLC_EGENERIC;
603 /* Kasenna enables KeepAlive by analysing the User-Agent string.
604 * Appending _KA to the string should be enough to enable this feature,
605 * however, there is a bug where the _KA doesn't get parsed from the
606 * default User-Agent as created by VLC/Live555 code. This is probably due
607 * to spaces in the string or the string being too long. Here we override
608 * the default string with a more compact version.
610 if( var_InheritBool( p_demux, "rtsp-kasenna" ))
612 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
616 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
618 p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
620 if( !wait_Live555_response( p_demux, i_timeout ) )
622 int i_code = p_sys->i_live555_ret;
625 msg_Dbg( p_demux, "authentication failed" );
629 dialog_Login( p_demux, &psz_user, &psz_pwd,
630 _("RTSP authentication"), "%s",
631 _("Please enter a valid login name and a password.") );
632 if( psz_user != NULL && psz_pwd != NULL )
634 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
638 else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
640 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
641 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
642 var_SetBool( p_demux, "rtsp-http", true );
643 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
650 msg_Dbg( p_demux, "connection timeout" );
653 msg_Dbg( p_demux, "connection error %d", i_code );
655 dialog_Fatal( p_demux, _("RTSP connection failed"),
656 _("Access to the stream is denied by the server configuration.") );
658 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
661 i_ret = VLC_EGENERIC;
665 /* malloc-ated copy */
673 /*****************************************************************************
674 * SessionsSetup: prepares the subsessions and does the SETUP
675 *****************************************************************************/
676 static int SessionsSetup( demux_t *p_demux )
678 demux_sys_t *p_sys = p_demux->p_sys;
679 MediaSubsessionIterator *iter = NULL;
680 MediaSubsession *sub = NULL;
684 int i_return = VLC_SUCCESS;
685 unsigned int i_receive_buffer = 0;
686 int i_frame_buffer = DEFAULT_FRAME_BUFFER_SIZE;
687 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
689 b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
690 var_GetBool( p_demux, "rtsp-http" );
691 i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
694 /* Create the session from the SDP */
695 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
697 msg_Err( p_demux, "Could not create the RTSP Session: %s",
698 p_sys->env->getResultMsg() );
702 /* Initialise each media subsession */
703 iter = new MediaSubsessionIterator( *p_sys->ms );
704 while( ( sub = iter->next() ) != NULL )
709 if( !vlc_object_alive (p_demux) )
715 /* Value taken from mplayer */
716 if( !strcmp( sub->mediumName(), "audio" ) )
717 i_receive_buffer = 100000;
718 else if( !strcmp( sub->mediumName(), "video" ) )
720 int i_var_buf_size = var_InheritInteger( p_demux, "rtsp-frame-buffer-size" );
721 if( i_var_buf_size > 0 )
722 i_frame_buffer = i_var_buf_size;
723 i_receive_buffer = 2000000;
725 else if( !strcmp( sub->mediumName(), "text" ) )
729 if( i_client_port != -1 )
731 sub->setClientPortNum( i_client_port );
735 if( strcasestr( sub->codecName(), "REAL" ) )
737 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
738 p_sys->b_real = true; /* This is a problem, we'll handle it later */
742 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
743 bInit = sub->initiate( 0 );
745 bInit = sub->initiate();
749 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
750 sub->mediumName(), sub->codecName(),
751 p_sys->env->getResultMsg() );
755 if( sub->rtpSource() != NULL )
757 int fd = sub->rtpSource()->RTPgs()->socketNum();
759 /* Increase the buffer size */
760 if( i_receive_buffer > 0 )
761 increaseReceiveBufferTo( *p_sys->env, fd, i_receive_buffer );
763 /* Increase the RTP reorder timebuffer just a bit */
764 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
766 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
769 /* Issue the SETUP */
772 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
773 toBool( b_rtsp_tcp ),
774 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
775 if( !wait_Live555_response( p_demux ) )
777 /* if we get an unsupported transport error, toggle TCP
778 * use and try again */
779 if( p_sys->i_live555_ret == 461 )
780 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
781 !toBool( b_rtsp_tcp ), False );
782 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
784 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
785 sub->mediumName(), sub->codecName(),
786 p_sys->env->getResultMsg() );
791 var_SetBool( p_demux, "rtsp-tcp", true );
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->b_selected = true;
826 tk->i_buffer = i_frame_buffer;
827 tk->p_buffer = (uint8_t *)malloc( i_frame_buffer );
836 /* Value taken from mplayer */
837 if( !strcmp( sub->mediumName(), "audio" ) )
839 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
840 tk->fmt.audio.i_channels = sub->numChannels();
841 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
843 if( !strcmp( sub->codecName(), "MPA" ) ||
844 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
845 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
847 tk->fmt.i_codec = VLC_CODEC_MPGA;
848 tk->fmt.audio.i_rate = 0;
850 else if( !strcmp( sub->codecName(), "AC3" ) )
852 tk->fmt.i_codec = VLC_CODEC_A52;
853 tk->fmt.audio.i_rate = 0;
855 else if( !strcmp( sub->codecName(), "L16" ) )
857 tk->fmt.i_codec = VLC_CODEC_S16B;
858 tk->fmt.audio.i_bitspersample = 16;
860 else if( !strcmp( sub->codecName(), "L20" ) )
862 tk->fmt.i_codec = VLC_CODEC_S20B;
863 tk->fmt.audio.i_bitspersample = 20;
865 else if( !strcmp( sub->codecName(), "L24" ) )
867 tk->fmt.i_codec = VLC_CODEC_S24B;
868 tk->fmt.audio.i_bitspersample = 24;
870 else if( !strcmp( sub->codecName(), "L8" ) )
872 tk->fmt.i_codec = VLC_CODEC_U8;
873 tk->fmt.audio.i_bitspersample = 8;
875 else if( !strcmp( sub->codecName(), "DAT12" ) )
877 tk->fmt.i_codec = VLC_CODEC_DAT12;
878 tk->fmt.audio.i_bitspersample = 12;
880 else if( !strcmp( sub->codecName(), "PCMU" ) )
882 tk->fmt.i_codec = VLC_CODEC_MULAW;
883 tk->fmt.audio.i_bitspersample = 8;
885 else if( !strcmp( sub->codecName(), "PCMA" ) )
887 tk->fmt.i_codec = VLC_CODEC_ALAW;
888 tk->fmt.audio.i_bitspersample = 8;
890 else if( !strncmp( sub->codecName(), "G726", 4 ) )
892 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
893 tk->fmt.audio.i_rate = 8000;
894 tk->fmt.audio.i_channels = 1;
895 if( !strcmp( sub->codecName()+5, "40" ) )
896 tk->fmt.i_bitrate = 40000;
897 else if( !strcmp( sub->codecName()+5, "32" ) )
898 tk->fmt.i_bitrate = 32000;
899 else if( !strcmp( sub->codecName()+5, "24" ) )
900 tk->fmt.i_bitrate = 24000;
901 else if( !strcmp( sub->codecName()+5, "16" ) )
902 tk->fmt.i_bitrate = 16000;
904 else if( !strcmp( sub->codecName(), "AMR" ) )
906 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
908 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
910 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
912 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
914 unsigned int i_extra;
917 tk->fmt.i_codec = VLC_CODEC_MP4A;
919 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
922 tk->fmt.i_extra = i_extra;
923 tk->fmt.p_extra = xmalloc( i_extra );
924 memcpy( tk->fmt.p_extra, p_extra, i_extra );
927 /* Because the "faad" decoder does not handle the LATM
928 * data length field at the start of each returned LATM
929 * frame, tell the RTP source to omit. */
930 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
932 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
934 unsigned int i_extra;
937 tk->fmt.i_codec = VLC_CODEC_MP4A;
939 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
942 tk->fmt.i_extra = i_extra;
943 tk->fmt.p_extra = xmalloc( i_extra );
944 memcpy( tk->fmt.p_extra, p_extra, i_extra );
948 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
951 if( p_sys->p_out_asf == NULL )
952 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
955 else if( !strcmp( sub->codecName(), "X-QT" ) ||
956 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
958 tk->b_quicktime = true;
960 else if( !strcmp( sub->codecName(), "SPEEX" ) )
962 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
963 if ( tk->fmt.audio.i_rate == 0 )
965 msg_Warn( p_demux,"Using 8kHz as default sample rate." );
966 tk->fmt.audio.i_rate = 8000;
969 else if( !strcmp( sub->codecName(), "VORBIS" ) )
971 tk->fmt.i_codec = VLC_CODEC_VORBIS;
972 unsigned int i_extra;
973 unsigned char *p_extra;
974 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
977 tk->fmt.i_extra = i_extra;
978 tk->fmt.p_extra = p_extra;
981 msg_Warn( p_demux,"Missing or unsupported vorbis header." );
984 else if( !strcmp( sub->mediumName(), "video" ) )
986 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
987 if( !strcmp( sub->codecName(), "MPV" ) )
989 tk->fmt.i_codec = VLC_CODEC_MPGV;
990 tk->fmt.b_packetized = false;
992 else if( !strcmp( sub->codecName(), "H263" ) ||
993 !strcmp( sub->codecName(), "H263-1998" ) ||
994 !strcmp( sub->codecName(), "H263-2000" ) )
996 tk->fmt.i_codec = VLC_CODEC_H263;
998 else if( !strcmp( sub->codecName(), "H261" ) )
1000 tk->fmt.i_codec = VLC_CODEC_H261;
1002 else if( !strcmp( sub->codecName(), "H264" ) )
1004 unsigned int i_extra = 0;
1005 uint8_t *p_extra = NULL;
1007 tk->fmt.i_codec = VLC_CODEC_H264;
1008 tk->fmt.b_packetized = false;
1010 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
1013 tk->fmt.i_extra = i_extra;
1014 tk->fmt.p_extra = xmalloc( i_extra );
1015 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1020 else if( !strcmp( sub->codecName(), "JPEG" ) )
1022 tk->fmt.i_codec = VLC_CODEC_MJPG;
1024 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1026 unsigned int i_extra;
1029 tk->fmt.i_codec = VLC_CODEC_MP4V;
1031 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1034 tk->fmt.i_extra = i_extra;
1035 tk->fmt.p_extra = xmalloc( i_extra );
1036 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1040 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1041 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1042 !strcmp( sub->codecName(), "X-QDM" ) ||
1043 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1044 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1046 tk->b_quicktime = true;
1048 else if( !strcmp( sub->codecName(), "MP2T" ) )
1051 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
1053 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1054 !strcmp( sub->codecName(), "MP1S" ) )
1057 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
1060 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1063 if( p_sys->p_out_asf == NULL )
1064 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
1067 else if( !strcmp( sub->codecName(), "DV" ) )
1070 tk->b_discard_trunc = true;
1071 tk->p_out_muxed = stream_DemuxNew( p_demux, "rawdv",
1074 else if( !strcmp( sub->codecName(), "VP8" ) )
1076 tk->fmt.i_codec = VLC_CODEC_VP8;
1079 else if( !strcmp( sub->mediumName(), "text" ) )
1081 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1083 if( !strcmp( sub->codecName(), "T140" ) )
1085 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1089 if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
1091 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1094 if( sub->rtcpInstance() != NULL )
1096 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1099 if( tk->p_es || tk->b_quicktime || ( tk->b_muxed && tk->p_out_muxed ) ||
1100 ( tk->b_asf && p_sys->p_out_asf ) )
1102 TAB_APPEND_CAST( (live_track_t **), p_sys->i_track, p_sys->track, tk );
1107 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1108 es_format_Clean( &tk->fmt );
1114 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1116 /* Retrieve the starttime if possible */
1117 p_sys->f_npt_start = p_sys->ms->playStartTime();
1119 /* Retrieve the duration if possible */
1120 p_sys->f_npt_length = p_sys->ms->playEndTime();
1123 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1126 p_sys->b_no_data = true;
1127 p_sys->i_no_data_ti = 0;
1132 /*****************************************************************************
1133 * Play: starts the actual playback of the stream
1134 *****************************************************************************/
1135 static int Play( demux_t *p_demux )
1137 demux_sys_t *p_sys = p_demux->p_sys;
1142 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_npt_start, -1, 1 );
1144 if( !wait_Live555_response(p_demux) )
1146 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1147 return VLC_EGENERIC;
1150 /* Retrieve the timeout value and set up a timeout prevention thread */
1151 p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
1152 if( p_sys->i_timeout <= 0 )
1153 p_sys->i_timeout = 60; /* default value from RFC2326 */
1155 /* start timeout-thread only if GET_PARAMETER is supported by the server */
1156 /* or start it if wmserver dialect, since they don't report that GET_PARAMETER is supported correctly */
1157 if( !p_sys->p_timeout && ( p_sys->b_get_param || var_InheritBool( p_demux, "rtsp-wmserver" ) ) )
1159 msg_Dbg( p_demux, "We have a timeout of %d seconds", p_sys->i_timeout );
1160 p_sys->p_timeout = (timeout_thread_t *)malloc( sizeof(timeout_thread_t) );
1161 if( p_sys->p_timeout )
1163 memset( p_sys->p_timeout, 0, sizeof(timeout_thread_t) );
1164 p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
1165 if( vlc_clone( &p_sys->p_timeout->handle, TimeoutPrevention,
1166 p_sys->p_timeout, VLC_THREAD_PRIORITY_LOW ) )
1168 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1169 free( p_sys->p_timeout );
1170 p_sys->p_timeout = NULL;
1173 msg_Dbg( p_demux, "spawned timeout thread" );
1176 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1181 /* Retrieve the starttime if possible */
1182 p_sys->f_npt_start = p_sys->ms->playStartTime();
1183 if( p_sys->ms->playEndTime() > 0 )
1184 p_sys->f_npt_length = p_sys->ms->playEndTime();
1186 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1191 /*****************************************************************************
1193 *****************************************************************************/
1194 static int Demux( demux_t *p_demux )
1196 demux_sys_t *p_sys = p_demux->p_sys;
1199 bool b_send_pcr = true;
1203 /* Check if we need to send the server a Keep-A-Live signal */
1204 if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
1206 char *psz_bye = NULL;
1207 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms, NULL, psz_bye );
1208 p_sys->b_timeout_call = false;
1211 for( i = 0; i < p_sys->i_track; i++ )
1213 live_track_t *tk = p_sys->track[i];
1218 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1219 if( !b && tk->b_selected )
1221 tk->b_selected = false;
1222 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1224 else if( b && !tk->b_selected)
1226 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1227 var_GetBool( p_demux, "rtsp-http" );
1228 p_sys->rtsp->sendSetupCommand( *tk->sub, default_live555_callback, False,
1229 toBool( b_rtsp_tcp ),
1230 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
1231 if( !wait_Live555_response( p_demux ) )
1233 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
1234 tk->sub->mediumName(), tk->sub->codecName(),
1235 p_sys->env->getResultMsg() );
1239 p_sys->rtsp->sendPlayCommand( *tk->sub, default_live555_callback, -1, -1, p_sys->ms->scale() );
1240 if( !wait_Live555_response(p_demux) )
1242 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1243 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1246 tk->b_selected = true;
1248 if( !tk->b_selected )
1249 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1253 if( tk->b_asf || tk->b_muxed )
1260 else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
1266 if( p_sys->i_pcr > 0 )
1269 es_out_Control( p_demux->out, ES_OUT_SET_PCR, 1 + p_sys->i_pcr );
1272 /* First warn we want to read data */
1273 p_sys->event_data = 0;
1274 for( i = 0; i < p_sys->i_track; i++ )
1276 live_track_t *tk = p_sys->track[i];
1278 if( tk->waiting == 0 )
1281 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1282 StreamRead, tk, StreamClose, tk );
1285 /* Create a task that will be called if we wait more than 300ms */
1286 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1289 p_sys->scheduler->doEventLoop( &p_sys->event_data );
1291 /* remove the task */
1292 p_sys->scheduler->unscheduleDelayedTask( task );
1294 /* Check for gap in pts value */
1295 for( i = 0; i < p_sys->i_track; i++ )
1297 live_track_t *tk = p_sys->track[i];
1299 if( !tk->b_muxed && !tk->b_rtcp_sync &&
1300 tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1302 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1304 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1305 tk->b_rtcp_sync = true;
1307 tk->i_pts = VLC_TS_INVALID;
1315 if( p_sys->b_multicast && p_sys->b_no_data &&
1316 ( p_sys->i_no_data_ti > 120 ) )
1318 /* FIXME Make this configurable
1319 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1323 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1324 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1326 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1327 var_GetBool( p_demux, "rtsp-http" );
1329 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1331 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1332 if( RollOverTcp( p_demux ) )
1334 msg_Err( p_demux, "TCP rollover failed, aborting" );
1339 msg_Err( p_demux, "no data received in 10s, aborting" );
1342 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1343 ( p_sys->i_no_data_ti > 34 ) )
1346 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1349 return p_sys->b_error ? 0 : 1;
1352 /*****************************************************************************
1354 *****************************************************************************/
1355 static int Control( demux_t *p_demux, int i_query, va_list args )
1357 demux_sys_t *p_sys = p_demux->p_sys;
1365 case DEMUX_GET_TIME:
1366 pi64 = (int64_t*)va_arg( args, int64_t * );
1367 if( p_sys->f_npt > 0 )
1369 *pi64 = (int64_t)(p_sys->f_npt * 1000000.);
1372 return VLC_EGENERIC;
1374 case DEMUX_GET_LENGTH:
1375 pi64 = (int64_t*)va_arg( args, int64_t * );
1376 if( p_sys->f_npt_length > 0 )
1378 double d_length = p_sys->f_npt_length * 1000000.0;
1379 if( d_length >= INT64_MAX )
1382 *pi64 = (int64_t)d_length;
1385 return VLC_EGENERIC;
1387 case DEMUX_GET_POSITION:
1388 pf = (double*)va_arg( args, double* );
1389 if( (p_sys->f_npt_length > 0) && (p_sys->f_npt > 0) )
1391 *pf = p_sys->f_npt / p_sys->f_npt_length;
1394 return VLC_EGENERIC;
1396 case DEMUX_SET_POSITION:
1397 case DEMUX_SET_TIME:
1398 if( p_sys->rtsp && (p_sys->f_npt_length > 0) )
1403 if( (i_query == DEMUX_SET_TIME) && (p_sys->f_npt > 0) )
1405 i64 = (int64_t)va_arg( args, int64_t );
1406 time = (float)(i64 / 1000000.0); /* in second */
1408 else if( i_query == DEMUX_SET_TIME )
1409 return VLC_EGENERIC;
1412 f = (double)va_arg( args, double );
1413 time = f * p_sys->f_npt_length; /* in second */
1416 if( p_sys->b_paused )
1418 p_sys->f_seek_request = time;
1422 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1424 if( !wait_Live555_response( p_demux ) )
1426 msg_Err( p_demux, "PAUSE before seek failed %s",
1427 p_sys->env->getResultMsg() );
1428 return VLC_EGENERIC;
1431 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1433 if( !wait_Live555_response( p_demux ) )
1435 msg_Err( p_demux, "seek PLAY failed %s",
1436 p_sys->env->getResultMsg() );
1437 return VLC_EGENERIC;
1441 for( i = 0; i < p_sys->i_track; i++ )
1443 p_sys->track[i]->b_rtcp_sync = false;
1444 p_sys->track[i]->i_pts = VLC_TS_INVALID;
1447 /* Retrieve the starttime if possible */
1448 p_sys->f_npt = p_sys->f_npt_start = p_sys->ms->playStartTime();
1450 /* Retrieve the duration if possible */
1451 if( p_sys->ms->playEndTime() > 0 )
1452 p_sys->f_npt_length = p_sys->ms->playEndTime();
1454 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1457 return VLC_EGENERIC;
1459 /* Special for access_demux */
1460 case DEMUX_CAN_PAUSE:
1461 case DEMUX_CAN_SEEK:
1462 pb = (bool*)va_arg( args, bool * );
1463 if( p_sys->rtsp && p_sys->f_npt_length > 0 )
1464 /* Not always true, but will be handled in SET_PAUSE_STATE */
1470 case DEMUX_CAN_CONTROL_PACE:
1471 pb = (bool*)va_arg( args, bool * );
1473 #if 1 /* Disable for now until we have a clock synchro algo
1474 * which works with something else than MPEG over UDP */
1481 case DEMUX_CAN_CONTROL_RATE:
1482 pb = (bool*)va_arg( args, bool * );
1483 pb2 = (bool*)va_arg( args, bool * );
1485 *pb = (p_sys->rtsp != NULL) &&
1486 (p_sys->f_npt_length > 0) &&
1487 ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1488 !var_GetBool( p_demux, "rtsp-wmserver" ) );
1492 case DEMUX_SET_RATE:
1494 double f_scale, f_old_scale;
1496 if( !p_sys->rtsp || (p_sys->f_npt_length <= 0) ||
1497 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1498 var_GetBool( p_demux, "rtsp-wmserver" ) )
1499 return VLC_EGENERIC;
1501 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1504 * "[...] should try to approximate the viewing rate, but
1505 * may restrict the range of scale values that it supports.
1506 * The response MUST contain the actual scale value chosen
1509 * Scale = 1 indicates normal play
1510 * Scale > 1 indicates fast forward
1511 * Scale < 1 && Scale > 0 indicates slow motion
1512 * Scale < 0 value indicates rewind
1515 pi_int = (int*)va_arg( args, int * );
1516 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1517 f_old_scale = p_sys->ms->scale();
1519 /* Passing -1 for the start and end time will mean liveMedia won't
1520 * create a Range: section for the RTSP message. The server should
1521 * pick up from the current position */
1522 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1524 if( !wait_Live555_response( p_demux ) )
1526 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1527 p_sys->env->getResultMsg() );
1528 return VLC_EGENERIC;
1531 if( p_sys->ms->scale() == f_old_scale )
1533 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1534 p_sys->ms->scale() );
1535 return VLC_EGENERIC;
1538 /* ReSync the stream */
1539 p_sys->f_npt_start = 0;
1543 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1544 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1548 case DEMUX_SET_PAUSE_STATE:
1550 bool b_pause = (bool)va_arg( args, int );
1551 if( p_sys->rtsp == NULL )
1552 return VLC_EGENERIC;
1554 if( b_pause == p_sys->b_paused )
1557 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1559 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1560 -1.0f, p_sys->ms->scale() );
1562 if( !wait_Live555_response( p_demux ) )
1564 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1565 return VLC_EGENERIC;
1567 p_sys->f_seek_request = -1;
1568 p_sys->b_paused = b_pause;
1570 /* When we Pause, we'll need the TimeoutPrevention thread to
1571 * handle sending the "Keep Alive" message to the server.
1572 * Unfortunately Live555 isn't thread safe and so can't
1573 * do this normally while the main Demux thread is handling
1574 * a live stream. We end up with the Timeout thread blocking
1575 * waiting for a response from the server. So when we PAUSE
1576 * we set a flag that the TimeoutPrevention function will check
1577 * and if it's set, it will trigger the GET_PARAMETER message */
1578 if( p_sys->b_paused && p_sys->p_timeout != NULL )
1579 p_sys->p_timeout->b_handle_keep_alive = true;
1580 else if( !p_sys->b_paused && p_sys->p_timeout != NULL )
1581 p_sys->p_timeout->b_handle_keep_alive = false;
1583 if( !p_sys->b_paused )
1585 for( int i = 0; i < p_sys->i_track; i++ )
1587 live_track_t *tk = p_sys->track[i];
1588 tk->b_rtcp_sync = false;
1589 tk->i_pts = VLC_TS_INVALID;
1591 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1595 /* Reset data received counter */
1596 p_sys->i_no_data_ti = 0;
1598 /* Retrieve the starttime if possible */
1599 p_sys->f_npt_start = p_sys->ms->playStartTime();
1601 /* Retrieve the duration if possible */
1602 if( p_sys->ms->playEndTime() )
1603 p_sys->f_npt_length = p_sys->ms->playEndTime();
1605 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1608 case DEMUX_GET_TITLE_INFO:
1609 case DEMUX_SET_TITLE:
1610 case DEMUX_SET_SEEKPOINT:
1611 return VLC_EGENERIC;
1613 case DEMUX_GET_PTS_DELAY:
1614 pi64 = (int64_t*)va_arg( args, int64_t * );
1615 *pi64 = INT64_C(1000)
1616 * var_InheritInteger( p_demux, "network-caching" );
1620 return VLC_EGENERIC;
1624 /*****************************************************************************
1625 * RollOverTcp: reopen the rtsp into TCP mode
1626 * XXX: ugly, a lot of code are duplicated from Open()
1627 * This should REALLY be fixed
1628 *****************************************************************************/
1629 static int RollOverTcp( demux_t *p_demux )
1631 demux_sys_t *p_sys = p_demux->p_sys;
1634 var_SetBool( p_demux, "rtsp-tcp", true );
1636 /* We close the old RTSP session */
1637 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1638 Medium::close( p_sys->ms );
1639 RTSPClient::close( p_sys->rtsp );
1641 for( i = 0; i < p_sys->i_track; i++ )
1643 live_track_t *tk = p_sys->track[i];
1645 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
1646 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1647 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1648 es_format_Clean( &tk->fmt );
1649 free( tk->p_buffer );
1652 TAB_CLEAN( p_sys->i_track, p_sys->track );
1653 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
1657 p_sys->b_no_data = true;
1658 p_sys->i_no_data_ti = 0;
1659 p_sys->p_out_asf = NULL;
1661 /* Reopen rtsp client */
1662 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1664 msg_Err( p_demux, "Failed to connect with rtsp://%s",
1669 if( p_sys->p_sdp == NULL )
1671 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1675 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1677 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1681 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1687 return VLC_EGENERIC;
1691 /*****************************************************************************
1693 *****************************************************************************/
1694 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1696 const uint8_t *p_data, unsigned i_size )
1698 const unsigned i_packet_size = p_demux->p_sys->asfh.i_min_data_packet_size;
1699 block_t *p_list = NULL;
1701 while( i_size >= 4 )
1703 unsigned i_flags = p_data[0];
1704 unsigned i_length_offset = (p_data[1] << 16) |
1707 bool b_length = i_flags & 0x40;
1708 bool b_relative_ts = i_flags & 0x20;
1709 bool b_duration = i_flags & 0x10;
1710 bool b_location_id = i_flags & 0x08;
1712 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1713 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1714 unsigned i_header_size = 4;
1722 if( i_header_size > i_size )
1724 msg_Warn( p_demux, "Invalid header size" );
1729 * When b_length is true, the streams I found do not seems to respect
1730 * the documentation.
1731 * From them, I have failed to find which choice between '__MIN()' or
1732 * 'i_length_offset - i_header_size' is the right one.
1736 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1738 i_payload = i_size - i_header_size;
1740 if( !tk->p_asf_block )
1742 tk->p_asf_block = block_Alloc( i_packet_size );
1743 if( !tk->p_asf_block )
1745 tk->p_asf_block->i_buffer = 0;
1747 unsigned i_offset = b_length ? 0 : i_length_offset;
1748 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1750 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1751 tk->p_asf_block->i_buffer += i_payload;
1754 /* We have a complete packet */
1755 tk->p_asf_block->i_buffer = i_packet_size;
1756 block_ChainAppend( &p_list, tk->p_asf_block );
1757 tk->p_asf_block = NULL;
1762 /* Reset on broken stream */
1763 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1764 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1765 tk->p_asf_block->i_buffer = 0;
1769 p_data += i_header_size + i_payload;
1770 i_size -= i_header_size + i_payload;
1775 /*****************************************************************************
1777 *****************************************************************************/
1778 static void StreamRead( void *p_private, unsigned int i_size,
1779 unsigned int i_truncated_bytes, struct timeval pts,
1780 unsigned int duration )
1782 VLC_UNUSED( duration );
1784 live_track_t *tk = (live_track_t*)p_private;
1785 demux_t *p_demux = tk->p_demux;
1786 demux_sys_t *p_sys = p_demux->p_sys;
1789 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1791 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1792 (int64_t)pts.tv_usec;
1794 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1795 i_pts &= INT64_C(0x00ffffffffffffff);
1797 /* Retrieve NPT for this pts */
1798 tk->f_npt = tk->sub->getNormalPlayTime(pts);
1800 if( tk->b_quicktime && tk->p_es == NULL )
1802 QuickTimeGenericRTPSource *qtRTPSource =
1803 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1804 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1805 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1807 /* Get codec informations from the quicktime atoms :
1808 * http://developer.apple.com/quicktime/icefloe/dispatch026.html */
1809 if( tk->fmt.i_cat == VIDEO_ES ) {
1810 if( qtState.sdAtomSize < 16 + 32 )
1813 p_sys->event_data = 0xff;
1817 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1818 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1819 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1821 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1823 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1824 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1825 + qtRTPSource->qtState.sdAtomSize;
1826 while (pos+8 < endpos) {
1827 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1828 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1829 if( memcmp(pos+4, "avcC", 4) == 0 &&
1831 atomLength <= INT_MAX )
1833 tk->fmt.i_extra = atomLength-8;
1834 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1835 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1843 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1844 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1845 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1849 if( qtState.sdAtomSize < 24 )
1852 p_sys->event_data = 0xff;
1856 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1857 tk->fmt.audio.i_bitspersample = (sdAtom[22] << 8) | sdAtom[23];
1859 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1863 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1865 pts.tv_sec * 1000000LL + pts.tv_usec );
1868 /* grow buffer if it looks like buffer is too small, but don't eat
1869 * up all the memory on strange streams */
1870 if( i_truncated_bytes > 0 )
1872 if( tk->i_buffer < 2000000 )
1875 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1876 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1877 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1880 msg_Warn( p_demux, "realloc failed" );
1884 tk->p_buffer = (uint8_t*)p_tmp;
1889 if( tk->b_discard_trunc )
1891 p_sys->event_data = 0xff;
1897 assert( i_size <= tk->i_buffer );
1899 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1900 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1902 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1904 p_block = block_Alloc( i_size + 1 );
1905 p_block->p_buffer[0] = amrSource->lastFrameHeader();
1906 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1908 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1910 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1911 uint32_t header = h261Source->lastSpecialHeader();
1912 p_block = block_Alloc( i_size + 4 );
1913 memcpy( p_block->p_buffer, &header, 4 );
1914 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1916 if( tk->sub->rtpSource()->curPacketMarkerBit() )
1917 p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1919 else if( tk->fmt.i_codec == VLC_CODEC_H264 )
1921 if( (tk->p_buffer[0] & 0x1f) >= 24 )
1922 msg_Warn( p_demux, "unsupported NAL type for H264" );
1924 /* Normal NAL type */
1925 p_block = block_Alloc( i_size + 4 );
1926 p_block->p_buffer[0] = 0x00;
1927 p_block->p_buffer[1] = 0x00;
1928 p_block->p_buffer[2] = 0x00;
1929 p_block->p_buffer[3] = 0x01;
1930 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1932 else if( tk->b_asf )
1934 p_block = StreamParseAsf( p_demux, tk,
1935 tk->sub->rtpSource()->curPacketMarkerBit(),
1936 tk->p_buffer, i_size );
1940 p_block = block_Alloc( i_size );
1941 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1944 if( p_sys->i_pcr < i_pts )
1946 p_sys->i_pcr = i_pts;
1949 /* Update our global npt value */
1950 if( tk->f_npt > 0 &&
1951 ( tk->f_npt < p_sys->f_npt_length || p_sys->f_npt_length <= 0 ) )
1952 p_sys->f_npt = tk->f_npt;
1956 if( !tk->b_muxed && !tk->b_asf )
1958 if( i_pts != tk->i_pts )
1959 p_block->i_pts = VLC_TS_0 + i_pts;
1960 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
1961 p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? VLC_TS_INVALID : (VLC_TS_0 + i_pts);
1965 stream_DemuxSend( tk->p_out_muxed, p_block );
1966 else if( tk->b_asf )
1967 stream_DemuxSend( p_sys->p_out_asf, p_block );
1969 es_out_Send( p_demux->out, tk->p_es, p_block );
1972 /* warn that's ok */
1973 p_sys->event_data = 0xff;
1975 /* we have read data */
1977 p_demux->p_sys->b_no_data = false;
1978 p_demux->p_sys->i_no_data_ti = 0;
1980 if( i_pts > 0 && !tk->b_muxed )
1986 /*****************************************************************************
1988 *****************************************************************************/
1989 static void StreamClose( void *p_private )
1991 live_track_t *tk = (live_track_t*)p_private;
1992 demux_t *p_demux = tk->p_demux;
1993 demux_sys_t *p_sys = p_demux->p_sys;
1994 tk->b_selected = false;
1995 p_sys->event_rtsp = 0xff;
1996 p_sys->event_data = 0xff;
1999 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
2002 for( int i = 0; i < p_sys->i_track; i++ )
2004 if( p_sys->track[i]->b_selected )
2007 msg_Dbg( p_demux, "RTSP track Close, %d track remaining", nb_tracks );
2009 p_sys->b_error = true;
2013 /*****************************************************************************
2015 *****************************************************************************/
2016 static void TaskInterruptRTSP( void *p_private )
2018 demux_t *p_demux = (demux_t*)p_private;
2021 p_demux->p_sys->event_rtsp = 0xff;
2024 static void TaskInterruptData( void *p_private )
2026 demux_t *p_demux = (demux_t*)p_private;
2028 p_demux->p_sys->i_no_data_ti++;
2031 p_demux->p_sys->event_data = 0xff;
2034 /*****************************************************************************
2036 *****************************************************************************/
2038 static void* TimeoutPrevention( void *p_data )
2040 timeout_thread_t *p_timeout = (timeout_thread_t *)p_data;
2044 /* Voodoo (= no) thread safety here! *Ahem* */
2045 if( p_timeout->b_handle_keep_alive )
2047 char *psz_bye = NULL;
2048 int canc = vlc_savecancel ();
2050 p_timeout->p_sys->rtsp->sendGetParameterCommand( *p_timeout->p_sys->ms, NULL, psz_bye );
2051 vlc_restorecancel (canc);
2053 p_timeout->p_sys->b_timeout_call = !p_timeout->b_handle_keep_alive;
2055 msleep (((int64_t)p_timeout->p_sys->i_timeout - 2) * CLOCK_FREQ);
2057 assert(0); /* dead code */
2060 /*****************************************************************************
2062 *****************************************************************************/
2063 static int ParseASF( demux_t *p_demux )
2065 demux_sys_t *p_sys = p_demux->p_sys;
2067 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
2068 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2072 /* Parse the asf header */
2073 if( psz_asf == NULL )
2074 return VLC_EGENERIC;
2076 psz_asf += strlen( psz_marker );
2077 psz_asf = strdup( psz_asf ); /* Duplicate it */
2078 psz_end = strchr( psz_asf, '\n' );
2080 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2083 if( psz_asf >= psz_end )
2086 return VLC_EGENERIC;
2089 /* Always smaller */
2090 p_header = block_Alloc( psz_end - psz_asf );
2091 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2092 p_header->i_buffer, psz_asf );
2093 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2094 if( p_header->i_buffer <= 0 )
2097 return VLC_EGENERIC;
2100 /* Parse it to get packet size */
2101 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2103 /* Send it to demuxer */
2104 stream_DemuxSend( p_sys->p_out_asf, p_header );
2111 static unsigned char* parseH264ConfigStr( char const* configStr,
2112 unsigned int& configSize )
2115 size_t i_records = 1;
2119 if( configStr == NULL || *configStr == '\0' )
2122 psz = dup = strdup( configStr );
2124 /* Count the number of commas */
2125 for( psz = dup; *psz != '\0'; ++psz )
2134 size_t configMax = 5*strlen(dup);
2135 unsigned char *cfg = new unsigned char[configMax];
2137 for( size_t i = 0; i < i_records; ++i )
2139 cfg[configSize++] = 0x00;
2140 cfg[configSize++] = 0x00;
2141 cfg[configSize++] = 0x00;
2142 cfg[configSize++] = 0x01;
2144 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2145 configMax-configSize, psz );
2146 psz += strlen(psz)+1;
2153 static uint8_t *parseVorbisConfigStr( char const* configStr,
2154 unsigned int& configSize )
2157 if( configStr == NULL || *configStr == '\0' )
2159 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1332115200 // 2012.03.20
2160 unsigned char *p_cfg = base64Decode( configStr, configSize );
2162 char* configStr_dup = strdup( configStr );
2163 unsigned char *p_cfg = base64Decode( configStr_dup, configSize );
2164 free( configStr_dup );
2166 uint8_t *p_extra = NULL;
2167 /* skip header count, ident number and length (cf. RFC 5215) */
2168 const unsigned int headerSkip = 9;
2169 if( configSize > headerSkip && ((uint8_t*)p_cfg)[3] == 1 )
2171 configSize -= headerSkip;
2172 p_extra = (uint8_t*)xmalloc( configSize );
2173 memcpy( p_extra, p_cfg+headerSkip, configSize );