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 )
253 static int Demux ( demux_t * );
254 static int Control( demux_t *, int, va_list );
256 static int Connect ( demux_t * );
257 static int SessionsSetup( demux_t * );
258 static int Play ( demux_t *);
259 static int ParseASF ( demux_t * );
260 static int RollOverTcp ( demux_t * );
262 static void StreamRead ( void *, unsigned int, unsigned int,
263 struct timeval, unsigned int );
264 static void StreamClose ( void * );
265 static void TaskInterruptData( void * );
266 static void TaskInterruptRTSP( void * );
268 static void* TimeoutPrevention( void * );
270 static unsigned char* parseH264ConfigStr( char const* configStr,
271 unsigned int& configSize );
272 static unsigned char* parseVorbisConfigStr( char const* configStr,
273 unsigned int& configSize );
275 /*****************************************************************************
277 *****************************************************************************/
278 static int Open ( vlc_object_t *p_this )
280 demux_t *p_demux = (demux_t*)p_this;
281 demux_sys_t *p_sys = NULL;
284 int i_error = VLC_EGENERIC;
288 /* See if it looks like a SDP
289 v, o, s fields are mandatory and in this order */
290 const uint8_t *p_peek;
291 if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
293 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
294 memcmp( p_peek, "v=0\n", 4 ) &&
295 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
301 p_demux->pf_demux = Demux;
302 p_demux->pf_control= Control;
303 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
304 if( !p_sys ) return VLC_ENOMEM;
306 msg_Dbg( p_demux, "version "LIVEMEDIA_LIBRARY_VERSION_STRING );
308 TAB_INIT( p_sys->i_track, p_sys->track );
310 p_sys->f_npt_start = 0.;
311 p_sys->f_npt_length = 0.;
312 p_sys->b_no_data = true;
313 p_sys->psz_path = strdup( p_demux->psz_location );
314 p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
315 p_sys->f_seek_request = -1;
317 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
318 vlc_UrlParse( &p_sys->url, p_sys->psz_path, 0 );
320 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
322 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
325 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
327 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
331 if( strcasecmp( p_demux->psz_access, "sdp" ) )
333 char *p = p_sys->psz_path;
334 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
337 if( p_demux->s != NULL )
339 /* Gather the complete sdp file */
341 int i_sdp_max = 1000;
342 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
346 i_error = VLC_ENOMEM;
352 int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
353 i_sdp_max - i_sdp - 1 );
355 if( !vlc_object_alive (p_demux) )
363 msg_Err( p_demux, "failed to read SDP" );
370 if( i_read < i_sdp_max - i_sdp - 1 )
377 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
379 p_sys->p_sdp = (char*)p_sdp;
381 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
383 msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
387 if( p_sys->p_sdp == NULL )
389 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
390 i_error = VLC_ENOMEM;
394 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
396 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
400 if( p_sys->b_real ) goto error;
402 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
405 if( p_sys->p_out_asf && ParseASF( p_demux ) )
407 msg_Err( p_demux, "cannot find a usable asf header" );
408 /* TODO Clean tracks */
412 if( p_sys->i_track <= 0 )
422 /*****************************************************************************
424 *****************************************************************************/
425 static void Close( vlc_object_t *p_this )
427 demux_t *p_demux = (demux_t*)p_this;
428 demux_sys_t *p_sys = p_demux->p_sys;
430 if( p_sys->p_timeout )
432 vlc_cancel( p_sys->p_timeout->handle );
433 vlc_join( p_sys->p_timeout->handle, NULL );
434 free( p_sys->p_timeout );
437 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
438 if( p_sys->ms ) Medium::close( p_sys->ms );
439 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
440 if( p_sys->env ) p_sys->env->reclaim();
442 for( int i = 0; i < p_sys->i_track; i++ )
444 live_track_t *tk = p_sys->track[i];
446 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
447 es_format_Clean( &tk->fmt );
448 free( tk->p_buffer );
451 TAB_CLEAN( p_sys->i_track, p_sys->track );
452 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
453 delete p_sys->scheduler;
454 free( p_sys->p_sdp );
455 free( p_sys->psz_path );
457 vlc_UrlClean( &p_sys->url );
462 static inline const char *strempty( const char *s ) { return s?s:""; }
463 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
465 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
467 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
468 demux_sys_t *p_sys = client_vlc->p_sys;
469 delete []result_string;
470 p_sys->i_live555_ret = result_code;
471 p_sys->b_error = p_sys->i_live555_ret != 0;
472 p_sys->event_rtsp = 1;
475 /* return true if the RTSP command succeeded */
476 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
479 demux_sys_t * p_sys = p_demux->p_sys;
480 p_sys->event_rtsp = 0;
483 /* Create a task that will be called if we wait more than timeout ms */
484 task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000,
488 p_sys->event_rtsp = 0;
489 p_sys->b_error = true;
490 p_sys->i_live555_ret = 0;
491 p_sys->scheduler->doEventLoop( &p_sys->event_rtsp );
492 //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
495 /* remove the task */
496 p_sys->scheduler->unscheduleDelayedTask( task );
498 return !p_sys->b_error;
501 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
502 char* result_string )
504 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
505 demux_sys_t *p_sys = client_vlc->p_sys;
506 p_sys->i_live555_ret = result_code;
507 if ( result_code == 0 )
509 char* sdpDescription = result_string;
510 free( p_sys->p_sdp );
514 p_sys->p_sdp = strdup( sdpDescription );
515 p_sys->b_error = false;
519 p_sys->b_error = true;
520 delete[] result_string;
521 p_sys->event_rtsp = 1;
524 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
525 char* result_string )
527 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
528 demux_sys_t *p_sys = client_vlc->p_sys;
530 // If OPTIONS fails, assume GET_PARAMETER is not supported but
531 // still continue on with the stream. Some servers (foscam)
532 // return 501/not implemented for OPTIONS.
534 && result_string != NULL
535 && strstr( result_string, "GET_PARAMETER" ) != NULL;
536 client->sendDescribeCommand( continueAfterDESCRIBE );
537 delete[] result_string;
540 /*****************************************************************************
541 * Connect: connects to the RTSP server to setup the session DESCRIBE
542 *****************************************************************************/
543 static int Connect( demux_t *p_demux )
545 demux_sys_t *p_sys = p_demux->p_sys;
546 Authenticator authenticator;
547 char *psz_user = NULL;
548 char *psz_pwd = NULL;
549 char *psz_url = NULL;
551 int i_ret = VLC_SUCCESS;
552 const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
554 /* Get the user name and password */
555 if( p_sys->url.psz_username || p_sys->url.psz_password )
557 /* Create the URL by stripping away the username/password part */
558 if( p_sys->url.i_port == 0 )
559 p_sys->url.i_port = 554;
560 if( asprintf( &psz_url, "rtsp://%s:%d%s",
561 strempty( p_sys->url.psz_host ),
563 strempty( p_sys->url.psz_path ) ) == -1 )
566 psz_user = strdup( strempty( p_sys->url.psz_username ) );
567 psz_pwd = strdup( strempty( p_sys->url.psz_password ) );
571 if( asprintf( &psz_url, "rtsp://%s", p_sys->psz_path ) == -1 )
574 psz_user = var_InheritString( p_demux, "rtsp-user" );
575 psz_pwd = var_InheritString( p_demux, "rtsp-pwd" );
579 if( !vlc_object_alive (p_demux) )
581 i_ret = VLC_EGENERIC;
585 if( var_CreateGetBool( p_demux, "rtsp-http" ) )
586 i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
588 p_sys->rtsp = new RTSPClientVlc( *p_sys->env, psz_url,
589 var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
590 "LibVLC/"VERSION, i_http_port, p_sys );
593 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
594 p_sys->env->getResultMsg() );
595 i_ret = VLC_EGENERIC;
599 /* Kasenna enables KeepAlive by analysing the User-Agent string.
600 * Appending _KA to the string should be enough to enable this feature,
601 * however, there is a bug where the _KA doesn't get parsed from the
602 * default User-Agent as created by VLC/Live555 code. This is probably due
603 * to spaces in the string or the string being too long. Here we override
604 * the default string with a more compact version.
606 if( var_InheritBool( p_demux, "rtsp-kasenna" ))
608 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
612 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
614 p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
616 if( !wait_Live555_response( p_demux, i_timeout ) )
618 int i_code = p_sys->i_live555_ret;
621 msg_Dbg( p_demux, "authentication failed" );
625 dialog_Login( p_demux, &psz_user, &psz_pwd,
626 _("RTSP authentication"), "%s",
627 _("Please enter a valid login name and a password.") );
628 if( psz_user != NULL && psz_pwd != NULL )
630 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
634 else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
636 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
637 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
638 var_SetBool( p_demux, "rtsp-http", true );
639 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
646 msg_Dbg( p_demux, "connection timeout" );
649 msg_Dbg( p_demux, "connection error %d", i_code );
651 dialog_Fatal( p_demux, _("RTSP connection failed"),
652 _("Access to the stream is denied by the server configuration.") );
654 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
657 i_ret = VLC_EGENERIC;
661 /* malloc-ated copy */
669 /*****************************************************************************
670 * SessionsSetup: prepares the subsessions and does the SETUP
671 *****************************************************************************/
672 static int SessionsSetup( demux_t *p_demux )
674 demux_sys_t *p_sys = p_demux->p_sys;
675 MediaSubsessionIterator *iter = NULL;
676 MediaSubsession *sub = NULL;
680 int i_return = VLC_SUCCESS;
681 unsigned int i_receive_buffer = 0;
682 int i_frame_buffer = DEFAULT_FRAME_BUFFER_SIZE;
683 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
685 b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
686 var_GetBool( p_demux, "rtsp-http" );
687 i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
690 /* Create the session from the SDP */
691 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
693 msg_Err( p_demux, "Could not create the RTSP Session: %s",
694 p_sys->env->getResultMsg() );
698 /* Initialise each media subsession */
699 iter = new MediaSubsessionIterator( *p_sys->ms );
700 while( ( sub = iter->next() ) != NULL )
705 if( !vlc_object_alive (p_demux) )
711 /* Value taken from mplayer */
712 if( !strcmp( sub->mediumName(), "audio" ) )
713 i_receive_buffer = 100000;
714 else if( !strcmp( sub->mediumName(), "video" ) )
716 int i_var_buf_size = var_InheritInteger( p_demux, "rtsp-frame-buffer-size" );
717 if( i_var_buf_size > 0 )
718 i_frame_buffer = i_var_buf_size;
719 i_receive_buffer = 2000000;
721 else if( !strcmp( sub->mediumName(), "text" ) )
725 if( i_client_port != -1 )
727 sub->setClientPortNum( i_client_port );
731 if( strcasestr( sub->codecName(), "REAL" ) )
733 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
734 p_sys->b_real = true; /* This is a problem, we'll handle it later */
738 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
739 bInit = sub->initiate( 0 );
741 bInit = sub->initiate();
745 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
746 sub->mediumName(), sub->codecName(),
747 p_sys->env->getResultMsg() );
751 if( sub->rtpSource() != NULL )
753 int fd = sub->rtpSource()->RTPgs()->socketNum();
755 /* Increase the buffer size */
756 if( i_receive_buffer > 0 )
757 increaseReceiveBufferTo( *p_sys->env, fd, i_receive_buffer );
759 /* Increase the RTP reorder timebuffer just a bit */
760 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
762 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
765 /* Issue the SETUP */
768 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
769 toBool( b_rtsp_tcp ),
770 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
771 if( !wait_Live555_response( p_demux ) )
773 /* if we get an unsupported transport error, toggle TCP
774 * use and try again */
775 if( p_sys->i_live555_ret == 461 )
776 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
777 !toBool( b_rtsp_tcp ), False );
778 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
780 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
781 sub->mediumName(), sub->codecName(),
782 p_sys->env->getResultMsg() );
787 var_SetBool( p_demux, "rtsp-tcp", true );
793 /* Check if we will receive data from this subsession for
795 if( sub->readSource() == NULL ) continue;
796 if( !p_sys->b_multicast )
798 /* We need different rollover behaviour for multicast */
799 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
802 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
808 tk->p_demux = p_demux;
811 tk->b_quicktime = false;
813 tk->p_asf_block = NULL;
815 tk->b_discard_trunc = false;
816 tk->p_out_muxed = NULL;
818 tk->b_rtcp_sync = false;
819 tk->i_pts = VLC_TS_INVALID;
821 tk->b_selected = true;
822 tk->i_buffer = i_frame_buffer;
823 tk->p_buffer = (uint8_t *)malloc( i_frame_buffer );
832 /* Value taken from mplayer */
833 if( !strcmp( sub->mediumName(), "audio" ) )
835 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
836 tk->fmt.audio.i_channels = sub->numChannels();
837 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
839 if( !strcmp( sub->codecName(), "MPA" ) ||
840 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
841 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
843 tk->fmt.i_codec = VLC_CODEC_MPGA;
844 tk->fmt.audio.i_rate = 0;
846 else if( !strcmp( sub->codecName(), "AC3" ) )
848 tk->fmt.i_codec = VLC_CODEC_A52;
849 tk->fmt.audio.i_rate = 0;
851 else if( !strcmp( sub->codecName(), "L16" ) )
853 tk->fmt.i_codec = VLC_CODEC_S16B;
854 tk->fmt.audio.i_bitspersample = 16;
856 else if( !strcmp( sub->codecName(), "L20" ) )
858 tk->fmt.i_codec = VLC_CODEC_S20B;
859 tk->fmt.audio.i_bitspersample = 20;
861 else if( !strcmp( sub->codecName(), "L24" ) )
863 tk->fmt.i_codec = VLC_CODEC_S24B;
864 tk->fmt.audio.i_bitspersample = 24;
866 else if( !strcmp( sub->codecName(), "L8" ) )
868 tk->fmt.i_codec = VLC_CODEC_U8;
869 tk->fmt.audio.i_bitspersample = 8;
871 else if( !strcmp( sub->codecName(), "DAT12" ) )
873 tk->fmt.i_codec = VLC_CODEC_DAT12;
874 tk->fmt.audio.i_bitspersample = 12;
876 else if( !strcmp( sub->codecName(), "PCMU" ) )
878 tk->fmt.i_codec = VLC_CODEC_MULAW;
879 tk->fmt.audio.i_bitspersample = 8;
881 else if( !strcmp( sub->codecName(), "PCMA" ) )
883 tk->fmt.i_codec = VLC_CODEC_ALAW;
884 tk->fmt.audio.i_bitspersample = 8;
886 else if( !strncmp( sub->codecName(), "G726", 4 ) )
888 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
889 tk->fmt.audio.i_rate = 8000;
890 tk->fmt.audio.i_channels = 1;
891 if( !strcmp( sub->codecName()+5, "40" ) )
892 tk->fmt.i_bitrate = 40000;
893 else if( !strcmp( sub->codecName()+5, "32" ) )
894 tk->fmt.i_bitrate = 32000;
895 else if( !strcmp( sub->codecName()+5, "24" ) )
896 tk->fmt.i_bitrate = 24000;
897 else if( !strcmp( sub->codecName()+5, "16" ) )
898 tk->fmt.i_bitrate = 16000;
900 else if( !strcmp( sub->codecName(), "AMR" ) )
902 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
904 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
906 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
908 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
910 unsigned int i_extra;
913 tk->fmt.i_codec = VLC_CODEC_MP4A;
915 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
918 tk->fmt.i_extra = i_extra;
919 tk->fmt.p_extra = xmalloc( i_extra );
920 memcpy( tk->fmt.p_extra, p_extra, i_extra );
923 /* Because the "faad" decoder does not handle the LATM
924 * data length field at the start of each returned LATM
925 * frame, tell the RTP source to omit. */
926 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
928 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
930 unsigned int i_extra;
933 tk->fmt.i_codec = VLC_CODEC_MP4A;
935 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
938 tk->fmt.i_extra = i_extra;
939 tk->fmt.p_extra = xmalloc( i_extra );
940 memcpy( tk->fmt.p_extra, p_extra, i_extra );
944 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
947 if( p_sys->p_out_asf == NULL )
948 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
951 else if( !strcmp( sub->codecName(), "X-QT" ) ||
952 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
954 tk->b_quicktime = true;
956 else if( !strcmp( sub->codecName(), "SPEEX" ) )
958 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
959 if ( tk->fmt.audio.i_rate == 0 )
961 msg_Warn( p_demux,"Using 8kHz as default sample rate." );
962 tk->fmt.audio.i_rate = 8000;
965 else if( !strcmp( sub->codecName(), "VORBIS" ) )
967 tk->fmt.i_codec = VLC_CODEC_VORBIS;
968 unsigned int i_extra;
969 unsigned char *p_extra;
970 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
973 tk->fmt.i_extra = i_extra;
974 tk->fmt.p_extra = p_extra;
977 msg_Warn( p_demux,"Missing or unsupported vorbis header." );
980 else if( !strcmp( sub->mediumName(), "video" ) )
982 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
983 if( !strcmp( sub->codecName(), "MPV" ) )
985 tk->fmt.i_codec = VLC_CODEC_MPGV;
986 tk->fmt.b_packetized = false;
988 else if( !strcmp( sub->codecName(), "H263" ) ||
989 !strcmp( sub->codecName(), "H263-1998" ) ||
990 !strcmp( sub->codecName(), "H263-2000" ) )
992 tk->fmt.i_codec = VLC_CODEC_H263;
994 else if( !strcmp( sub->codecName(), "H261" ) )
996 tk->fmt.i_codec = VLC_CODEC_H261;
998 else if( !strcmp( sub->codecName(), "H264" ) )
1000 unsigned int i_extra = 0;
1001 uint8_t *p_extra = NULL;
1003 tk->fmt.i_codec = VLC_CODEC_H264;
1004 tk->fmt.b_packetized = false;
1006 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
1009 tk->fmt.i_extra = i_extra;
1010 tk->fmt.p_extra = xmalloc( i_extra );
1011 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1016 else if( !strcmp( sub->codecName(), "JPEG" ) )
1018 tk->fmt.i_codec = VLC_CODEC_MJPG;
1020 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1022 unsigned int i_extra;
1025 tk->fmt.i_codec = VLC_CODEC_MP4V;
1027 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1030 tk->fmt.i_extra = i_extra;
1031 tk->fmt.p_extra = xmalloc( i_extra );
1032 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1036 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1037 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1038 !strcmp( sub->codecName(), "X-QDM" ) ||
1039 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1040 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1042 tk->b_quicktime = true;
1044 else if( !strcmp( sub->codecName(), "MP2T" ) )
1047 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
1049 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1050 !strcmp( sub->codecName(), "MP1S" ) )
1053 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
1056 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1059 if( p_sys->p_out_asf == NULL )
1060 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
1063 else if( !strcmp( sub->codecName(), "DV" ) )
1066 tk->b_discard_trunc = true;
1067 tk->p_out_muxed = stream_DemuxNew( p_demux, "rawdv",
1070 else if( !strcmp( sub->codecName(), "VP8" ) )
1072 tk->fmt.i_codec = VLC_CODEC_VP8;
1075 else if( !strcmp( sub->mediumName(), "text" ) )
1077 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1079 if( !strcmp( sub->codecName(), "T140" ) )
1081 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1085 if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
1087 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1090 if( sub->rtcpInstance() != NULL )
1092 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1095 if( tk->p_es || tk->b_quicktime || ( tk->b_muxed && tk->p_out_muxed ) ||
1096 ( tk->b_asf && p_sys->p_out_asf ) )
1098 TAB_APPEND_CAST( (live_track_t **), p_sys->i_track, p_sys->track, tk );
1103 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1104 es_format_Clean( &tk->fmt );
1110 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1112 /* Retrieve the starttime if possible */
1113 p_sys->f_npt_start = p_sys->ms->playStartTime();
1115 /* Retrieve the duration if possible */
1116 p_sys->f_npt_length = p_sys->ms->playEndTime();
1119 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1122 p_sys->b_no_data = true;
1123 p_sys->i_no_data_ti = 0;
1128 /*****************************************************************************
1129 * Play: starts the actual playback of the stream
1130 *****************************************************************************/
1131 static int Play( demux_t *p_demux )
1133 demux_sys_t *p_sys = p_demux->p_sys;
1138 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_npt_start, -1, 1 );
1140 if( !wait_Live555_response(p_demux) )
1142 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1143 return VLC_EGENERIC;
1146 /* Retrieve the timeout value and set up a timeout prevention thread */
1147 p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
1148 if( p_sys->i_timeout <= 0 )
1149 p_sys->i_timeout = 60; /* default value from RFC2326 */
1151 /* start timeout-thread only if GET_PARAMETER is supported by the server */
1152 /* or start it if wmserver dialect, since they don't report that GET_PARAMETER is supported correctly */
1153 if( !p_sys->p_timeout && ( p_sys->b_get_param || var_InheritBool( p_demux, "rtsp-wmserver" ) ) )
1155 msg_Dbg( p_demux, "We have a timeout of %d seconds", p_sys->i_timeout );
1156 p_sys->p_timeout = (timeout_thread_t *)malloc( sizeof(timeout_thread_t) );
1157 if( p_sys->p_timeout )
1159 memset( p_sys->p_timeout, 0, sizeof(timeout_thread_t) );
1160 p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
1161 if( vlc_clone( &p_sys->p_timeout->handle, TimeoutPrevention,
1162 p_sys->p_timeout, VLC_THREAD_PRIORITY_LOW ) )
1164 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1165 free( p_sys->p_timeout );
1166 p_sys->p_timeout = NULL;
1169 msg_Dbg( p_demux, "spawned timeout thread" );
1172 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1177 /* Retrieve the starttime if possible */
1178 p_sys->f_npt_start = p_sys->ms->playStartTime();
1179 if( p_sys->ms->playEndTime() > 0 )
1180 p_sys->f_npt_length = p_sys->ms->playEndTime();
1182 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1187 /*****************************************************************************
1189 *****************************************************************************/
1190 static int Demux( demux_t *p_demux )
1192 demux_sys_t *p_sys = p_demux->p_sys;
1195 bool b_send_pcr = true;
1199 /* Check if we need to send the server a Keep-A-Live signal */
1200 if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
1202 char *psz_bye = NULL;
1203 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms, NULL, psz_bye );
1204 p_sys->b_timeout_call = false;
1207 for( i = 0; i < p_sys->i_track; i++ )
1209 live_track_t *tk = p_sys->track[i];
1214 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1215 if( !b && tk->b_selected )
1217 tk->b_selected = false;
1218 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1220 else if( b && !tk->b_selected)
1222 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1223 var_GetBool( p_demux, "rtsp-http" );
1224 p_sys->rtsp->sendSetupCommand( *tk->sub, default_live555_callback, False,
1225 toBool( b_rtsp_tcp ),
1226 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
1227 if( !wait_Live555_response( p_demux ) )
1229 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
1230 tk->sub->mediumName(), tk->sub->codecName(),
1231 p_sys->env->getResultMsg() );
1235 p_sys->rtsp->sendPlayCommand( *tk->sub, default_live555_callback, -1, -1, p_sys->ms->scale() );
1236 if( !wait_Live555_response(p_demux) )
1238 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1239 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1242 tk->b_selected = true;
1244 if( !tk->b_selected )
1245 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1249 if( tk->b_asf || tk->b_muxed )
1256 else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
1262 if( p_sys->i_pcr > 0 )
1265 es_out_Control( p_demux->out, ES_OUT_SET_PCR, 1 + p_sys->i_pcr );
1268 /* First warn we want to read data */
1269 p_sys->event_data = 0;
1270 for( i = 0; i < p_sys->i_track; i++ )
1272 live_track_t *tk = p_sys->track[i];
1274 if( tk->waiting == 0 )
1277 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1278 StreamRead, tk, StreamClose, tk );
1281 /* Create a task that will be called if we wait more than 300ms */
1282 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1285 p_sys->scheduler->doEventLoop( &p_sys->event_data );
1287 /* remove the task */
1288 p_sys->scheduler->unscheduleDelayedTask( task );
1290 /* Check for gap in pts value */
1291 for( i = 0; i < p_sys->i_track; i++ )
1293 live_track_t *tk = p_sys->track[i];
1295 if( !tk->b_muxed && !tk->b_rtcp_sync &&
1296 tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1298 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1300 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1301 tk->b_rtcp_sync = true;
1303 tk->i_pts = VLC_TS_INVALID;
1311 if( p_sys->b_multicast && p_sys->b_no_data &&
1312 ( p_sys->i_no_data_ti > 120 ) )
1314 /* FIXME Make this configurable
1315 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1319 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1320 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1322 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1323 var_GetBool( p_demux, "rtsp-http" );
1325 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1327 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1328 if( RollOverTcp( p_demux ) )
1330 msg_Err( p_demux, "TCP rollover failed, aborting" );
1335 msg_Err( p_demux, "no data received in 10s, aborting" );
1338 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1339 ( p_sys->i_no_data_ti > 34 ) )
1342 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1345 return p_sys->b_error ? 0 : 1;
1348 /*****************************************************************************
1350 *****************************************************************************/
1351 static int Control( demux_t *p_demux, int i_query, va_list args )
1353 demux_sys_t *p_sys = p_demux->p_sys;
1361 case DEMUX_GET_TIME:
1362 pi64 = (int64_t*)va_arg( args, int64_t * );
1363 if( p_sys->f_npt > 0 )
1365 *pi64 = (int64_t)(p_sys->f_npt * 1000000.);
1368 return VLC_EGENERIC;
1370 case DEMUX_GET_LENGTH:
1371 pi64 = (int64_t*)va_arg( args, int64_t * );
1372 if( p_sys->f_npt_length > 0 )
1374 double d_length = p_sys->f_npt_length * 1000000.0;
1375 if( d_length >= INT64_MAX )
1378 *pi64 = (int64_t)d_length;
1381 return VLC_EGENERIC;
1383 case DEMUX_GET_POSITION:
1384 pf = (double*)va_arg( args, double* );
1385 if( (p_sys->f_npt_length > 0) && (p_sys->f_npt > 0) )
1387 *pf = p_sys->f_npt / p_sys->f_npt_length;
1390 return VLC_EGENERIC;
1392 case DEMUX_SET_POSITION:
1393 case DEMUX_SET_TIME:
1394 if( p_sys->rtsp && (p_sys->f_npt_length > 0) )
1399 if( (i_query == DEMUX_SET_TIME) && (p_sys->f_npt > 0) )
1401 i64 = (int64_t)va_arg( args, int64_t );
1402 time = (float)(i64 / 1000000.0); /* in second */
1404 else if( i_query == DEMUX_SET_TIME )
1405 return VLC_EGENERIC;
1408 f = (double)va_arg( args, double );
1409 time = f * p_sys->f_npt_length; /* in second */
1412 if( p_sys->b_paused )
1414 p_sys->f_seek_request = time;
1418 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1420 if( !wait_Live555_response( p_demux ) )
1422 msg_Err( p_demux, "PAUSE before seek failed %s",
1423 p_sys->env->getResultMsg() );
1424 return VLC_EGENERIC;
1427 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1429 if( !wait_Live555_response( p_demux ) )
1431 msg_Err( p_demux, "seek PLAY failed %s",
1432 p_sys->env->getResultMsg() );
1433 return VLC_EGENERIC;
1437 for( i = 0; i < p_sys->i_track; i++ )
1439 p_sys->track[i]->b_rtcp_sync = false;
1440 p_sys->track[i]->i_pts = VLC_TS_INVALID;
1443 /* Retrieve the starttime if possible */
1444 p_sys->f_npt = p_sys->f_npt_start = p_sys->ms->playStartTime();
1446 /* Retrieve the duration if possible */
1447 if( p_sys->ms->playEndTime() > 0 )
1448 p_sys->f_npt_length = p_sys->ms->playEndTime();
1450 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1453 return VLC_EGENERIC;
1455 /* Special for access_demux */
1456 case DEMUX_CAN_PAUSE:
1457 case DEMUX_CAN_SEEK:
1458 pb = (bool*)va_arg( args, bool * );
1459 if( p_sys->rtsp && p_sys->f_npt_length > 0 )
1460 /* Not always true, but will be handled in SET_PAUSE_STATE */
1466 case DEMUX_CAN_CONTROL_PACE:
1467 pb = (bool*)va_arg( args, bool * );
1469 #if 1 /* Disable for now until we have a clock synchro algo
1470 * which works with something else than MPEG over UDP */
1477 case DEMUX_CAN_CONTROL_RATE:
1478 pb = (bool*)va_arg( args, bool * );
1479 pb2 = (bool*)va_arg( args, bool * );
1481 *pb = (p_sys->rtsp != NULL) &&
1482 (p_sys->f_npt_length > 0) &&
1483 ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1484 !var_GetBool( p_demux, "rtsp-wmserver" ) );
1488 case DEMUX_SET_RATE:
1490 double f_scale, f_old_scale;
1492 if( !p_sys->rtsp || (p_sys->f_npt_length <= 0) ||
1493 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1494 var_GetBool( p_demux, "rtsp-wmserver" ) )
1495 return VLC_EGENERIC;
1497 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1500 * "[...] should try to approximate the viewing rate, but
1501 * may restrict the range of scale values that it supports.
1502 * The response MUST contain the actual scale value chosen
1505 * Scale = 1 indicates normal play
1506 * Scale > 1 indicates fast forward
1507 * Scale < 1 && Scale > 0 indicates slow motion
1508 * Scale < 0 value indicates rewind
1511 pi_int = (int*)va_arg( args, int * );
1512 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1513 f_old_scale = p_sys->ms->scale();
1515 /* Passing -1 for the start and end time will mean liveMedia won't
1516 * create a Range: section for the RTSP message. The server should
1517 * pick up from the current position */
1518 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1520 if( !wait_Live555_response( p_demux ) )
1522 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1523 p_sys->env->getResultMsg() );
1524 return VLC_EGENERIC;
1527 if( p_sys->ms->scale() == f_old_scale )
1529 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1530 p_sys->ms->scale() );
1531 return VLC_EGENERIC;
1534 /* ReSync the stream */
1535 p_sys->f_npt_start = 0;
1539 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1540 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1544 case DEMUX_SET_PAUSE_STATE:
1546 bool b_pause = (bool)va_arg( args, int );
1547 if( p_sys->rtsp == NULL )
1548 return VLC_EGENERIC;
1550 if( b_pause == p_sys->b_paused )
1553 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1555 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1556 -1.0f, p_sys->ms->scale() );
1558 if( !wait_Live555_response( p_demux ) )
1560 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1561 return VLC_EGENERIC;
1563 p_sys->f_seek_request = -1;
1564 p_sys->b_paused = b_pause;
1566 /* When we Pause, we'll need the TimeoutPrevention thread to
1567 * handle sending the "Keep Alive" message to the server.
1568 * Unfortunately Live555 isn't thread safe and so can't
1569 * do this normally while the main Demux thread is handling
1570 * a live stream. We end up with the Timeout thread blocking
1571 * waiting for a response from the server. So when we PAUSE
1572 * we set a flag that the TimeoutPrevention function will check
1573 * and if it's set, it will trigger the GET_PARAMETER message */
1574 if( p_sys->b_paused && p_sys->p_timeout != NULL )
1575 p_sys->p_timeout->b_handle_keep_alive = true;
1576 else if( !p_sys->b_paused && p_sys->p_timeout != NULL )
1577 p_sys->p_timeout->b_handle_keep_alive = false;
1579 if( !p_sys->b_paused )
1581 for( int i = 0; i < p_sys->i_track; i++ )
1583 live_track_t *tk = p_sys->track[i];
1584 tk->b_rtcp_sync = false;
1585 tk->i_pts = VLC_TS_INVALID;
1587 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1591 /* Reset data received counter */
1592 p_sys->i_no_data_ti = 0;
1594 /* Retrieve the starttime if possible */
1595 p_sys->f_npt_start = p_sys->ms->playStartTime();
1597 /* Retrieve the duration if possible */
1598 if( p_sys->ms->playEndTime() )
1599 p_sys->f_npt_length = p_sys->ms->playEndTime();
1601 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1604 case DEMUX_GET_TITLE_INFO:
1605 case DEMUX_SET_TITLE:
1606 case DEMUX_SET_SEEKPOINT:
1607 return VLC_EGENERIC;
1609 case DEMUX_GET_PTS_DELAY:
1610 pi64 = (int64_t*)va_arg( args, int64_t * );
1611 *pi64 = INT64_C(1000)
1612 * var_InheritInteger( p_demux, "network-caching" );
1616 return VLC_EGENERIC;
1620 /*****************************************************************************
1621 * RollOverTcp: reopen the rtsp into TCP mode
1622 * XXX: ugly, a lot of code are duplicated from Open()
1623 * This should REALLY be fixed
1624 *****************************************************************************/
1625 static int RollOverTcp( demux_t *p_demux )
1627 demux_sys_t *p_sys = p_demux->p_sys;
1630 var_SetBool( p_demux, "rtsp-tcp", true );
1632 /* We close the old RTSP session */
1633 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1634 Medium::close( p_sys->ms );
1635 RTSPClient::close( p_sys->rtsp );
1637 for( i = 0; i < p_sys->i_track; i++ )
1639 live_track_t *tk = p_sys->track[i];
1641 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
1642 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1643 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1644 es_format_Clean( &tk->fmt );
1645 free( tk->p_buffer );
1648 TAB_CLEAN( p_sys->i_track, p_sys->track );
1649 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
1653 p_sys->b_no_data = true;
1654 p_sys->i_no_data_ti = 0;
1655 p_sys->p_out_asf = NULL;
1657 /* Reopen rtsp client */
1658 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1660 msg_Err( p_demux, "Failed to connect with rtsp://%s",
1665 if( p_sys->p_sdp == NULL )
1667 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1671 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1673 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1677 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1683 return VLC_EGENERIC;
1687 /*****************************************************************************
1689 *****************************************************************************/
1690 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1692 const uint8_t *p_data, unsigned i_size )
1694 const unsigned i_packet_size = p_demux->p_sys->asfh.i_min_data_packet_size;
1695 block_t *p_list = NULL;
1697 while( i_size >= 4 )
1699 unsigned i_flags = p_data[0];
1700 unsigned i_length_offset = (p_data[1] << 16) |
1703 bool b_length = i_flags & 0x40;
1704 bool b_relative_ts = i_flags & 0x20;
1705 bool b_duration = i_flags & 0x10;
1706 bool b_location_id = i_flags & 0x08;
1708 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1709 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1710 unsigned i_header_size = 4;
1718 if( i_header_size > i_size )
1720 msg_Warn( p_demux, "Invalid header size" );
1725 * When b_length is true, the streams I found do not seems to respect
1726 * the documentation.
1727 * From them, I have failed to find which choice between '__MIN()' or
1728 * 'i_length_offset - i_header_size' is the right one.
1732 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1734 i_payload = i_size - i_header_size;
1736 if( !tk->p_asf_block )
1738 tk->p_asf_block = block_Alloc( i_packet_size );
1739 if( !tk->p_asf_block )
1741 tk->p_asf_block->i_buffer = 0;
1743 unsigned i_offset = b_length ? 0 : i_length_offset;
1744 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1746 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1747 tk->p_asf_block->i_buffer += i_payload;
1750 /* We have a complete packet */
1751 tk->p_asf_block->i_buffer = i_packet_size;
1752 block_ChainAppend( &p_list, tk->p_asf_block );
1753 tk->p_asf_block = NULL;
1758 /* Reset on broken stream */
1759 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1760 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1761 tk->p_asf_block->i_buffer = 0;
1765 p_data += i_header_size + i_payload;
1766 i_size -= i_header_size + i_payload;
1771 /*****************************************************************************
1773 *****************************************************************************/
1774 static void StreamRead( void *p_private, unsigned int i_size,
1775 unsigned int i_truncated_bytes, struct timeval pts,
1776 unsigned int duration )
1778 VLC_UNUSED( duration );
1780 live_track_t *tk = (live_track_t*)p_private;
1781 demux_t *p_demux = tk->p_demux;
1782 demux_sys_t *p_sys = p_demux->p_sys;
1785 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1787 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1788 (int64_t)pts.tv_usec;
1790 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1791 i_pts &= INT64_C(0x00ffffffffffffff);
1793 /* Retrieve NPT for this pts */
1794 tk->f_npt = tk->sub->getNormalPlayTime(pts);
1796 if( tk->b_quicktime && tk->p_es == NULL )
1798 QuickTimeGenericRTPSource *qtRTPSource =
1799 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1800 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1801 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1803 /* Get codec informations from the quicktime atoms :
1804 * http://developer.apple.com/quicktime/icefloe/dispatch026.html */
1805 if( tk->fmt.i_cat == VIDEO_ES ) {
1806 if( qtState.sdAtomSize < 16 + 32 )
1809 p_sys->event_data = 0xff;
1813 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1814 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1815 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1817 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1819 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1820 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1821 + qtRTPSource->qtState.sdAtomSize;
1822 while (pos+8 < endpos) {
1823 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1824 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1825 if( memcmp(pos+4, "avcC", 4) == 0 &&
1827 atomLength <= INT_MAX )
1829 tk->fmt.i_extra = atomLength-8;
1830 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1831 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1839 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1840 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1841 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1845 if( qtState.sdAtomSize < 24 )
1848 p_sys->event_data = 0xff;
1852 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1853 tk->fmt.audio.i_bitspersample = (sdAtom[22] << 8) | sdAtom[23];
1855 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1859 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1861 pts.tv_sec * 1000000LL + pts.tv_usec );
1864 /* grow buffer if it looks like buffer is too small, but don't eat
1865 * up all the memory on strange streams */
1866 if( i_truncated_bytes > 0 )
1868 if( tk->i_buffer < 2000000 )
1871 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1872 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1873 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1876 msg_Warn( p_demux, "realloc failed" );
1880 tk->p_buffer = (uint8_t*)p_tmp;
1885 if( tk->b_discard_trunc )
1887 p_sys->event_data = 0xff;
1893 assert( i_size <= tk->i_buffer );
1895 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1896 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1898 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1900 p_block = block_Alloc( i_size + 1 );
1901 p_block->p_buffer[0] = amrSource->lastFrameHeader();
1902 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1904 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1906 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1907 uint32_t header = h261Source->lastSpecialHeader();
1908 p_block = block_Alloc( i_size + 4 );
1909 memcpy( p_block->p_buffer, &header, 4 );
1910 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1912 if( tk->sub->rtpSource()->curPacketMarkerBit() )
1913 p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1915 else if( tk->fmt.i_codec == VLC_CODEC_H264 )
1917 if( (tk->p_buffer[0] & 0x1f) >= 24 )
1918 msg_Warn( p_demux, "unsupported NAL type for H264" );
1920 /* Normal NAL type */
1921 p_block = block_Alloc( i_size + 4 );
1922 p_block->p_buffer[0] = 0x00;
1923 p_block->p_buffer[1] = 0x00;
1924 p_block->p_buffer[2] = 0x00;
1925 p_block->p_buffer[3] = 0x01;
1926 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1928 else if( tk->b_asf )
1930 p_block = StreamParseAsf( p_demux, tk,
1931 tk->sub->rtpSource()->curPacketMarkerBit(),
1932 tk->p_buffer, i_size );
1936 p_block = block_Alloc( i_size );
1937 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1940 if( p_sys->i_pcr < i_pts )
1942 p_sys->i_pcr = i_pts;
1945 /* Update our global npt value */
1946 if( tk->f_npt > 0 &&
1947 ( tk->f_npt < p_sys->f_npt_length || p_sys->f_npt_length <= 0 ) )
1948 p_sys->f_npt = tk->f_npt;
1952 if( !tk->b_muxed && !tk->b_asf )
1954 if( i_pts != tk->i_pts )
1955 p_block->i_pts = VLC_TS_0 + i_pts;
1956 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
1957 p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? VLC_TS_INVALID : (VLC_TS_0 + i_pts);
1961 stream_DemuxSend( tk->p_out_muxed, p_block );
1962 else if( tk->b_asf )
1963 stream_DemuxSend( p_sys->p_out_asf, p_block );
1965 es_out_Send( p_demux->out, tk->p_es, p_block );
1968 /* warn that's ok */
1969 p_sys->event_data = 0xff;
1971 /* we have read data */
1973 p_demux->p_sys->b_no_data = false;
1974 p_demux->p_sys->i_no_data_ti = 0;
1976 if( i_pts > 0 && !tk->b_muxed )
1982 /*****************************************************************************
1984 *****************************************************************************/
1985 static void StreamClose( void *p_private )
1987 live_track_t *tk = (live_track_t*)p_private;
1988 demux_t *p_demux = tk->p_demux;
1989 demux_sys_t *p_sys = p_demux->p_sys;
1990 tk->b_selected = false;
1991 p_sys->event_rtsp = 0xff;
1992 p_sys->event_data = 0xff;
1995 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1998 for( int i = 0; i < p_sys->i_track; i++ )
2000 if( p_sys->track[i]->b_selected )
2003 msg_Dbg( p_demux, "RTSP track Close, %d track remaining", nb_tracks );
2005 p_sys->b_error = true;
2009 /*****************************************************************************
2011 *****************************************************************************/
2012 static void TaskInterruptRTSP( void *p_private )
2014 demux_t *p_demux = (demux_t*)p_private;
2017 p_demux->p_sys->event_rtsp = 0xff;
2020 static void TaskInterruptData( void *p_private )
2022 demux_t *p_demux = (demux_t*)p_private;
2024 p_demux->p_sys->i_no_data_ti++;
2027 p_demux->p_sys->event_data = 0xff;
2030 /*****************************************************************************
2032 *****************************************************************************/
2034 static void* TimeoutPrevention( void *p_data )
2036 timeout_thread_t *p_timeout = (timeout_thread_t *)p_data;
2040 /* Voodoo (= no) thread safety here! *Ahem* */
2041 if( p_timeout->b_handle_keep_alive )
2043 char *psz_bye = NULL;
2044 int canc = vlc_savecancel ();
2046 p_timeout->p_sys->rtsp->sendGetParameterCommand( *p_timeout->p_sys->ms, NULL, psz_bye );
2047 vlc_restorecancel (canc);
2049 p_timeout->p_sys->b_timeout_call = !p_timeout->b_handle_keep_alive;
2051 msleep (((int64_t)p_timeout->p_sys->i_timeout - 2) * CLOCK_FREQ);
2053 assert(0); /* dead code */
2056 /*****************************************************************************
2058 *****************************************************************************/
2059 static int ParseASF( demux_t *p_demux )
2061 demux_sys_t *p_sys = p_demux->p_sys;
2063 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
2064 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2068 /* Parse the asf header */
2069 if( psz_asf == NULL )
2070 return VLC_EGENERIC;
2072 psz_asf += strlen( psz_marker );
2073 psz_asf = strdup( psz_asf ); /* Duplicate it */
2074 psz_end = strchr( psz_asf, '\n' );
2076 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2079 if( psz_asf >= psz_end )
2082 return VLC_EGENERIC;
2085 /* Always smaller */
2086 p_header = block_Alloc( psz_end - psz_asf );
2087 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2088 p_header->i_buffer, psz_asf );
2089 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2090 if( p_header->i_buffer <= 0 )
2093 return VLC_EGENERIC;
2096 /* Parse it to get packet size */
2097 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2099 /* Send it to demuxer */
2100 stream_DemuxSend( p_sys->p_out_asf, p_header );
2107 static unsigned char* parseH264ConfigStr( char const* configStr,
2108 unsigned int& configSize )
2111 size_t i_records = 1;
2115 if( configStr == NULL || *configStr == '\0' )
2118 psz = dup = strdup( configStr );
2120 /* Count the number of commas */
2121 for( psz = dup; *psz != '\0'; ++psz )
2130 size_t configMax = 5*strlen(dup);
2131 unsigned char *cfg = new unsigned char[configMax];
2133 for( size_t i = 0; i < i_records; ++i )
2135 cfg[configSize++] = 0x00;
2136 cfg[configSize++] = 0x00;
2137 cfg[configSize++] = 0x00;
2138 cfg[configSize++] = 0x01;
2140 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2141 configMax-configSize, psz );
2142 psz += strlen(psz)+1;
2149 static uint8_t *parseVorbisConfigStr( char const* configStr,
2150 unsigned int& configSize )
2153 if( configStr == NULL || *configStr == '\0' )
2155 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1332115200 // 2012.03.20
2156 unsigned char *p_cfg = base64Decode( configStr, configSize );
2158 char* configStr_dup = strdup( configStr );
2159 unsigned char *p_cfg = base64Decode( configStr_dup, configSize );
2160 free( configStr_dup );
2162 uint8_t *p_extra = NULL;
2163 /* skip header count, ident number and length (cf. RFC 5215) */
2164 const unsigned int headerSkip = 9;
2165 if( configSize > headerSkip && ((uint8_t*)p_cfg)[3] == 1 )
2167 configSize -= headerSkip;
2168 p_extra = (uint8_t*)xmalloc( configSize );
2169 memcpy( p_extra, p_cfg+headerSkip, configSize );