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>
66 #include "../access/mms/asf.h" /* Who said ugly ? */
71 /*****************************************************************************
73 *****************************************************************************/
74 static int Open ( vlc_object_t * );
75 static void Close( vlc_object_t * );
77 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
78 #define KASENNA_LONGTEXT N_( "Kasenna servers use an old and nonstandard " \
79 "dialect of RTSP. With this parameter VLC will try this dialect, but "\
80 "then it cannot connect to normal RTSP servers." )
82 #define WMSERVER_TEXT N_("WMServer RTSP dialect")
83 #define WMSERVER_LONGTEXT N_("WMServer uses a nonstandard dialect " \
84 "of RTSP. Selecting this parameter will tell VLC to assume some " \
85 "options contrary to RFC 2326 guidelines.")
87 #define USER_TEXT N_("RTSP user name")
88 #define USER_LONGTEXT N_("Sets the username for the connection, " \
89 "if no username or password are set in the url.")
90 #define PASS_TEXT N_("RTSP password")
91 #define PASS_LONGTEXT N_("Sets the password for the connection, " \
92 "if no username or password are set in the url.")
93 #define FRAME_BUFFER_SIZE_TEXT N_("RTSP frame buffer size")
94 #define FRAME_BUFFER_SIZE_LONGTEXT N_("RTSP start frame buffer size of the video " \
95 "track, can be increased in case of broken pictures due " \
96 "to too small buffer.")
97 #define DEFAULT_FRAME_BUFFER_SIZE 100000
100 set_description( N_("RTP/RTSP/SDP demuxer (using Live555)" ) )
101 set_capability( "demux", 50 )
102 set_shortname( "RTP/RTSP")
103 set_callbacks( Open, Close )
104 add_shortcut( "live", "livedotcom" )
105 set_category( CAT_INPUT )
106 set_subcategory( SUBCAT_INPUT_DEMUX )
109 set_description( N_("RTSP/RTP access and demux") )
110 add_shortcut( "rtsp", "pnm", "live", "livedotcom" )
111 set_capability( "access_demux", 0 )
112 set_callbacks( Open, Close )
113 add_bool( "rtsp-tcp", false,
114 N_("Use RTP over RTSP (TCP)"),
115 N_("Use RTP over RTSP (TCP)"), true )
117 add_integer( "rtp-client-port", -1,
119 N_("Port to use for the RTP source of the session"), true )
120 add_bool( "rtsp-mcast", false,
121 N_("Force multicast RTP via RTSP"),
122 N_("Force multicast RTP via RTSP"), true )
124 add_bool( "rtsp-http", false,
125 N_("Tunnel RTSP and RTP over HTTP"),
126 N_("Tunnel RTSP and RTP over HTTP"), true )
128 add_integer( "rtsp-http-port", 80,
129 N_("HTTP tunnel port"),
130 N_("Port to use for tunneling the RTSP/RTP over HTTP."),
132 add_bool( "rtsp-kasenna", false, KASENNA_TEXT,
133 KASENNA_LONGTEXT, true )
135 add_bool( "rtsp-wmserver", false, WMSERVER_TEXT,
136 WMSERVER_LONGTEXT, true)
138 add_string( "rtsp-user", NULL, USER_TEXT,
139 USER_LONGTEXT, true )
141 add_password( "rtsp-pwd", NULL, PASS_TEXT,
142 PASS_LONGTEXT, true )
143 add_integer( "rtsp-frame-buffer-size", DEFAULT_FRAME_BUFFER_SIZE,
144 FRAME_BUFFER_SIZE_TEXT, FRAME_BUFFER_SIZE_LONGTEXT,
149 /*****************************************************************************
151 *****************************************************************************/
156 MediaSubsession *sub;
164 block_t *p_asf_block;
165 bool b_discard_trunc;
166 stream_t *p_out_muxed; /* for muxed stream */
169 unsigned int i_buffer;
180 struct timeout_thread_t
184 bool b_handle_keep_alive;
191 char *p_sdp; /* XXX mallocated */
192 char *psz_path; /* URL-encoded path */
196 TaskScheduler *scheduler;
197 UsageEnvironment *env ;
202 live_track_t **track;
210 int64_t i_pcr; /* The clock */
215 /* timeout thread information */
216 int i_timeout; /* session timeout value in seconds */
217 bool b_timeout_call;/* mark to send an RTSP call to prevent server timeout */
218 timeout_thread_t *p_timeout; /* the actual thread that makes sure we don't timeout */
222 bool b_multicast; /* if one of the tracks is multicasted */
223 bool b_no_data; /* if we never received any data */
224 int i_no_data_ti; /* consecutive number of TaskInterrupt */
229 bool b_get_param; /* Does the server support GET_PARAMETER */
230 bool b_paused; /* Are we paused? */
232 int i_live555_ret; /* live555 callback return code */
234 float f_seek_request;/* In case we receive a seek request while paused*/
238 class RTSPClientVlc : public RTSPClient
241 RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
242 char const* applicationName, portNumBits tunnelOverHTTPPortNum,
243 demux_sys_t *p_sys) :
244 RTSPClient( env, rtspURL, verbosityLevel, applicationName,
245 tunnelOverHTTPPortNum )
252 static int Demux ( demux_t * );
253 static int Control( demux_t *, int, va_list );
255 static int Connect ( demux_t * );
256 static int SessionsSetup( demux_t * );
257 static int Play ( demux_t *);
258 static int ParseASF ( demux_t * );
259 static int RollOverTcp ( demux_t * );
261 static void StreamRead ( void *, unsigned int, unsigned int,
262 struct timeval, unsigned int );
263 static void StreamClose ( void * );
264 static void TaskInterruptData( void * );
265 static void TaskInterruptRTSP( void * );
267 static void* TimeoutPrevention( void * );
269 static unsigned char* parseH264ConfigStr( char const* configStr,
270 unsigned int& configSize );
272 /*****************************************************************************
274 *****************************************************************************/
275 static int Open ( vlc_object_t *p_this )
277 demux_t *p_demux = (demux_t*)p_this;
278 demux_sys_t *p_sys = NULL;
281 int i_error = VLC_EGENERIC;
285 /* See if it looks like a SDP
286 v, o, s fields are mandatory and in this order */
287 const uint8_t *p_peek;
288 if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
290 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
291 memcmp( p_peek, "v=0\n", 4 ) &&
292 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
298 p_demux->pf_demux = Demux;
299 p_demux->pf_control= Control;
300 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
301 if( !p_sys ) return VLC_ENOMEM;
303 msg_Dbg( p_demux, "version "LIVEMEDIA_LIBRARY_VERSION_STRING );
305 TAB_INIT( p_sys->i_track, p_sys->track );
307 p_sys->f_npt_start = 0.;
308 p_sys->f_npt_length = 0.;
309 p_sys->b_no_data = true;
310 p_sys->psz_path = strdup( p_demux->psz_location );
311 p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
312 p_sys->f_seek_request = -1;
314 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
315 vlc_UrlParse( &p_sys->url, p_sys->psz_path, 0 );
317 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
319 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
322 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
324 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
328 if( strcasecmp( p_demux->psz_access, "sdp" ) )
330 char *p = p_sys->psz_path;
331 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
334 if( p_demux->s != NULL )
336 /* Gather the complete sdp file */
338 int i_sdp_max = 1000;
339 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
343 i_error = VLC_ENOMEM;
349 int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
350 i_sdp_max - i_sdp - 1 );
352 if( !vlc_object_alive (p_demux) )
360 msg_Err( p_demux, "failed to read SDP" );
367 if( i_read < i_sdp_max - i_sdp - 1 )
374 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
376 p_sys->p_sdp = (char*)p_sdp;
378 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
380 msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
384 if( p_sys->p_sdp == NULL )
386 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
387 i_error = VLC_ENOMEM;
391 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
393 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
397 if( p_sys->b_real ) goto error;
399 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
402 if( p_sys->p_out_asf && ParseASF( p_demux ) )
404 msg_Err( p_demux, "cannot find a usable asf header" );
405 /* TODO Clean tracks */
409 if( p_sys->i_track <= 0 )
419 /*****************************************************************************
421 *****************************************************************************/
422 static void Close( vlc_object_t *p_this )
424 demux_t *p_demux = (demux_t*)p_this;
425 demux_sys_t *p_sys = p_demux->p_sys;
427 if( p_sys->p_timeout )
429 vlc_cancel( p_sys->p_timeout->handle );
430 vlc_join( p_sys->p_timeout->handle, NULL );
431 free( p_sys->p_timeout );
434 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
435 if( p_sys->ms ) Medium::close( p_sys->ms );
436 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
437 if( p_sys->env ) p_sys->env->reclaim();
439 for( int i = 0; i < p_sys->i_track; i++ )
441 live_track_t *tk = p_sys->track[i];
443 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
444 es_format_Clean( &tk->fmt );
445 free( tk->p_buffer );
448 TAB_CLEAN( p_sys->i_track, p_sys->track );
449 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
450 delete p_sys->scheduler;
451 free( p_sys->p_sdp );
452 free( p_sys->psz_path );
454 vlc_UrlClean( &p_sys->url );
459 static inline const char *strempty( const char *s ) { return s?s:""; }
460 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
462 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
464 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
465 demux_sys_t *p_sys = client_vlc->p_sys;
466 delete []result_string;
467 p_sys->i_live555_ret = result_code;
468 p_sys->b_error = p_sys->i_live555_ret != 0;
469 p_sys->event_rtsp = 1;
472 /* return true if the RTSP command succeeded */
473 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
476 demux_sys_t * p_sys = p_demux->p_sys;
477 p_sys->event_rtsp = 0;
480 /* Create a task that will be called if we wait more than timeout ms */
481 task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000,
485 p_sys->event_rtsp = 0;
486 p_sys->b_error = true;
487 p_sys->i_live555_ret = 0;
488 p_sys->scheduler->doEventLoop( &p_sys->event_rtsp );
489 //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
492 /* remove the task */
493 p_sys->scheduler->unscheduleDelayedTask( task );
495 return !p_sys->b_error;
498 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
499 char* result_string )
501 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
502 demux_sys_t *p_sys = client_vlc->p_sys;
503 p_sys->i_live555_ret = result_code;
504 if ( result_code == 0 )
506 char* sdpDescription = result_string;
507 free( p_sys->p_sdp );
511 p_sys->p_sdp = strdup( sdpDescription );
512 p_sys->b_error = false;
516 p_sys->b_error = true;
517 delete[] result_string;
518 p_sys->event_rtsp = 1;
521 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
522 char* result_string )
524 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
525 demux_sys_t *p_sys = client_vlc->p_sys;
527 // If OPTIONS fails, assume GET_PARAMETER is not supported but
528 // still continue on with the stream. Some servers (foscam)
529 // return 501/not implemented for OPTIONS.
531 && result_string != NULL
532 && strstr( result_string, "GET_PARAMETER" ) != NULL;
533 client->sendDescribeCommand( continueAfterDESCRIBE );
534 delete[] result_string;
537 /*****************************************************************************
538 * Connect: connects to the RTSP server to setup the session DESCRIBE
539 *****************************************************************************/
540 static int Connect( demux_t *p_demux )
542 demux_sys_t *p_sys = p_demux->p_sys;
543 Authenticator authenticator;
544 char *psz_user = NULL;
545 char *psz_pwd = NULL;
546 char *psz_url = NULL;
548 int i_ret = VLC_SUCCESS;
549 const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
551 /* Get the user name and password */
552 if( p_sys->url.psz_username || p_sys->url.psz_password )
554 /* Create the URL by stripping away the username/password part */
555 if( p_sys->url.i_port == 0 )
556 p_sys->url.i_port = 554;
557 if( asprintf( &psz_url, "rtsp://%s:%d%s",
558 strempty( p_sys->url.psz_host ),
560 strempty( p_sys->url.psz_path ) ) == -1 )
563 psz_user = strdup( strempty( p_sys->url.psz_username ) );
564 psz_pwd = strdup( strempty( p_sys->url.psz_password ) );
568 if( asprintf( &psz_url, "rtsp://%s", p_sys->psz_path ) == -1 )
571 psz_user = var_InheritString( p_demux, "rtsp-user" );
572 psz_pwd = var_InheritString( p_demux, "rtsp-pwd" );
576 if( !vlc_object_alive (p_demux) )
578 i_ret = VLC_EGENERIC;
582 if( var_CreateGetBool( p_demux, "rtsp-http" ) )
583 i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
585 p_sys->rtsp = new RTSPClientVlc( *p_sys->env, psz_url,
586 var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
587 "LibVLC/"VERSION, i_http_port, p_sys );
590 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
591 p_sys->env->getResultMsg() );
592 i_ret = VLC_EGENERIC;
596 /* Kasenna enables KeepAlive by analysing the User-Agent string.
597 * Appending _KA to the string should be enough to enable this feature,
598 * however, there is a bug where the _KA doesn't get parsed from the
599 * default User-Agent as created by VLC/Live555 code. This is probably due
600 * to spaces in the string or the string being too long. Here we override
601 * the default string with a more compact version.
603 if( var_InheritBool( p_demux, "rtsp-kasenna" ))
605 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
609 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
611 p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
613 if( !wait_Live555_response( p_demux, i_timeout ) )
615 int i_code = p_sys->i_live555_ret;
618 msg_Dbg( p_demux, "authentication failed" );
622 dialog_Login( p_demux, &psz_user, &psz_pwd,
623 _("RTSP authentication"), "%s",
624 _("Please enter a valid login name and a password.") );
625 if( psz_user != NULL && psz_pwd != NULL )
627 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
631 else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
633 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
634 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
635 var_SetBool( p_demux, "rtsp-http", true );
636 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
643 msg_Dbg( p_demux, "connection timeout" );
646 msg_Dbg( p_demux, "connection error %d", i_code );
648 dialog_Fatal( p_demux, _("RTSP connection failed"),
649 _("Access to the stream is denied by the server configuration.") );
651 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
654 i_ret = VLC_EGENERIC;
658 /* malloc-ated copy */
666 /*****************************************************************************
667 * SessionsSetup: prepares the subsessions and does the SETUP
668 *****************************************************************************/
669 static int SessionsSetup( demux_t *p_demux )
671 demux_sys_t *p_sys = p_demux->p_sys;
672 MediaSubsessionIterator *iter = NULL;
673 MediaSubsession *sub = NULL;
677 int i_return = VLC_SUCCESS;
678 unsigned int i_receive_buffer = 0;
679 int i_frame_buffer = DEFAULT_FRAME_BUFFER_SIZE;
680 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
682 b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
683 var_GetBool( p_demux, "rtsp-http" );
684 i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
687 /* Create the session from the SDP */
688 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
690 msg_Err( p_demux, "Could not create the RTSP Session: %s",
691 p_sys->env->getResultMsg() );
695 /* Initialise each media subsession */
696 iter = new MediaSubsessionIterator( *p_sys->ms );
697 while( ( sub = iter->next() ) != NULL )
702 if( !vlc_object_alive (p_demux) )
708 /* Value taken from mplayer */
709 if( !strcmp( sub->mediumName(), "audio" ) )
710 i_receive_buffer = 100000;
711 else if( !strcmp( sub->mediumName(), "video" ) )
713 int i_var_buf_size = var_InheritInteger( p_demux, "rtsp-frame-buffer-size" );
714 if( i_var_buf_size > 0 )
715 i_frame_buffer = i_var_buf_size;
716 i_receive_buffer = 2000000;
718 else if( !strcmp( sub->mediumName(), "text" ) )
722 if( i_client_port != -1 )
724 sub->setClientPortNum( i_client_port );
728 if( strcasestr( sub->codecName(), "REAL" ) )
730 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
731 p_sys->b_real = true; /* This is a problem, we'll handle it later */
735 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
736 bInit = sub->initiate( 0 );
738 bInit = sub->initiate();
742 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
743 sub->mediumName(), sub->codecName(),
744 p_sys->env->getResultMsg() );
748 if( sub->rtpSource() != NULL )
750 int fd = sub->rtpSource()->RTPgs()->socketNum();
752 /* Increase the buffer size */
753 if( i_receive_buffer > 0 )
754 increaseReceiveBufferTo( *p_sys->env, fd, i_receive_buffer );
756 /* Increase the RTP reorder timebuffer just a bit */
757 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
759 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
762 /* Issue the SETUP */
765 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
766 toBool( b_rtsp_tcp ),
767 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
768 if( !wait_Live555_response( p_demux ) )
770 /* if we get an unsupported transport error, toggle TCP
771 * use and try again */
772 if( p_sys->i_live555_ret == 461 )
773 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
774 !toBool( b_rtsp_tcp ), False );
775 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
777 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
778 sub->mediumName(), sub->codecName(),
779 p_sys->env->getResultMsg() );
784 var_SetBool( p_demux, "rtsp-tcp", true );
790 /* Check if we will receive data from this subsession for
792 if( sub->readSource() == NULL ) continue;
793 if( !p_sys->b_multicast )
795 /* We need different rollover behaviour for multicast */
796 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
799 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
805 tk->p_demux = p_demux;
808 tk->b_quicktime = false;
810 tk->p_asf_block = NULL;
812 tk->b_discard_trunc = false;
813 tk->p_out_muxed = NULL;
815 tk->b_rtcp_sync = false;
816 tk->i_pts = VLC_TS_INVALID;
818 tk->b_selected = true;
819 tk->i_buffer = i_frame_buffer;
820 tk->p_buffer = (uint8_t *)malloc( i_frame_buffer );
829 /* Value taken from mplayer */
830 if( !strcmp( sub->mediumName(), "audio" ) )
832 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
833 tk->fmt.audio.i_channels = sub->numChannels();
834 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
836 if( !strcmp( sub->codecName(), "MPA" ) ||
837 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
838 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
840 tk->fmt.i_codec = VLC_CODEC_MPGA;
841 tk->fmt.audio.i_rate = 0;
843 else if( !strcmp( sub->codecName(), "AC3" ) )
845 tk->fmt.i_codec = VLC_CODEC_A52;
846 tk->fmt.audio.i_rate = 0;
848 else if( !strcmp( sub->codecName(), "L16" ) )
850 tk->fmt.i_codec = VLC_CODEC_S16B;
851 tk->fmt.audio.i_bitspersample = 16;
853 else if( !strcmp( sub->codecName(), "L20" ) )
855 tk->fmt.i_codec = VLC_CODEC_S20B;
856 tk->fmt.audio.i_bitspersample = 20;
858 else if( !strcmp( sub->codecName(), "L24" ) )
860 tk->fmt.i_codec = VLC_CODEC_S24B;
861 tk->fmt.audio.i_bitspersample = 24;
863 else if( !strcmp( sub->codecName(), "L8" ) )
865 tk->fmt.i_codec = VLC_CODEC_U8;
866 tk->fmt.audio.i_bitspersample = 8;
868 else if( !strcmp( sub->codecName(), "DAT12" ) )
870 tk->fmt.i_codec = VLC_CODEC_DAT12;
871 tk->fmt.audio.i_bitspersample = 12;
873 else if( !strcmp( sub->codecName(), "PCMU" ) )
875 tk->fmt.i_codec = VLC_CODEC_MULAW;
876 tk->fmt.audio.i_bitspersample = 8;
878 else if( !strcmp( sub->codecName(), "PCMA" ) )
880 tk->fmt.i_codec = VLC_CODEC_ALAW;
881 tk->fmt.audio.i_bitspersample = 8;
883 else if( !strncmp( sub->codecName(), "G726", 4 ) )
885 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
886 tk->fmt.audio.i_rate = 8000;
887 tk->fmt.audio.i_channels = 1;
888 if( !strcmp( sub->codecName()+5, "40" ) )
889 tk->fmt.i_bitrate = 40000;
890 else if( !strcmp( sub->codecName()+5, "32" ) )
891 tk->fmt.i_bitrate = 32000;
892 else if( !strcmp( sub->codecName()+5, "24" ) )
893 tk->fmt.i_bitrate = 24000;
894 else if( !strcmp( sub->codecName()+5, "16" ) )
895 tk->fmt.i_bitrate = 16000;
897 else if( !strcmp( sub->codecName(), "AMR" ) )
899 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
901 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
903 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
905 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
907 unsigned int i_extra;
910 tk->fmt.i_codec = VLC_CODEC_MP4A;
912 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
915 tk->fmt.i_extra = i_extra;
916 tk->fmt.p_extra = xmalloc( i_extra );
917 memcpy( tk->fmt.p_extra, p_extra, i_extra );
920 /* Because the "faad" decoder does not handle the LATM
921 * data length field at the start of each returned LATM
922 * frame, tell the RTP source to omit. */
923 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
925 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
927 unsigned int i_extra;
930 tk->fmt.i_codec = VLC_CODEC_MP4A;
932 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
935 tk->fmt.i_extra = i_extra;
936 tk->fmt.p_extra = xmalloc( i_extra );
937 memcpy( tk->fmt.p_extra, p_extra, i_extra );
941 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
944 if( p_sys->p_out_asf == NULL )
945 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
948 else if( !strcmp( sub->codecName(), "X-QT" ) ||
949 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
951 tk->b_quicktime = true;
953 else if( !strcmp( sub->codecName(), "SPEEX" ) )
955 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
956 if ( tk->fmt.audio.i_rate == 0 )
958 msg_Warn( p_demux,"Using 8kHz as default sample rate." );
959 tk->fmt.audio.i_rate = 8000;
963 else if( !strcmp( sub->mediumName(), "video" ) )
965 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
966 if( !strcmp( sub->codecName(), "MPV" ) )
968 tk->fmt.i_codec = VLC_CODEC_MPGV;
969 tk->fmt.b_packetized = false;
971 else if( !strcmp( sub->codecName(), "H263" ) ||
972 !strcmp( sub->codecName(), "H263-1998" ) ||
973 !strcmp( sub->codecName(), "H263-2000" ) )
975 tk->fmt.i_codec = VLC_CODEC_H263;
977 else if( !strcmp( sub->codecName(), "H261" ) )
979 tk->fmt.i_codec = VLC_CODEC_H261;
981 else if( !strcmp( sub->codecName(), "H264" ) )
983 unsigned int i_extra = 0;
984 uint8_t *p_extra = NULL;
986 tk->fmt.i_codec = VLC_CODEC_H264;
987 tk->fmt.b_packetized = false;
989 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
992 tk->fmt.i_extra = i_extra;
993 tk->fmt.p_extra = xmalloc( i_extra );
994 memcpy( tk->fmt.p_extra, p_extra, i_extra );
999 else if( !strcmp( sub->codecName(), "JPEG" ) )
1001 tk->fmt.i_codec = VLC_CODEC_MJPG;
1003 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1005 unsigned int i_extra;
1008 tk->fmt.i_codec = VLC_CODEC_MP4V;
1010 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
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 );
1019 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1020 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1021 !strcmp( sub->codecName(), "X-QDM" ) ||
1022 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1023 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1025 tk->b_quicktime = true;
1027 else if( !strcmp( sub->codecName(), "MP2T" ) )
1030 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
1032 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1033 !strcmp( sub->codecName(), "MP1S" ) )
1036 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
1039 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1042 if( p_sys->p_out_asf == NULL )
1043 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
1046 else if( !strcmp( sub->codecName(), "DV" ) )
1049 tk->b_discard_trunc = true;
1050 tk->p_out_muxed = stream_DemuxNew( p_demux, "rawdv",
1054 else if( !strcmp( sub->mediumName(), "text" ) )
1056 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1058 if( !strcmp( sub->codecName(), "T140" ) )
1060 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1064 if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
1066 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1069 if( sub->rtcpInstance() != NULL )
1071 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1074 if( tk->p_es || tk->b_quicktime || ( tk->b_muxed && tk->p_out_muxed ) ||
1075 ( tk->b_asf && p_sys->p_out_asf ) )
1077 TAB_APPEND_CAST( (live_track_t **), p_sys->i_track, p_sys->track, tk );
1082 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1083 es_format_Clean( &tk->fmt );
1089 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1091 /* Retrieve the starttime if possible */
1092 p_sys->f_npt_start = p_sys->ms->playStartTime();
1094 /* Retrieve the duration if possible */
1095 p_sys->f_npt_length = p_sys->ms->playEndTime();
1098 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1101 p_sys->b_no_data = true;
1102 p_sys->i_no_data_ti = 0;
1107 /*****************************************************************************
1108 * Play: starts the actual playback of the stream
1109 *****************************************************************************/
1110 static int Play( demux_t *p_demux )
1112 demux_sys_t *p_sys = p_demux->p_sys;
1117 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_npt_start, -1, 1 );
1119 if( !wait_Live555_response(p_demux) )
1121 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1122 return VLC_EGENERIC;
1125 /* Retrieve the timeout value and set up a timeout prevention thread */
1126 p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
1127 if( p_sys->i_timeout <= 0 )
1128 p_sys->i_timeout = 60; /* default value from RFC2326 */
1130 /* start timeout-thread only if GET_PARAMETER is supported by the server */
1131 if( !p_sys->p_timeout && p_sys->b_get_param )
1133 msg_Dbg( p_demux, "We have a timeout of %d seconds", p_sys->i_timeout );
1134 p_sys->p_timeout = (timeout_thread_t *)malloc( sizeof(timeout_thread_t) );
1135 if( p_sys->p_timeout )
1137 memset( p_sys->p_timeout, 0, sizeof(timeout_thread_t) );
1138 p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
1139 if( vlc_clone( &p_sys->p_timeout->handle, TimeoutPrevention,
1140 p_sys->p_timeout, VLC_THREAD_PRIORITY_LOW ) )
1142 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1143 free( p_sys->p_timeout );
1144 p_sys->p_timeout = NULL;
1147 msg_Dbg( p_demux, "spawned timeout thread" );
1150 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1155 /* Retrieve the starttime if possible */
1156 p_sys->f_npt_start = p_sys->ms->playStartTime();
1157 if( p_sys->ms->playEndTime() > 0 )
1158 p_sys->f_npt_length = p_sys->ms->playEndTime();
1160 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1165 /*****************************************************************************
1167 *****************************************************************************/
1168 static int Demux( demux_t *p_demux )
1170 demux_sys_t *p_sys = p_demux->p_sys;
1173 bool b_send_pcr = true;
1177 /* Check if we need to send the server a Keep-A-Live signal */
1178 if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
1180 char *psz_bye = NULL;
1181 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms, NULL, psz_bye );
1182 p_sys->b_timeout_call = false;
1185 for( i = 0; i < p_sys->i_track; i++ )
1187 live_track_t *tk = p_sys->track[i];
1192 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1193 if( !b && tk->b_selected )
1195 tk->b_selected = false;
1196 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1198 else if( b && !tk->b_selected)
1200 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1201 var_GetBool( p_demux, "rtsp-http" );
1202 p_sys->rtsp->sendSetupCommand( *tk->sub, default_live555_callback, False,
1203 toBool( b_rtsp_tcp ),
1204 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
1205 if( !wait_Live555_response( p_demux ) )
1207 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
1208 tk->sub->mediumName(), tk->sub->codecName(),
1209 p_sys->env->getResultMsg() );
1213 p_sys->rtsp->sendPlayCommand( *tk->sub, default_live555_callback, -1, -1, p_sys->ms->scale() );
1214 if( !wait_Live555_response(p_demux) )
1216 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1217 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1220 tk->b_selected = true;
1222 if( !tk->b_selected )
1223 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1227 if( tk->b_asf || tk->b_muxed )
1234 else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
1240 if( p_sys->i_pcr > 0 )
1243 es_out_Control( p_demux->out, ES_OUT_SET_PCR, 1 + p_sys->i_pcr );
1246 /* First warn we want to read data */
1247 p_sys->event_data = 0;
1248 for( i = 0; i < p_sys->i_track; i++ )
1250 live_track_t *tk = p_sys->track[i];
1252 if( tk->waiting == 0 )
1255 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1256 StreamRead, tk, StreamClose, tk );
1259 /* Create a task that will be called if we wait more than 300ms */
1260 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1263 p_sys->scheduler->doEventLoop( &p_sys->event_data );
1265 /* remove the task */
1266 p_sys->scheduler->unscheduleDelayedTask( task );
1268 /* Check for gap in pts value */
1269 for( i = 0; i < p_sys->i_track; i++ )
1271 live_track_t *tk = p_sys->track[i];
1273 if( !tk->b_muxed && !tk->b_rtcp_sync &&
1274 tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1276 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1278 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1279 tk->b_rtcp_sync = true;
1281 tk->i_pts = VLC_TS_INVALID;
1289 if( p_sys->b_multicast && p_sys->b_no_data &&
1290 ( p_sys->i_no_data_ti > 120 ) )
1292 /* FIXME Make this configurable
1293 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1297 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1298 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1300 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1301 var_GetBool( p_demux, "rtsp-http" );
1303 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1305 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1306 if( RollOverTcp( p_demux ) )
1308 msg_Err( p_demux, "TCP rollover failed, aborting" );
1313 msg_Err( p_demux, "no data received in 10s, aborting" );
1316 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1317 ( p_sys->i_no_data_ti > 34 ) )
1320 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1323 return p_sys->b_error ? 0 : 1;
1326 /*****************************************************************************
1328 *****************************************************************************/
1329 static int Control( demux_t *p_demux, int i_query, va_list args )
1331 demux_sys_t *p_sys = p_demux->p_sys;
1339 case DEMUX_GET_TIME:
1340 pi64 = (int64_t*)va_arg( args, int64_t * );
1341 if( p_sys->f_npt > 0 )
1343 *pi64 = (int64_t)(p_sys->f_npt * 1000000.);
1346 return VLC_EGENERIC;
1348 case DEMUX_GET_LENGTH:
1349 pi64 = (int64_t*)va_arg( args, int64_t * );
1350 if( p_sys->f_npt_length > 0 )
1352 double d_length = p_sys->f_npt_length * 1000000.0;
1353 if( d_length >= INT64_MAX )
1356 *pi64 = (int64_t)d_length;
1359 return VLC_EGENERIC;
1361 case DEMUX_GET_POSITION:
1362 pf = (double*)va_arg( args, double* );
1363 if( (p_sys->f_npt_length > 0) && (p_sys->f_npt > 0) )
1365 *pf = p_sys->f_npt / p_sys->f_npt_length;
1368 return VLC_EGENERIC;
1370 case DEMUX_SET_POSITION:
1371 case DEMUX_SET_TIME:
1372 if( p_sys->rtsp && (p_sys->f_npt_length > 0) )
1377 if( (i_query == DEMUX_SET_TIME) && (p_sys->f_npt > 0) )
1379 i64 = (int64_t)va_arg( args, int64_t );
1380 time = (float)(i64 / 1000000.0); /* in second */
1382 else if( i_query == DEMUX_SET_TIME )
1383 return VLC_EGENERIC;
1386 f = (double)va_arg( args, double );
1387 time = f * p_sys->f_npt_length; /* in second */
1390 if( p_sys->b_paused )
1392 p_sys->f_seek_request = time;
1396 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1398 if( !wait_Live555_response( p_demux ) )
1400 msg_Err( p_demux, "PAUSE before seek failed %s",
1401 p_sys->env->getResultMsg() );
1402 return VLC_EGENERIC;
1405 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1407 if( !wait_Live555_response( p_demux ) )
1409 msg_Err( p_demux, "seek PLAY failed %s",
1410 p_sys->env->getResultMsg() );
1411 return VLC_EGENERIC;
1415 for( i = 0; i < p_sys->i_track; i++ )
1417 p_sys->track[i]->b_rtcp_sync = false;
1418 p_sys->track[i]->i_pts = VLC_TS_INVALID;
1421 /* Retrieve the starttime if possible */
1422 p_sys->f_npt = p_sys->f_npt_start = p_sys->ms->playStartTime();
1424 /* Retrieve the duration if possible */
1425 if( p_sys->ms->playEndTime() > 0 )
1426 p_sys->f_npt_length = p_sys->ms->playEndTime();
1428 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1431 return VLC_EGENERIC;
1433 /* Special for access_demux */
1434 case DEMUX_CAN_PAUSE:
1435 case DEMUX_CAN_SEEK:
1436 pb = (bool*)va_arg( args, bool * );
1437 if( p_sys->rtsp && p_sys->f_npt_length > 0 )
1438 /* Not always true, but will be handled in SET_PAUSE_STATE */
1444 case DEMUX_CAN_CONTROL_PACE:
1445 pb = (bool*)va_arg( args, bool * );
1447 #if 1 /* Disable for now until we have a clock synchro algo
1448 * which works with something else than MPEG over UDP */
1455 case DEMUX_CAN_CONTROL_RATE:
1456 pb = (bool*)va_arg( args, bool * );
1457 pb2 = (bool*)va_arg( args, bool * );
1459 *pb = (p_sys->rtsp != NULL) &&
1460 (p_sys->f_npt_length > 0) &&
1461 ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1462 !var_GetBool( p_demux, "rtsp-wmserver" ) );
1466 case DEMUX_SET_RATE:
1468 double f_scale, f_old_scale;
1470 if( !p_sys->rtsp || (p_sys->f_npt_length <= 0) ||
1471 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1472 var_GetBool( p_demux, "rtsp-wmserver" ) )
1473 return VLC_EGENERIC;
1475 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1478 * "[...] should try to approximate the viewing rate, but
1479 * may restrict the range of scale values that it supports.
1480 * The response MUST contain the actual scale value chosen
1483 * Scale = 1 indicates normal play
1484 * Scale > 1 indicates fast forward
1485 * Scale < 1 && Scale > 0 indicates slow motion
1486 * Scale < 0 value indicates rewind
1489 pi_int = (int*)va_arg( args, int * );
1490 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1491 f_old_scale = p_sys->ms->scale();
1493 /* Passing -1 for the start and end time will mean liveMedia won't
1494 * create a Range: section for the RTSP message. The server should
1495 * pick up from the current position */
1496 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1498 if( !wait_Live555_response( p_demux ) )
1500 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1501 p_sys->env->getResultMsg() );
1502 return VLC_EGENERIC;
1505 if( p_sys->ms->scale() == f_old_scale )
1507 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1508 p_sys->ms->scale() );
1509 return VLC_EGENERIC;
1512 /* ReSync the stream */
1513 p_sys->f_npt_start = 0;
1517 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1518 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1522 case DEMUX_SET_PAUSE_STATE:
1524 bool b_pause = (bool)va_arg( args, int );
1525 if( p_sys->rtsp == NULL )
1526 return VLC_EGENERIC;
1528 if( b_pause == p_sys->b_paused )
1531 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1533 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1534 -1.0f, p_sys->ms->scale() );
1536 if( !wait_Live555_response( p_demux ) )
1538 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1539 return VLC_EGENERIC;
1541 p_sys->f_seek_request = -1;
1542 p_sys->b_paused = b_pause;
1544 /* When we Pause, we'll need the TimeoutPrevention thread to
1545 * handle sending the "Keep Alive" message to the server.
1546 * Unfortunately Live555 isn't thread safe and so can't
1547 * do this normally while the main Demux thread is handling
1548 * a live stream. We end up with the Timeout thread blocking
1549 * waiting for a response from the server. So when we PAUSE
1550 * we set a flag that the TimeoutPrevention function will check
1551 * and if it's set, it will trigger the GET_PARAMETER message */
1552 if( p_sys->b_paused && p_sys->p_timeout != NULL )
1553 p_sys->p_timeout->b_handle_keep_alive = true;
1554 else if( !p_sys->b_paused && p_sys->p_timeout != NULL )
1555 p_sys->p_timeout->b_handle_keep_alive = false;
1557 if( !p_sys->b_paused )
1559 for( int i = 0; i < p_sys->i_track; i++ )
1561 live_track_t *tk = p_sys->track[i];
1562 tk->b_rtcp_sync = false;
1563 tk->i_pts = VLC_TS_INVALID;
1565 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1569 /* Reset data received counter */
1570 p_sys->i_no_data_ti = 0;
1572 /* Retrieve the starttime if possible */
1573 p_sys->f_npt_start = p_sys->ms->playStartTime();
1575 /* Retrieve the duration if possible */
1576 if( p_sys->ms->playEndTime() )
1577 p_sys->f_npt_length = p_sys->ms->playEndTime();
1579 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1582 case DEMUX_GET_TITLE_INFO:
1583 case DEMUX_SET_TITLE:
1584 case DEMUX_SET_SEEKPOINT:
1585 return VLC_EGENERIC;
1587 case DEMUX_GET_PTS_DELAY:
1588 pi64 = (int64_t*)va_arg( args, int64_t * );
1589 *pi64 = INT64_C(1000)
1590 * var_InheritInteger( p_demux, "network-caching" );
1594 return VLC_EGENERIC;
1598 /*****************************************************************************
1599 * RollOverTcp: reopen the rtsp into TCP mode
1600 * XXX: ugly, a lot of code are duplicated from Open()
1601 * This should REALLY be fixed
1602 *****************************************************************************/
1603 static int RollOverTcp( demux_t *p_demux )
1605 demux_sys_t *p_sys = p_demux->p_sys;
1608 var_SetBool( p_demux, "rtsp-tcp", true );
1610 /* We close the old RTSP session */
1611 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1612 Medium::close( p_sys->ms );
1613 RTSPClient::close( p_sys->rtsp );
1615 for( i = 0; i < p_sys->i_track; i++ )
1617 live_track_t *tk = p_sys->track[i];
1619 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
1620 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1621 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1622 es_format_Clean( &tk->fmt );
1623 free( tk->p_buffer );
1626 TAB_CLEAN( p_sys->i_track, p_sys->track );
1627 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
1631 p_sys->b_no_data = true;
1632 p_sys->i_no_data_ti = 0;
1633 p_sys->p_out_asf = NULL;
1635 /* Reopen rtsp client */
1636 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1638 msg_Err( p_demux, "Failed to connect with rtsp://%s",
1643 if( p_sys->p_sdp == NULL )
1645 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1649 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1651 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1655 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1661 return VLC_EGENERIC;
1665 /*****************************************************************************
1667 *****************************************************************************/
1668 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1670 const uint8_t *p_data, unsigned i_size )
1672 const unsigned i_packet_size = p_demux->p_sys->asfh.i_min_data_packet_size;
1673 block_t *p_list = NULL;
1675 while( i_size >= 4 )
1677 unsigned i_flags = p_data[0];
1678 unsigned i_length_offset = (p_data[1] << 16) |
1681 bool b_length = i_flags & 0x40;
1682 bool b_relative_ts = i_flags & 0x20;
1683 bool b_duration = i_flags & 0x10;
1684 bool b_location_id = i_flags & 0x08;
1686 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1687 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1688 unsigned i_header_size = 4;
1696 if( i_header_size > i_size )
1698 msg_Warn( p_demux, "Invalid header size" );
1703 * When b_length is true, the streams I found do not seems to respect
1704 * the documentation.
1705 * From them, I have failed to find which choice between '__MIN()' or
1706 * 'i_length_offset - i_header_size' is the right one.
1710 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1712 i_payload = i_size - i_header_size;
1714 if( !tk->p_asf_block )
1716 tk->p_asf_block = block_Alloc( i_packet_size );
1717 if( !tk->p_asf_block )
1719 tk->p_asf_block->i_buffer = 0;
1721 unsigned i_offset = b_length ? 0 : i_length_offset;
1722 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1724 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1725 tk->p_asf_block->i_buffer += i_payload;
1728 /* We have a complete packet */
1729 tk->p_asf_block->i_buffer = i_packet_size;
1730 block_ChainAppend( &p_list, tk->p_asf_block );
1731 tk->p_asf_block = NULL;
1736 /* Reset on broken stream */
1737 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1738 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1739 tk->p_asf_block->i_buffer = 0;
1743 p_data += i_header_size + i_payload;
1744 i_size -= i_header_size + i_payload;
1749 /*****************************************************************************
1751 *****************************************************************************/
1752 static void StreamRead( void *p_private, unsigned int i_size,
1753 unsigned int i_truncated_bytes, struct timeval pts,
1754 unsigned int duration )
1756 VLC_UNUSED( duration );
1758 live_track_t *tk = (live_track_t*)p_private;
1759 demux_t *p_demux = tk->p_demux;
1760 demux_sys_t *p_sys = p_demux->p_sys;
1763 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1765 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1766 (int64_t)pts.tv_usec;
1768 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1769 i_pts &= INT64_C(0x00ffffffffffffff);
1771 /* Retrieve NPT for this pts */
1772 tk->f_npt = tk->sub->getNormalPlayTime(pts);
1774 if( tk->b_quicktime && tk->p_es == NULL )
1776 QuickTimeGenericRTPSource *qtRTPSource =
1777 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1778 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1779 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1781 /* Get codec informations from the quicktime atoms :
1782 * http://developer.apple.com/quicktime/icefloe/dispatch026.html */
1783 if( tk->fmt.i_cat == VIDEO_ES ) {
1784 if( qtState.sdAtomSize < 16 + 32 )
1787 p_sys->event_data = 0xff;
1791 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1792 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1793 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1795 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1797 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1798 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1799 + qtRTPSource->qtState.sdAtomSize;
1800 while (pos+8 < endpos) {
1801 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1802 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1803 if( memcmp(pos+4, "avcC", 4) == 0 &&
1805 atomLength <= INT_MAX )
1807 tk->fmt.i_extra = atomLength-8;
1808 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1809 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1817 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1818 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1819 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1823 if( qtState.sdAtomSize < 24 )
1826 p_sys->event_data = 0xff;
1830 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1831 tk->fmt.audio.i_bitspersample = (sdAtom[22] << 8) | sdAtom[23];
1833 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1837 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1839 pts.tv_sec * 1000000LL + pts.tv_usec );
1842 /* grow buffer if it looks like buffer is too small, but don't eat
1843 * up all the memory on strange streams */
1844 if( i_truncated_bytes > 0 )
1846 if( tk->i_buffer < 2000000 )
1849 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1850 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1851 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1854 msg_Warn( p_demux, "realloc failed" );
1858 tk->p_buffer = (uint8_t*)p_tmp;
1863 if( tk->b_discard_trunc )
1865 p_sys->event_data = 0xff;
1871 assert( i_size <= tk->i_buffer );
1873 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1874 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1876 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1878 p_block = block_Alloc( i_size + 1 );
1879 p_block->p_buffer[0] = amrSource->lastFrameHeader();
1880 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1882 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1884 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1885 uint32_t header = h261Source->lastSpecialHeader();
1886 p_block = block_Alloc( i_size + 4 );
1887 memcpy( p_block->p_buffer, &header, 4 );
1888 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1890 if( tk->sub->rtpSource()->curPacketMarkerBit() )
1891 p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1893 else if( tk->fmt.i_codec == VLC_CODEC_H264 )
1895 if( (tk->p_buffer[0] & 0x1f) >= 24 )
1896 msg_Warn( p_demux, "unsupported NAL type for H264" );
1898 /* Normal NAL type */
1899 p_block = block_Alloc( i_size + 4 );
1900 p_block->p_buffer[0] = 0x00;
1901 p_block->p_buffer[1] = 0x00;
1902 p_block->p_buffer[2] = 0x00;
1903 p_block->p_buffer[3] = 0x01;
1904 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1906 else if( tk->b_asf )
1908 p_block = StreamParseAsf( p_demux, tk,
1909 tk->sub->rtpSource()->curPacketMarkerBit(),
1910 tk->p_buffer, i_size );
1914 p_block = block_Alloc( i_size );
1915 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1918 if( p_sys->i_pcr < i_pts )
1920 p_sys->i_pcr = i_pts;
1923 /* Update our global npt value */
1924 if( tk->f_npt > 0 &&
1925 ( tk->f_npt < p_sys->f_npt_length || p_sys->f_npt_length <= 0 ) )
1926 p_sys->f_npt = tk->f_npt;
1930 if( !tk->b_muxed && !tk->b_asf )
1932 if( i_pts != tk->i_pts )
1933 p_block->i_pts = VLC_TS_0 + i_pts;
1934 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
1935 p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? VLC_TS_INVALID : (VLC_TS_0 + i_pts);
1939 stream_DemuxSend( tk->p_out_muxed, p_block );
1940 else if( tk->b_asf )
1941 stream_DemuxSend( p_sys->p_out_asf, p_block );
1943 es_out_Send( p_demux->out, tk->p_es, p_block );
1946 /* warn that's ok */
1947 p_sys->event_data = 0xff;
1949 /* we have read data */
1951 p_demux->p_sys->b_no_data = false;
1952 p_demux->p_sys->i_no_data_ti = 0;
1954 if( i_pts > 0 && !tk->b_muxed )
1960 /*****************************************************************************
1962 *****************************************************************************/
1963 static void StreamClose( void *p_private )
1965 live_track_t *tk = (live_track_t*)p_private;
1966 demux_t *p_demux = tk->p_demux;
1967 demux_sys_t *p_sys = p_demux->p_sys;
1968 tk->b_selected = false;
1969 p_sys->event_rtsp = 0xff;
1970 p_sys->event_data = 0xff;
1973 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1976 for( int i = 0; i < p_sys->i_track; i++ )
1978 if( p_sys->track[i]->b_selected )
1981 msg_Dbg( p_demux, "RTSP track Close, %d track remaining", nb_tracks );
1983 p_sys->b_error = true;
1987 /*****************************************************************************
1989 *****************************************************************************/
1990 static void TaskInterruptRTSP( void *p_private )
1992 demux_t *p_demux = (demux_t*)p_private;
1995 p_demux->p_sys->event_rtsp = 0xff;
1998 static void TaskInterruptData( void *p_private )
2000 demux_t *p_demux = (demux_t*)p_private;
2002 p_demux->p_sys->i_no_data_ti++;
2005 p_demux->p_sys->event_data = 0xff;
2008 /*****************************************************************************
2010 *****************************************************************************/
2012 static void* TimeoutPrevention( void *p_data )
2014 timeout_thread_t *p_timeout = (timeout_thread_t *)p_data;
2018 /* Voodoo (= no) thread safety here! *Ahem* */
2019 if( p_timeout->b_handle_keep_alive )
2021 char *psz_bye = NULL;
2022 int canc = vlc_savecancel ();
2024 p_timeout->p_sys->rtsp->sendGetParameterCommand( *p_timeout->p_sys->ms, NULL, psz_bye );
2025 vlc_restorecancel (canc);
2027 p_timeout->p_sys->b_timeout_call = !p_timeout->b_handle_keep_alive;
2029 msleep (((int64_t)p_timeout->p_sys->i_timeout - 2) * CLOCK_FREQ);
2031 assert(0); /* dead code */
2034 /*****************************************************************************
2036 *****************************************************************************/
2037 static int ParseASF( demux_t *p_demux )
2039 demux_sys_t *p_sys = p_demux->p_sys;
2041 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
2042 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2046 /* Parse the asf header */
2047 if( psz_asf == NULL )
2048 return VLC_EGENERIC;
2050 psz_asf += strlen( psz_marker );
2051 psz_asf = strdup( psz_asf ); /* Duplicate it */
2052 psz_end = strchr( psz_asf, '\n' );
2054 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2057 if( psz_asf >= psz_end )
2060 return VLC_EGENERIC;
2063 /* Always smaller */
2064 p_header = block_Alloc( psz_end - psz_asf );
2065 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2066 p_header->i_buffer, psz_asf );
2067 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2068 if( p_header->i_buffer <= 0 )
2071 return VLC_EGENERIC;
2074 /* Parse it to get packet size */
2075 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2077 /* Send it to demuxer */
2078 stream_DemuxSend( p_sys->p_out_asf, p_header );
2085 static unsigned char* parseH264ConfigStr( char const* configStr,
2086 unsigned int& configSize )
2089 size_t i_records = 1;
2093 if( configStr == NULL || *configStr == '\0' )
2096 psz = dup = strdup( configStr );
2098 /* Count the number of commas */
2099 for( psz = dup; *psz != '\0'; ++psz )
2108 size_t configMax = 5*strlen(dup);
2109 unsigned char *cfg = new unsigned char[configMax];
2111 for( size_t i = 0; i < i_records; ++i )
2113 cfg[configSize++] = 0x00;
2114 cfg[configSize++] = 0x00;
2115 cfg[configSize++] = 0x00;
2116 cfg[configSize++] = 0x01;
2118 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2119 configMax-configSize, psz );
2120 psz += strlen(psz)+1;