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 *****************************************************************************/
37 #include <vlc_common.h>
38 #include <vlc_plugin.h>
39 #include <vlc_input.h>
40 #include <vlc_demux.h>
41 #include <vlc_dialog.h>
43 #include <vlc_strings.h>
44 #include <vlc_interrupt.h>
51 # include <winsock2.h>
54 #include <UsageEnvironment.hh>
55 #include <BasicUsageEnvironment.hh>
56 #include <GroupsockHelper.hh>
57 #include <liveMedia.hh>
58 #include <liveMedia_version.hh>
62 #include "../access/mms/asf.h" /* Who said ugly ? */
65 /*****************************************************************************
67 *****************************************************************************/
68 static int Open ( vlc_object_t * );
69 static void Close( vlc_object_t * );
71 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
72 #define KASENNA_LONGTEXT N_( "Kasenna servers use an old and nonstandard " \
73 "dialect of RTSP. With this parameter VLC will try this dialect, but "\
74 "then it cannot connect to normal RTSP servers." )
76 #define WMSERVER_TEXT N_("WMServer RTSP dialect")
77 #define WMSERVER_LONGTEXT N_("WMServer uses a nonstandard dialect " \
78 "of RTSP. Selecting this parameter will tell VLC to assume some " \
79 "options contrary to RFC 2326 guidelines.")
81 #define USER_TEXT N_("Username")
82 #define USER_LONGTEXT N_("Sets the username for the connection, " \
83 "if no username or password are set in the url.")
84 #define PASS_TEXT N_("Password")
85 #define PASS_LONGTEXT N_("Sets the password for the connection, " \
86 "if no username or password are set in the url.")
87 #define FRAME_BUFFER_SIZE_TEXT N_("RTSP frame buffer size")
88 #define FRAME_BUFFER_SIZE_LONGTEXT N_("RTSP start frame buffer size of the video " \
89 "track, can be increased in case of broken pictures due " \
90 "to too small buffer.")
91 #define DEFAULT_FRAME_BUFFER_SIZE 100000
94 set_description( N_("RTP/RTSP/SDP demuxer (using Live555)" ) )
95 set_capability( "demux", 50 )
96 set_shortname( "RTP/RTSP")
97 set_callbacks( Open, Close )
98 add_shortcut( "live", "livedotcom" )
99 set_category( CAT_INPUT )
100 set_subcategory( SUBCAT_INPUT_DEMUX )
103 set_description( N_("RTSP/RTP access and demux") )
104 add_shortcut( "rtsp", "pnm", "live", "livedotcom", "satip" )
105 set_capability( "access_demux", 0 )
106 set_callbacks( Open, Close )
107 add_bool( "rtsp-tcp", false,
108 N_("Use RTP over RTSP (TCP)"),
109 N_("Use RTP over RTSP (TCP)"), true )
111 add_integer( "rtp-client-port", -1,
113 N_("Port to use for the RTP source of the session"), true )
114 add_bool( "rtsp-mcast", false,
115 N_("Force multicast RTP via RTSP"),
116 N_("Force multicast RTP via RTSP"), true )
118 add_bool( "rtsp-http", false,
119 N_("Tunnel RTSP and RTP over HTTP"),
120 N_("Tunnel RTSP and RTP over HTTP"), true )
122 add_integer( "rtsp-http-port", 80,
123 N_("HTTP tunnel port"),
124 N_("Port to use for tunneling the RTSP/RTP over HTTP."),
126 add_bool( "rtsp-kasenna", false, KASENNA_TEXT,
127 KASENNA_LONGTEXT, true )
129 add_bool( "rtsp-wmserver", false, WMSERVER_TEXT,
130 WMSERVER_LONGTEXT, true)
132 add_string( "rtsp-user", NULL, USER_TEXT,
133 USER_LONGTEXT, true )
135 add_password( "rtsp-pwd", NULL, PASS_TEXT,
136 PASS_LONGTEXT, true )
137 add_integer( "rtsp-frame-buffer-size", DEFAULT_FRAME_BUFFER_SIZE,
138 FRAME_BUFFER_SIZE_TEXT, FRAME_BUFFER_SIZE_LONGTEXT,
143 /*****************************************************************************
145 *****************************************************************************/
150 MediaSubsession *sub;
158 block_t *p_asf_block;
159 bool b_discard_trunc;
160 stream_t *p_out_muxed; /* for muxed stream */
163 unsigned int i_buffer;
174 struct timeout_thread_t
178 bool b_handle_keep_alive;
185 char *p_sdp; /* XXX mallocated */
186 char *psz_path; /* URL-encoded path */
190 TaskScheduler *scheduler;
191 UsageEnvironment *env ;
196 live_track_t **track;
204 int64_t i_pcr; /* The clock */
209 /* timeout thread information */
210 int i_timeout; /* session timeout value in seconds */
211 bool b_timeout_call;/* mark to send an RTSP call to prevent server timeout */
212 timeout_thread_t *p_timeout; /* the actual thread that makes sure we don't timeout */
213 vlc_mutex_t timeout_mutex; /* Serialise calls to live555 in timeout thread w.r.t. Demux()/Control() */
217 bool b_multicast; /* if one of the tracks is multicasted */
218 bool b_no_data; /* if we never received any data */
219 int i_no_data_ti; /* consecutive number of TaskInterrupt */
224 bool b_get_param; /* Does the server support GET_PARAMETER */
225 bool b_paused; /* Are we paused? */
227 int i_live555_ret; /* live555 callback return code */
229 float f_seek_request;/* In case we receive a seek request while paused*/
233 class RTSPClientVlc : public RTSPClient
236 RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
237 char const* applicationName, portNumBits tunnelOverHTTPPortNum,
238 demux_sys_t *p_sys) :
239 RTSPClient( env, rtspURL, verbosityLevel, applicationName,
240 tunnelOverHTTPPortNum
241 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1373932800
251 static int Demux ( demux_t * );
252 static int Control( demux_t *, int, va_list );
254 static int Connect ( demux_t * );
255 static int SessionsSetup( demux_t * );
256 static int Play ( demux_t *);
257 static int ParseASF ( demux_t * );
258 static int RollOverTcp ( demux_t * );
260 static void StreamRead ( void *, unsigned int, unsigned int,
261 struct timeval, unsigned int );
262 static void StreamClose ( void * );
263 static void TaskInterruptData( void * );
264 static void TaskInterruptRTSP( void * );
266 static void* TimeoutPrevention( void * );
268 static unsigned char* parseH264ConfigStr( char const* configStr,
269 unsigned int& configSize );
270 static unsigned char* parseVorbisConfigStr( char const* configStr,
271 unsigned int& configSize );
273 /*****************************************************************************
275 *****************************************************************************/
276 static int Open ( vlc_object_t *p_this )
278 demux_t *p_demux = (demux_t*)p_this;
279 demux_sys_t *p_sys = NULL;
282 int i_error = VLC_EGENERIC;
286 /* See if it looks like a SDP
287 v, o, s fields are mandatory and in this order */
288 const uint8_t *p_peek;
289 if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
291 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
292 memcmp( p_peek, "v=0\n", 4 ) &&
293 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
299 p_demux->pf_demux = Demux;
300 p_demux->pf_control= Control;
301 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
302 if( !p_sys ) return VLC_ENOMEM;
304 msg_Dbg( p_demux, "version " LIVEMEDIA_LIBRARY_VERSION_STRING );
306 TAB_INIT( p_sys->i_track, p_sys->track );
308 p_sys->f_npt_start = 0.;
309 p_sys->f_npt_length = 0.;
310 p_sys->b_no_data = true;
311 p_sys->psz_path = strdup( p_demux->psz_location );
312 p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
313 p_sys->f_seek_request = -1;
314 vlc_mutex_init(&p_sys->timeout_mutex);
316 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
317 vlc_UrlParse( &p_sys->url, p_sys->psz_path );
319 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
321 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
324 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
326 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
330 if( strcasecmp( p_demux->psz_access, "sdp" ) )
332 char *p = p_sys->psz_path;
333 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
336 if( strcasecmp( p_demux->psz_access, "satip" ) == 0 )
338 if( asprintf(&p_sys->p_sdp, "v=0\r\n"
341 "i=SATIP RTP Stream\r\n"
342 "m=video 0 RTP/AVP 33\r\n"
343 "a=control:rtsp://%s\r\n\r\n",
344 p_sys->url.psz_host, p_sys->psz_path) < 0 )
348 if( p_demux->s != NULL )
350 /* Gather the complete sdp file */
352 int i_sdp_max = 1000;
353 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
357 i_error = VLC_ENOMEM;
363 int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
364 i_sdp_max - i_sdp - 1 );
367 msg_Err( p_demux, "failed to read SDP" );
374 if( i_read < i_sdp_max - i_sdp - 1 )
381 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
383 p_sys->p_sdp = (char*)p_sdp;
385 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
387 msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
391 if( p_sys->p_sdp == NULL )
393 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
394 i_error = VLC_ENOMEM;
398 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
400 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
404 if( p_sys->b_real ) goto error;
406 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
409 if( p_sys->p_out_asf && ParseASF( p_demux ) )
411 msg_Err( p_demux, "cannot find a usable asf header" );
412 /* TODO Clean tracks */
416 if( p_sys->i_track <= 0 )
426 /*****************************************************************************
428 *****************************************************************************/
429 static void Close( vlc_object_t *p_this )
431 demux_t *p_demux = (demux_t*)p_this;
432 demux_sys_t *p_sys = p_demux->p_sys;
434 if( p_sys->p_timeout )
436 vlc_cancel( p_sys->p_timeout->handle );
437 vlc_join( p_sys->p_timeout->handle, NULL );
438 free( p_sys->p_timeout );
441 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
442 if( p_sys->ms ) Medium::close( p_sys->ms );
443 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
444 if( p_sys->env ) p_sys->env->reclaim();
446 for( int i = 0; i < p_sys->i_track; i++ )
448 live_track_t *tk = p_sys->track[i];
450 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
451 es_format_Clean( &tk->fmt );
452 free( tk->p_buffer );
455 TAB_CLEAN( p_sys->i_track, p_sys->track );
456 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
457 delete p_sys->scheduler;
458 free( p_sys->p_sdp );
459 free( p_sys->psz_path );
461 vlc_UrlClean( &p_sys->url );
462 vlc_mutex_destroy(&p_sys->timeout_mutex);
467 static inline const char *strempty( const char *s ) { return s?s:""; }
468 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
470 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
472 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
473 demux_sys_t *p_sys = client_vlc->p_sys;
474 delete []result_string;
475 p_sys->i_live555_ret = result_code;
476 p_sys->b_error = p_sys->i_live555_ret != 0;
477 p_sys->event_rtsp = 1;
480 /* return true if the RTSP command succeeded */
481 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
484 demux_sys_t * p_sys = p_demux->p_sys;
485 p_sys->event_rtsp = 0;
488 /* Create a task that will be called if we wait more than timeout ms */
489 task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000,
493 p_sys->event_rtsp = 0;
494 p_sys->b_error = true;
495 p_sys->i_live555_ret = 0;
496 p_sys->scheduler->doEventLoop( &p_sys->event_rtsp );
497 //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
500 /* remove the task */
501 p_sys->scheduler->unscheduleDelayedTask( task );
503 return !p_sys->b_error;
506 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
507 char* result_string )
509 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
510 demux_sys_t *p_sys = client_vlc->p_sys;
511 p_sys->i_live555_ret = result_code;
512 if ( result_code == 0 )
514 char* sdpDescription = result_string;
515 free( p_sys->p_sdp );
519 p_sys->p_sdp = strdup( sdpDescription );
520 p_sys->b_error = false;
524 p_sys->b_error = true;
525 delete[] result_string;
526 p_sys->event_rtsp = 1;
529 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
530 char* result_string )
532 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
533 demux_sys_t *p_sys = client_vlc->p_sys;
535 // If OPTIONS fails, assume GET_PARAMETER is not supported but
536 // still continue on with the stream. Some servers (foscam)
537 // return 501/not implemented for OPTIONS.
539 && result_string != NULL
540 && strstr( result_string, "GET_PARAMETER" ) != NULL;
541 if( p_sys->p_sdp == NULL )
543 client->sendDescribeCommand( continueAfterDESCRIBE );
547 p_sys->b_error = false;
548 p_sys->event_rtsp = 1;
550 delete[] result_string;
553 /*****************************************************************************
554 * Connect: connects to the RTSP server to setup the session DESCRIBE
555 *****************************************************************************/
556 static int Connect( demux_t *p_demux )
558 demux_sys_t *p_sys = p_demux->p_sys;
559 Authenticator authenticator;
560 char *psz_user = NULL;
561 char *psz_pwd = NULL;
562 char *psz_url = NULL;
564 int i_ret = VLC_SUCCESS;
565 const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
567 /* Get the user name and password */
568 if( p_sys->url.psz_username || p_sys->url.psz_password )
570 /* Create the URL by stripping away the username/password part */
571 if( p_sys->url.i_port == 0 )
572 p_sys->url.i_port = 554;
573 if( asprintf( &psz_url, "rtsp://%s:%d%s%s%s",
574 strempty( p_sys->url.psz_host ),
576 strempty( p_sys->url.psz_path ),
577 p_sys->url.psz_option ? "?" : "",
578 strempty(p_sys->url.psz_option) ) == -1 )
581 psz_user = strdup( strempty( p_sys->url.psz_username ) );
582 psz_pwd = strdup( strempty( p_sys->url.psz_password ) );
586 if( asprintf( &psz_url, "rtsp://%s", p_sys->psz_path ) == -1 )
589 psz_user = var_InheritString( p_demux, "rtsp-user" );
590 psz_pwd = var_InheritString( p_demux, "rtsp-pwd" );
594 /* FIXME: This is naive and incorrect; it does not prevent the thread
595 * getting stuck in blocking socket operations. */
598 i_ret = VLC_EGENERIC;
602 if( var_CreateGetBool( p_demux, "rtsp-http" ) )
603 i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
605 p_sys->rtsp = new RTSPClientVlc( *p_sys->env, psz_url,
606 var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
607 "LibVLC/" VERSION, i_http_port, p_sys );
610 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
611 p_sys->env->getResultMsg() );
612 i_ret = VLC_EGENERIC;
616 /* Kasenna enables KeepAlive by analysing the User-Agent string.
617 * Appending _KA to the string should be enough to enable this feature,
618 * however, there is a bug where the _KA doesn't get parsed from the
619 * default User-Agent as created by VLC/Live555 code. This is probably due
620 * to spaces in the string or the string being too long. Here we override
621 * the default string with a more compact version.
623 if( var_InheritBool( p_demux, "rtsp-kasenna" ))
625 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
629 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
631 p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
633 if( !wait_Live555_response( p_demux, i_timeout ) )
635 int i_code = p_sys->i_live555_ret;
638 msg_Dbg( p_demux, "authentication failed" );
642 dialog_Login( p_demux, &psz_user, &psz_pwd,
643 _("RTSP authentication"), "%s",
644 _("Please enter a valid login name and a password.") );
645 if( psz_user != NULL && psz_pwd != NULL )
647 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
651 else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
653 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
654 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
655 var_SetBool( p_demux, "rtsp-http", true );
656 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
663 msg_Dbg( p_demux, "connection timeout" );
666 msg_Dbg( p_demux, "connection error %d", i_code );
668 dialog_Fatal( p_demux, _("RTSP connection failed"),
669 _("Access to the stream is denied by the server configuration.") );
671 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
674 i_ret = VLC_EGENERIC;
678 /* malloc-ated copy */
686 /*****************************************************************************
687 * SessionsSetup: prepares the subsessions and does the SETUP
688 *****************************************************************************/
689 static int SessionsSetup( demux_t *p_demux )
691 demux_sys_t *p_sys = p_demux->p_sys;
692 MediaSubsessionIterator *iter = NULL;
693 MediaSubsession *sub = NULL;
697 int i_return = VLC_SUCCESS;
698 unsigned int i_receive_buffer = 0;
699 int i_frame_buffer = DEFAULT_FRAME_BUFFER_SIZE;
700 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
701 const char *p_sess_lang = NULL;
704 b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
705 var_GetBool( p_demux, "rtsp-http" );
706 i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
709 /* Create the session from the SDP */
710 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
712 msg_Err( p_demux, "Could not create the RTSP Session: %s",
713 p_sys->env->getResultMsg() );
717 if( strcmp( p_sys->p_sdp, "m=" ) != 0 )
719 const char *p_sess_attr_end;
721 p_sess_attr_end = strstr( p_sys->p_sdp, "\nm=" );
722 if( !p_sess_attr_end )
723 p_sess_attr_end = strstr( p_sys->p_sdp, "\rm=" );
725 p_sess_lang = p_sess_attr_end ? strstr( p_sys->p_sdp, "a=lang:" ) : NULL;
727 p_sess_lang - p_sys->p_sdp > p_sess_attr_end - p_sys->p_sdp )
731 /* Initialise each media subsession */
732 iter = new MediaSubsessionIterator( *p_sys->ms );
733 while( ( sub = iter->next() ) != NULL )
738 /* Value taken from mplayer */
739 if( !strcmp( sub->mediumName(), "audio" ) )
740 i_receive_buffer = 100000;
741 else if( !strcmp( sub->mediumName(), "video" ) )
743 int i_var_buf_size = var_InheritInteger( p_demux, "rtsp-frame-buffer-size" );
744 if( i_var_buf_size > 0 )
745 i_frame_buffer = i_var_buf_size;
746 i_receive_buffer = 2000000;
748 else if( !strcmp( sub->mediumName(), "text" ) )
752 if( strcasestr( sub->codecName(), "REAL" ) )
754 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
755 p_sys->b_real = true; /* This is a problem, we'll handle it later */
759 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
760 bInit = sub->initiate( 0 );
762 bInit = sub->initiate();
766 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
767 sub->mediumName(), sub->codecName(),
768 p_sys->env->getResultMsg() );
772 if( sub->rtpSource() != NULL )
774 int fd = sub->rtpSource()->RTPgs()->socketNum();
776 /* Increase the buffer size */
777 if( i_receive_buffer > 0 )
778 increaseReceiveBufferTo( *p_sys->env, fd, i_receive_buffer );
780 /* Increase the RTP reorder timebuffer just a bit */
781 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
783 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
786 /* Issue the SETUP */
790 if( i_client_port != -1 )
792 sub->setClientPortNum( i_client_port );
796 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
797 toBool( b_rtsp_tcp ),
798 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
799 if( !wait_Live555_response( p_demux ) )
801 /* if we get an unsupported transport error, toggle TCP
802 * use and try again */
803 if( p_sys->i_live555_ret == 461 )
804 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
805 !toBool( b_rtsp_tcp ), False );
806 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
808 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
809 sub->mediumName(), sub->codecName(),
810 p_sys->env->getResultMsg() );
815 var_SetBool( p_demux, "rtsp-tcp", true );
821 /* Check if we will receive data from this subsession for
823 if( sub->readSource() == NULL ) continue;
824 if( !p_sys->b_multicast )
826 /* We need different rollover behaviour for multicast */
827 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
830 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
836 tk->p_demux = p_demux;
839 tk->b_quicktime = false;
841 tk->p_asf_block = NULL;
843 tk->b_discard_trunc = false;
844 tk->p_out_muxed = NULL;
846 tk->b_rtcp_sync = false;
847 tk->i_pts = VLC_TS_INVALID;
849 tk->b_selected = true;
850 tk->i_buffer = i_frame_buffer;
851 tk->p_buffer = (uint8_t *)malloc( i_frame_buffer );
860 /* Value taken from mplayer */
861 if( !strcmp( sub->mediumName(), "audio" ) )
863 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
864 tk->fmt.audio.i_channels = sub->numChannels();
865 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
867 if( !strcmp( sub->codecName(), "MPA" ) ||
868 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
869 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
871 tk->fmt.i_codec = VLC_CODEC_MPGA;
872 tk->fmt.audio.i_rate = 0;
874 else if( !strcmp( sub->codecName(), "AC3" ) )
876 tk->fmt.i_codec = VLC_CODEC_A52;
877 tk->fmt.audio.i_rate = 0;
879 else if( !strcmp( sub->codecName(), "L16" ) )
881 tk->fmt.i_codec = VLC_CODEC_S16B;
882 tk->fmt.audio.i_bitspersample = 16;
884 else if( !strcmp( sub->codecName(), "L20" ) )
886 tk->fmt.i_codec = VLC_CODEC_S20B;
887 tk->fmt.audio.i_bitspersample = 20;
889 else if( !strcmp( sub->codecName(), "L24" ) )
891 tk->fmt.i_codec = VLC_CODEC_S24B;
892 tk->fmt.audio.i_bitspersample = 24;
894 else if( !strcmp( sub->codecName(), "L8" ) )
896 tk->fmt.i_codec = VLC_CODEC_U8;
897 tk->fmt.audio.i_bitspersample = 8;
899 else if( !strcmp( sub->codecName(), "DAT12" ) )
901 tk->fmt.i_codec = VLC_CODEC_DAT12;
902 tk->fmt.audio.i_bitspersample = 12;
904 else if( !strcmp( sub->codecName(), "PCMU" ) )
906 tk->fmt.i_codec = VLC_CODEC_MULAW;
907 tk->fmt.audio.i_bitspersample = 8;
909 else if( !strcmp( sub->codecName(), "PCMA" ) )
911 tk->fmt.i_codec = VLC_CODEC_ALAW;
912 tk->fmt.audio.i_bitspersample = 8;
914 else if( !strncmp( sub->codecName(), "G726", 4 ) )
916 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
917 tk->fmt.audio.i_rate = 8000;
918 tk->fmt.audio.i_channels = 1;
919 if( !strcmp( sub->codecName()+5, "40" ) )
920 tk->fmt.i_bitrate = 40000;
921 else if( !strcmp( sub->codecName()+5, "32" ) )
922 tk->fmt.i_bitrate = 32000;
923 else if( !strcmp( sub->codecName()+5, "24" ) )
924 tk->fmt.i_bitrate = 24000;
925 else if( !strcmp( sub->codecName()+5, "16" ) )
926 tk->fmt.i_bitrate = 16000;
928 else if( !strcmp( sub->codecName(), "AMR" ) )
930 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
932 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
934 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
936 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
938 unsigned int i_extra;
941 tk->fmt.i_codec = VLC_CODEC_MP4A;
943 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
946 tk->fmt.i_extra = i_extra;
947 tk->fmt.p_extra = xmalloc( i_extra );
948 memcpy( tk->fmt.p_extra, p_extra, i_extra );
951 /* Because the "faad" decoder does not handle the LATM
952 * data length field at the start of each returned LATM
953 * frame, tell the RTP source to omit. */
954 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
956 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
958 unsigned int i_extra;
961 tk->fmt.i_codec = VLC_CODEC_MP4A;
963 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
966 tk->fmt.i_extra = i_extra;
967 tk->fmt.p_extra = xmalloc( i_extra );
968 memcpy( tk->fmt.p_extra, p_extra, i_extra );
972 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
975 if( p_sys->p_out_asf == NULL )
976 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
979 else if( !strcmp( sub->codecName(), "X-QT" ) ||
980 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
982 tk->b_quicktime = true;
984 else if( !strcmp( sub->codecName(), "SPEEX" ) )
986 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
988 else if( !strcmp( sub->codecName(), "VORBIS" ) )
990 tk->fmt.i_codec = VLC_CODEC_VORBIS;
991 unsigned int i_extra;
992 unsigned char *p_extra;
993 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
996 tk->fmt.i_extra = i_extra;
997 tk->fmt.p_extra = p_extra;
1000 msg_Warn( p_demux,"Missing or unsupported vorbis header." );
1002 else if( !strcmp( sub->codecName(), "OPUS" ) )
1004 tk->fmt.i_codec = VLC_CODEC_OPUS;
1007 else if( !strcmp( sub->mediumName(), "video" ) )
1009 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
1010 if( !strcmp( sub->codecName(), "MPV" ) )
1012 tk->fmt.i_codec = VLC_CODEC_MPGV;
1013 tk->fmt.b_packetized = false;
1015 else if( !strcmp( sub->codecName(), "H263" ) ||
1016 !strcmp( sub->codecName(), "H263-1998" ) ||
1017 !strcmp( sub->codecName(), "H263-2000" ) )
1019 tk->fmt.i_codec = VLC_CODEC_H263;
1021 else if( !strcmp( sub->codecName(), "H261" ) )
1023 tk->fmt.i_codec = VLC_CODEC_H261;
1025 else if( !strcmp( sub->codecName(), "H264" ) )
1027 unsigned int i_extra = 0;
1028 uint8_t *p_extra = NULL;
1030 tk->fmt.i_codec = VLC_CODEC_H264;
1031 tk->fmt.b_packetized = false;
1033 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
1036 tk->fmt.i_extra = i_extra;
1037 tk->fmt.p_extra = xmalloc( i_extra );
1038 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1043 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1393372800 // 2014.02.26
1044 else if( !strcmp( sub->codecName(), "H265" ) )
1046 unsigned int i_extra1 = 0, i_extra2 = 0, i_extra3 = 0, i_extraTot;
1047 uint8_t *p_extra1 = NULL, *p_extra2 = NULL, *p_extra3 = NULL;
1049 tk->fmt.i_codec = VLC_CODEC_HEVC;
1050 tk->fmt.b_packetized = false;
1052 p_extra1 = parseH264ConfigStr( sub->fmtp_spropvps(), i_extra1 );
1053 p_extra2 = parseH264ConfigStr( sub->fmtp_spropsps(), i_extra2 );
1054 p_extra3 = parseH264ConfigStr( sub->fmtp_sproppps(), i_extra3 );
1055 i_extraTot = i_extra1 + i_extra2 + i_extra3;
1056 if( i_extraTot > 0 )
1058 tk->fmt.i_extra = i_extraTot;
1059 tk->fmt.p_extra = xmalloc( i_extraTot );
1062 memcpy( tk->fmt.p_extra, p_extra1, i_extra1 );
1066 memcpy( ((char*)tk->fmt.p_extra)+i_extra1, p_extra2, i_extra2 );
1070 memcpy( ((char*)tk->fmt.p_extra)+i_extra1+i_extra2, p_extra3, i_extra3 );
1073 delete[] p_extra1; delete[] p_extra2; delete[] p_extra3;
1077 else if( !strcmp( sub->codecName(), "JPEG" ) )
1079 tk->fmt.i_codec = VLC_CODEC_MJPG;
1081 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1083 unsigned int i_extra;
1086 tk->fmt.i_codec = VLC_CODEC_MP4V;
1088 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1091 tk->fmt.i_extra = i_extra;
1092 tk->fmt.p_extra = xmalloc( i_extra );
1093 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1097 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1098 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1099 !strcmp( sub->codecName(), "X-QDM" ) ||
1100 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1101 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1103 tk->b_quicktime = true;
1105 else if( !strcmp( sub->codecName(), "MP2T" ) )
1108 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
1110 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1111 !strcmp( sub->codecName(), "MP1S" ) )
1114 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
1117 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1120 if( p_sys->p_out_asf == NULL )
1121 p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
1124 else if( !strcmp( sub->codecName(), "DV" ) )
1127 tk->b_discard_trunc = true;
1128 tk->p_out_muxed = stream_DemuxNew( p_demux, "rawdv",
1131 else if( !strcmp( sub->codecName(), "VP8" ) )
1133 tk->fmt.i_codec = VLC_CODEC_VP8;
1135 else if( !strcmp( sub->codecName(), "THEORA" ) )
1137 tk->fmt.i_codec = VLC_CODEC_THEORA;
1138 unsigned int i_extra;
1139 unsigned char *p_extra;
1140 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
1143 tk->fmt.i_extra = i_extra;
1144 tk->fmt.p_extra = p_extra;
1147 msg_Warn( p_demux,"Missing or unsupported theora header." );
1150 else if( !strcmp( sub->mediumName(), "text" ) )
1152 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1154 if( !strcmp( sub->codecName(), "T140" ) )
1156 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1160 /* Try and parse a=lang: attribute */
1161 p_lang = strstr( sub->savedSDPLines(), "a=lang:" );
1163 p_lang = p_sess_lang;
1167 unsigned i_lang_len;
1169 i_lang_len = strcspn( p_lang, " \r\n" );
1170 tk->fmt.psz_language = strndup( p_lang, i_lang_len );
1173 if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
1175 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1178 if( sub->rtcpInstance() != NULL )
1180 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1183 if( tk->p_es || tk->b_quicktime || ( tk->b_muxed && tk->p_out_muxed ) ||
1184 ( tk->b_asf && p_sys->p_out_asf ) )
1186 TAB_APPEND_CAST( (live_track_t **), p_sys->i_track, p_sys->track, tk );
1191 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1192 es_format_Clean( &tk->fmt );
1198 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1200 /* Retrieve the starttime if possible */
1201 p_sys->f_npt_start = p_sys->ms->playStartTime();
1203 /* Retrieve the duration if possible */
1204 p_sys->f_npt_length = p_sys->ms->playEndTime();
1207 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1210 p_sys->b_no_data = true;
1211 p_sys->i_no_data_ti = 0;
1216 /*****************************************************************************
1217 * Play: starts the actual playback of the stream
1218 *****************************************************************************/
1219 static int Play( demux_t *p_demux )
1221 demux_sys_t *p_sys = p_demux->p_sys;
1226 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_npt_start, -1, 1 );
1228 if( !wait_Live555_response(p_demux) )
1230 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1231 return VLC_EGENERIC;
1234 /* Retrieve the timeout value and set up a timeout prevention thread */
1235 p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
1236 if( p_sys->i_timeout <= 0 )
1237 p_sys->i_timeout = 60; /* default value from RFC2326 */
1239 /* start timeout-thread. GET_PARAMETER will be used if supported by
1240 * the server. OPTIONS will be used as a fallback */
1241 if( !p_sys->p_timeout )
1243 msg_Dbg( p_demux, "We have a timeout of %d seconds", p_sys->i_timeout );
1244 p_sys->p_timeout = (timeout_thread_t *)malloc( sizeof(timeout_thread_t) );
1245 if( p_sys->p_timeout )
1247 memset( p_sys->p_timeout, 0, sizeof(timeout_thread_t) );
1248 p_sys->p_timeout->p_demux = p_demux;
1249 if( vlc_clone( &p_sys->p_timeout->handle, TimeoutPrevention,
1250 p_sys->p_timeout, VLC_THREAD_PRIORITY_LOW ) )
1252 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1253 free( p_sys->p_timeout );
1254 p_sys->p_timeout = NULL;
1257 msg_Dbg( p_demux, "spawned timeout thread" );
1260 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1265 /* Retrieve the starttime if possible */
1266 p_sys->f_npt_start = p_sys->ms->playStartTime();
1267 if( p_sys->ms->playEndTime() > 0 )
1268 p_sys->f_npt_length = p_sys->ms->playEndTime();
1270 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1275 /*****************************************************************************
1277 *****************************************************************************/
1278 static int Demux( demux_t *p_demux )
1280 demux_sys_t *p_sys = p_demux->p_sys;
1283 bool b_send_pcr = true;
1286 /* Protect Live555 from simultaneous calls in TimeoutPrevention()
1288 vlc_mutex_locker locker(&p_sys->timeout_mutex);
1290 /* Check if we need to send the server a Keep-A-Live signal */
1291 if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
1293 char *psz_bye = NULL;
1294 /* Use GET_PARAMETERS if supported. wmserver dialect supports
1295 * it, but does not report this properly. */
1296 if( p_sys->b_get_param || var_GetBool( p_demux, "rtsp-wmserver" ) )
1297 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms, NULL, psz_bye );
1299 p_sys->rtsp->sendOptionsCommand(NULL, NULL);
1301 p_sys->b_timeout_call = false;
1304 for( i = 0; i < p_sys->i_track; i++ )
1306 live_track_t *tk = p_sys->track[i];
1311 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1312 if( !b && tk->b_selected && p_sys->rtsp )
1314 tk->b_selected = false;
1315 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1317 else if( b && !tk->b_selected)
1319 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1320 var_GetBool( p_demux, "rtsp-http" );
1321 p_sys->rtsp->sendSetupCommand( *tk->sub, default_live555_callback, False,
1322 toBool( b_rtsp_tcp ),
1323 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
1324 if( !wait_Live555_response( p_demux ) )
1326 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
1327 tk->sub->mediumName(), tk->sub->codecName(),
1328 p_sys->env->getResultMsg() );
1332 p_sys->rtsp->sendPlayCommand( *tk->sub, default_live555_callback, -1, -1, p_sys->ms->scale() );
1333 if( !wait_Live555_response(p_demux) )
1335 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1336 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1339 tk->b_selected = true;
1341 if( !tk->b_selected )
1342 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1346 if( tk->b_asf || tk->b_muxed )
1349 if( p_sys->i_pcr > 0 )
1352 es_out_Control( p_demux->out, ES_OUT_SET_PCR, 1 + p_sys->i_pcr );
1355 /* First warn we want to read data */
1356 p_sys->event_data = 0;
1357 for( i = 0; i < p_sys->i_track; i++ )
1359 live_track_t *tk = p_sys->track[i];
1361 if( tk->waiting == 0 )
1364 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1365 StreamRead, tk, StreamClose, tk );
1368 /* Create a task that will be called if we wait more than 300ms */
1369 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1372 p_sys->scheduler->doEventLoop( &p_sys->event_data );
1374 /* remove the task */
1375 p_sys->scheduler->unscheduleDelayedTask( task );
1377 /* Check for gap in pts value */
1378 for( i = 0; i < p_sys->i_track; i++ )
1380 live_track_t *tk = p_sys->track[i];
1382 if( !tk->b_muxed && !tk->b_rtcp_sync &&
1383 tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1385 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1387 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1388 tk->b_rtcp_sync = true;
1390 tk->i_pts = VLC_TS_INVALID;
1397 if( p_sys->b_multicast && p_sys->b_no_data &&
1398 ( p_sys->i_no_data_ti > 120 ) )
1400 /* FIXME Make this configurable
1401 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1405 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1406 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1408 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1409 var_GetBool( p_demux, "rtsp-http" );
1411 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1413 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1414 if( RollOverTcp( p_demux ) )
1416 msg_Err( p_demux, "TCP rollover failed, aborting" );
1421 msg_Err( p_demux, "no data received in 10s, aborting" );
1424 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1425 ( p_sys->i_no_data_ti > 34 ) )
1428 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1431 return p_sys->b_error ? 0 : 1;
1434 /*****************************************************************************
1436 *****************************************************************************/
1437 static int Control( demux_t *p_demux, int i_query, va_list args )
1439 demux_sys_t *p_sys = p_demux->p_sys;
1445 vlc_mutex_locker locker(&p_sys->timeout_mutex); /* (see same in Demux) */
1449 case DEMUX_GET_TIME:
1450 pi64 = (int64_t*)va_arg( args, int64_t * );
1451 if( p_sys->f_npt > 0 )
1453 *pi64 = (int64_t)(p_sys->f_npt * 1000000.);
1456 return VLC_EGENERIC;
1458 case DEMUX_GET_LENGTH:
1459 pi64 = (int64_t*)va_arg( args, int64_t * );
1460 if( p_sys->f_npt_length > 0 )
1462 double d_length = p_sys->f_npt_length * 1000000.0;
1463 if( d_length >= INT64_MAX )
1466 *pi64 = (int64_t)d_length;
1469 return VLC_EGENERIC;
1471 case DEMUX_GET_POSITION:
1472 pf = (double*)va_arg( args, double* );
1473 if( (p_sys->f_npt_length > 0) && (p_sys->f_npt > 0) )
1475 *pf = p_sys->f_npt / p_sys->f_npt_length;
1478 return VLC_EGENERIC;
1480 case DEMUX_SET_POSITION:
1481 case DEMUX_SET_TIME:
1482 if( p_sys->rtsp && (p_sys->f_npt_length > 0) )
1487 if( (i_query == DEMUX_SET_TIME) && (p_sys->f_npt > 0) )
1489 i64 = (int64_t)va_arg( args, int64_t );
1490 time = (float)(i64 / 1000000.0); /* in second */
1492 else if( i_query == DEMUX_SET_TIME )
1493 return VLC_EGENERIC;
1496 f = (double)va_arg( args, double );
1497 time = f * p_sys->f_npt_length; /* in second */
1500 if( p_sys->b_paused )
1502 p_sys->f_seek_request = time;
1506 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1508 if( !wait_Live555_response( p_demux ) )
1510 msg_Err( p_demux, "PAUSE before seek failed %s",
1511 p_sys->env->getResultMsg() );
1512 return VLC_EGENERIC;
1515 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1517 if( !wait_Live555_response( p_demux ) )
1519 msg_Err( p_demux, "seek PLAY failed %s",
1520 p_sys->env->getResultMsg() );
1521 return VLC_EGENERIC;
1525 for( i = 0; i < p_sys->i_track; i++ )
1527 p_sys->track[i]->b_rtcp_sync = false;
1528 p_sys->track[i]->i_pts = VLC_TS_INVALID;
1531 /* Retrieve the starttime if possible */
1532 p_sys->f_npt = p_sys->f_npt_start = p_sys->ms->playStartTime();
1534 /* Retrieve the duration if possible */
1535 if( p_sys->ms->playEndTime() > 0 )
1536 p_sys->f_npt_length = p_sys->ms->playEndTime();
1538 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1541 return VLC_EGENERIC;
1543 /* Special for access_demux */
1544 case DEMUX_CAN_PAUSE:
1545 case DEMUX_CAN_SEEK:
1546 pb = (bool*)va_arg( args, bool * );
1547 if( p_sys->rtsp && p_sys->f_npt_length > 0 )
1548 /* Not always true, but will be handled in SET_PAUSE_STATE */
1554 case DEMUX_CAN_CONTROL_PACE:
1555 pb = (bool*)va_arg( args, bool * );
1557 #if 1 /* Disable for now until we have a clock synchro algo
1558 * which works with something else than MPEG over UDP */
1565 case DEMUX_CAN_CONTROL_RATE:
1566 pb = (bool*)va_arg( args, bool * );
1567 pb2 = (bool*)va_arg( args, bool * );
1569 *pb = (p_sys->rtsp != NULL) &&
1570 (p_sys->f_npt_length > 0) &&
1571 ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1572 !var_GetBool( p_demux, "rtsp-wmserver" ) );
1576 case DEMUX_SET_RATE:
1578 double f_scale, f_old_scale;
1580 if( !p_sys->rtsp || (p_sys->f_npt_length <= 0) ||
1581 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1582 var_GetBool( p_demux, "rtsp-wmserver" ) )
1583 return VLC_EGENERIC;
1585 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1588 * "[...] should try to approximate the viewing rate, but
1589 * may restrict the range of scale values that it supports.
1590 * The response MUST contain the actual scale value chosen
1593 * Scale = 1 indicates normal play
1594 * Scale > 1 indicates fast forward
1595 * Scale < 1 && Scale > 0 indicates slow motion
1596 * Scale < 0 value indicates rewind
1599 pi_int = (int*)va_arg( args, int * );
1600 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1601 f_old_scale = p_sys->ms->scale();
1603 /* Passing -1 for the start and end time will mean liveMedia won't
1604 * create a Range: section for the RTSP message. The server should
1605 * pick up from the current position */
1606 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1608 if( !wait_Live555_response( p_demux ) )
1610 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1611 p_sys->env->getResultMsg() );
1612 return VLC_EGENERIC;
1615 if( p_sys->ms->scale() == f_old_scale )
1617 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1618 p_sys->ms->scale() );
1619 return VLC_EGENERIC;
1622 /* ReSync the stream */
1623 p_sys->f_npt_start = 0;
1627 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1628 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1632 case DEMUX_SET_PAUSE_STATE:
1634 bool b_pause = (bool)va_arg( args, int );
1635 if( p_sys->rtsp == NULL )
1636 return VLC_EGENERIC;
1638 if( b_pause == p_sys->b_paused )
1641 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1643 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1644 -1.0f, p_sys->ms->scale() );
1646 if( !wait_Live555_response( p_demux ) )
1648 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1649 return VLC_EGENERIC;
1651 p_sys->f_seek_request = -1;
1652 p_sys->b_paused = b_pause;
1654 /* When we Pause, we'll need the TimeoutPrevention thread to
1655 * handle sending the "Keep Alive" message to the server.
1656 * Unfortunately Live555 isn't thread safe and so can't
1657 * do this normally while the main Demux thread is handling
1658 * a live stream. We end up with the Timeout thread blocking
1659 * waiting for a response from the server. So when we PAUSE
1660 * we set a flag that the TimeoutPrevention function will check
1661 * and if it's set, it will trigger the GET_PARAMETER message */
1662 if( p_sys->b_paused && p_sys->p_timeout != NULL )
1663 p_sys->p_timeout->b_handle_keep_alive = true;
1664 else if( !p_sys->b_paused && p_sys->p_timeout != NULL )
1665 p_sys->p_timeout->b_handle_keep_alive = false;
1667 if( !p_sys->b_paused )
1669 for( int i = 0; i < p_sys->i_track; i++ )
1671 live_track_t *tk = p_sys->track[i];
1672 tk->b_rtcp_sync = false;
1673 tk->i_pts = VLC_TS_INVALID;
1675 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1679 /* Reset data received counter */
1680 p_sys->i_no_data_ti = 0;
1682 /* Retrieve the starttime if possible */
1683 p_sys->f_npt_start = p_sys->ms->playStartTime();
1685 /* Retrieve the duration if possible */
1686 if( p_sys->ms->playEndTime() )
1687 p_sys->f_npt_length = p_sys->ms->playEndTime();
1689 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1692 case DEMUX_GET_TITLE_INFO:
1693 case DEMUX_SET_TITLE:
1694 case DEMUX_SET_SEEKPOINT:
1695 return VLC_EGENERIC;
1697 case DEMUX_GET_PTS_DELAY:
1698 pi64 = (int64_t*)va_arg( args, int64_t * );
1699 *pi64 = INT64_C(1000)
1700 * var_InheritInteger( p_demux, "network-caching" );
1704 return VLC_EGENERIC;
1708 /*****************************************************************************
1709 * RollOverTcp: reopen the rtsp into TCP mode
1710 * XXX: ugly, a lot of code are duplicated from Open()
1711 * This should REALLY be fixed
1712 *****************************************************************************/
1713 static int RollOverTcp( demux_t *p_demux )
1715 demux_sys_t *p_sys = p_demux->p_sys;
1718 var_SetBool( p_demux, "rtsp-tcp", true );
1720 /* We close the old RTSP session */
1721 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1722 Medium::close( p_sys->ms );
1723 RTSPClient::close( p_sys->rtsp );
1725 for( i = 0; i < p_sys->i_track; i++ )
1727 live_track_t *tk = p_sys->track[i];
1729 if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
1730 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1731 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1732 es_format_Clean( &tk->fmt );
1733 free( tk->p_buffer );
1736 TAB_CLEAN( p_sys->i_track, p_sys->track );
1737 if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
1741 p_sys->b_no_data = true;
1742 p_sys->i_no_data_ti = 0;
1743 p_sys->p_out_asf = NULL;
1745 /* Reopen rtsp client */
1746 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1748 msg_Err( p_demux, "Failed to connect with rtsp://%s",
1753 if( p_sys->p_sdp == NULL )
1755 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1759 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1761 msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1765 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1771 return VLC_EGENERIC;
1775 /*****************************************************************************
1777 *****************************************************************************/
1778 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1780 const uint8_t *p_data, unsigned i_size )
1782 const unsigned i_packet_size = p_demux->p_sys->asfh.i_min_data_packet_size;
1783 block_t *p_list = NULL;
1785 while( i_size >= 4 )
1787 unsigned i_flags = p_data[0];
1788 unsigned i_length_offset = (p_data[1] << 16) |
1791 bool b_length = i_flags & 0x40;
1792 bool b_relative_ts = i_flags & 0x20;
1793 bool b_duration = i_flags & 0x10;
1794 bool b_location_id = i_flags & 0x08;
1796 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1797 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1798 unsigned i_header_size = 4;
1806 if( i_header_size > i_size )
1808 msg_Warn( p_demux, "Invalid header size" );
1813 * When b_length is true, the streams I found do not seems to respect
1814 * the documentation.
1815 * From them, I have failed to find which choice between '__MIN()' or
1816 * 'i_length_offset - i_header_size' is the right one.
1820 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1822 i_payload = i_size - i_header_size;
1824 if( !tk->p_asf_block )
1826 tk->p_asf_block = block_Alloc( i_packet_size );
1827 if( !tk->p_asf_block )
1829 tk->p_asf_block->i_buffer = 0;
1831 unsigned i_offset = b_length ? 0 : i_length_offset;
1832 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1834 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1835 tk->p_asf_block->i_buffer += i_payload;
1838 /* We have a complete packet */
1839 tk->p_asf_block->i_buffer = i_packet_size;
1840 block_ChainAppend( &p_list, tk->p_asf_block );
1841 tk->p_asf_block = NULL;
1846 /* Reset on broken stream */
1847 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1848 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1849 tk->p_asf_block->i_buffer = 0;
1853 p_data += i_header_size + i_payload;
1854 i_size -= i_header_size + i_payload;
1859 /*****************************************************************************
1861 *****************************************************************************/
1862 static void StreamRead( void *p_private, unsigned int i_size,
1863 unsigned int i_truncated_bytes, struct timeval pts,
1864 unsigned int duration )
1866 VLC_UNUSED( duration );
1868 live_track_t *tk = (live_track_t*)p_private;
1869 demux_t *p_demux = tk->p_demux;
1870 demux_sys_t *p_sys = p_demux->p_sys;
1873 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1875 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1876 (int64_t)pts.tv_usec;
1878 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1879 i_pts &= INT64_C(0x00ffffffffffffff);
1881 /* Retrieve NPT for this pts */
1882 tk->f_npt = tk->sub->getNormalPlayTime(pts);
1884 if( tk->b_quicktime && tk->p_es == NULL )
1886 QuickTimeGenericRTPSource *qtRTPSource =
1887 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1888 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1889 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1891 /* Get codec information from the quicktime atoms :
1892 * http://developer.apple.com/quicktime/icefloe/dispatch026.html */
1893 if( tk->fmt.i_cat == VIDEO_ES ) {
1894 if( qtState.sdAtomSize < 16 + 32 )
1897 p_sys->event_data = 0xff;
1901 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1902 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1903 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1905 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1907 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1908 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1909 + qtRTPSource->qtState.sdAtomSize;
1910 while (pos+8 < endpos) {
1911 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1912 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1913 if( memcmp(pos+4, "avcC", 4) == 0 &&
1915 atomLength <= INT_MAX )
1917 tk->fmt.i_extra = atomLength-8;
1918 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1919 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1927 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1928 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1929 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1933 if( qtState.sdAtomSize < 24 )
1936 p_sys->event_data = 0xff;
1940 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1941 tk->fmt.audio.i_bitspersample = (sdAtom[22] << 8) | sdAtom[23];
1943 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1947 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1949 pts.tv_sec * 1000000LL + pts.tv_usec );
1952 /* grow buffer if it looks like buffer is too small, but don't eat
1953 * up all the memory on strange streams */
1954 if( i_truncated_bytes > 0 )
1956 if( tk->i_buffer < 2000000 )
1959 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1960 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1961 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1964 msg_Warn( p_demux, "realloc failed" );
1968 tk->p_buffer = (uint8_t*)p_tmp;
1973 if( tk->b_discard_trunc )
1975 p_sys->event_data = 0xff;
1981 assert( i_size <= tk->i_buffer );
1983 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1984 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1986 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1988 p_block = block_Alloc( i_size + 1 );
1989 p_block->p_buffer[0] = amrSource->lastFrameHeader();
1990 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1992 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1994 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1995 uint32_t header = h261Source->lastSpecialHeader();
1996 p_block = block_Alloc( i_size + 4 );
1997 memcpy( p_block->p_buffer, &header, 4 );
1998 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
2000 if( tk->sub->rtpSource()->curPacketMarkerBit() )
2001 p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
2003 else if( tk->fmt.i_codec == VLC_CODEC_H264 || tk->fmt.i_codec == VLC_CODEC_HEVC )
2005 if( tk->fmt.i_codec == VLC_CODEC_H264 && (tk->p_buffer[0] & 0x1f) >= 24 )
2006 msg_Warn( p_demux, "unsupported NAL type for H264" );
2007 else if( tk->fmt.i_codec == VLC_CODEC_HEVC && ((tk->p_buffer[0] & 0x7e)>>1) >= 48 )
2008 msg_Warn( p_demux, "unsupported NAL type for H265" );
2010 /* Normal NAL type */
2011 p_block = block_Alloc( i_size + 4 );
2012 p_block->p_buffer[0] = 0x00;
2013 p_block->p_buffer[1] = 0x00;
2014 p_block->p_buffer[2] = 0x00;
2015 p_block->p_buffer[3] = 0x01;
2016 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
2018 else if( tk->b_asf )
2020 p_block = StreamParseAsf( p_demux, tk,
2021 tk->sub->rtpSource()->curPacketMarkerBit(),
2022 tk->p_buffer, i_size );
2026 p_block = block_Alloc( i_size );
2027 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
2030 if( p_sys->i_pcr < i_pts )
2032 p_sys->i_pcr = i_pts;
2035 /* Update our global npt value */
2036 if( tk->f_npt > 0 &&
2037 ( tk->f_npt < p_sys->f_npt_length || p_sys->f_npt_length <= 0 ) )
2038 p_sys->f_npt = tk->f_npt;
2042 if( !tk->b_muxed && !tk->b_asf )
2044 if( i_pts != tk->i_pts )
2045 p_block->i_pts = VLC_TS_0 + i_pts;
2046 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
2047 p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? VLC_TS_INVALID : (VLC_TS_0 + i_pts);
2051 stream_DemuxSend( tk->p_out_muxed, p_block );
2052 else if( tk->b_asf )
2053 stream_DemuxSend( p_sys->p_out_asf, p_block );
2055 es_out_Send( p_demux->out, tk->p_es, p_block );
2058 /* warn that's ok */
2059 p_sys->event_data = 0xff;
2061 /* we have read data */
2063 p_demux->p_sys->b_no_data = false;
2064 p_demux->p_sys->i_no_data_ti = 0;
2066 if( i_pts > 0 && !tk->b_muxed )
2072 /*****************************************************************************
2074 *****************************************************************************/
2075 static void StreamClose( void *p_private )
2077 live_track_t *tk = (live_track_t*)p_private;
2078 demux_t *p_demux = tk->p_demux;
2079 demux_sys_t *p_sys = p_demux->p_sys;
2080 tk->b_selected = false;
2081 p_sys->event_rtsp = 0xff;
2082 p_sys->event_data = 0xff;
2085 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
2088 for( int i = 0; i < p_sys->i_track; i++ )
2090 if( p_sys->track[i]->b_selected )
2093 msg_Dbg( p_demux, "RTSP track Close, %d track remaining", nb_tracks );
2095 p_sys->b_error = true;
2099 /*****************************************************************************
2101 *****************************************************************************/
2102 static void TaskInterruptRTSP( void *p_private )
2104 demux_t *p_demux = (demux_t*)p_private;
2107 p_demux->p_sys->event_rtsp = 0xff;
2110 static void TaskInterruptData( void *p_private )
2112 demux_t *p_demux = (demux_t*)p_private;
2114 p_demux->p_sys->i_no_data_ti++;
2117 p_demux->p_sys->event_data = 0xff;
2120 /*****************************************************************************
2122 *****************************************************************************/
2124 static void* TimeoutPrevention( void *p_data )
2126 timeout_thread_t *p_timeout = (timeout_thread_t *)p_data;
2127 demux_t *p_demux = p_timeout->p_demux;
2128 demux_sys_t *p_sys = p_demux->p_sys;
2132 /* Voodoo (= no) thread safety here! *Ahem* */
2133 if( p_timeout->b_handle_keep_alive )
2135 /* Protect Live555 from us calling their functions simultaneously
2136 with Demux() or Control() */
2137 vlc_mutex_locker locker(&p_sys->timeout_mutex);
2139 char *psz_bye = NULL;
2140 int canc = vlc_savecancel ();
2142 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms, default_live555_callback, psz_bye );
2144 if( !wait_Live555_response( p_demux ) )
2146 msg_Err( p_demux, "GET_PARAMETER keepalive failed: %s",
2147 p_sys->env->getResultMsg() );
2148 /* Just continue, worst case is we get timed out later */
2151 vlc_restorecancel (canc);
2153 p_sys->b_timeout_call = !p_timeout->b_handle_keep_alive;
2155 msleep (((int64_t)p_sys->i_timeout - 2) * CLOCK_FREQ);
2157 vlc_assert_unreachable(); /* dead code */
2160 /*****************************************************************************
2162 *****************************************************************************/
2163 static int ParseASF( demux_t *p_demux )
2165 demux_sys_t *p_sys = p_demux->p_sys;
2167 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
2168 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2172 /* Parse the asf header */
2173 if( psz_asf == NULL )
2174 return VLC_EGENERIC;
2176 psz_asf += strlen( psz_marker );
2177 psz_asf = strdup( psz_asf ); /* Duplicate it */
2178 psz_end = strchr( psz_asf, '\n' );
2180 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2183 if( psz_asf >= psz_end )
2186 return VLC_EGENERIC;
2189 /* Always smaller */
2190 p_header = block_Alloc( psz_end - psz_asf );
2191 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2192 p_header->i_buffer, psz_asf );
2193 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2194 if( p_header->i_buffer <= 0 )
2197 return VLC_EGENERIC;
2200 /* Parse it to get packet size */
2201 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2203 /* Send it to demuxer */
2204 stream_DemuxSend( p_sys->p_out_asf, p_header );
2211 static unsigned char* parseH264ConfigStr( char const* configStr,
2212 unsigned int& configSize )
2215 size_t i_records = 1;
2219 if( configStr == NULL || *configStr == '\0' )
2222 psz = dup = strdup( configStr );
2224 /* Count the number of commas */
2225 for( psz = dup; *psz != '\0'; ++psz )
2234 size_t configMax = 5*strlen(dup);
2235 unsigned char *cfg = new unsigned char[configMax];
2237 for( size_t i = 0; i < i_records; ++i )
2239 cfg[configSize++] = 0x00;
2240 cfg[configSize++] = 0x00;
2241 cfg[configSize++] = 0x00;
2242 cfg[configSize++] = 0x01;
2244 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2245 configMax-configSize, psz );
2246 psz += strlen(psz)+1;
2253 static uint8_t *parseVorbisConfigStr( char const* configStr,
2254 unsigned int& configSize )
2257 if( configStr == NULL || *configStr == '\0' )
2259 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1332115200 // 2012.03.20
2260 unsigned char *p_cfg = base64Decode( configStr, configSize );
2262 char* configStr_dup = strdup( configStr );
2263 unsigned char *p_cfg = base64Decode( configStr_dup, configSize );
2264 free( configStr_dup );
2266 uint8_t *p_extra = NULL;
2267 /* skip header count, ident number and length (cf. RFC 5215) */
2268 const unsigned int headerSkip = 9;
2269 if( configSize > headerSkip && ((uint8_t*)p_cfg)[3] == 1 )
2271 configSize -= headerSkip;
2272 p_extra = (uint8_t*)xmalloc( configSize );
2273 memcpy( p_extra, p_cfg+headerSkip, configSize );