codec/hxxx_helper: removing redundant new-line from call to msg_Dbg
[vlc.git] / modules / access / live555.cpp
blobc54fe3894fbb3878e9cd5908878dacf409e34804
1 /*****************************************************************************
2 * live555.cpp : LIVE555 Streaming Media support.
3 *****************************************************************************
4 * Copyright (C) 2003-2007 VLC authors and VideoLAN
5 * $Id$
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 /*****************************************************************************
28 * Preamble
29 *****************************************************************************/
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
35 #include <inttypes.h>
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>
42 #include <vlc_url.h>
43 #include <vlc_strings.h>
44 #include <vlc_interrupt.h>
45 #include <vlc_keystore.h>
47 #include <limits.h>
48 #include <assert.h>
50 #include <new>
52 #if defined( _WIN32 )
53 # include <winsock2.h>
54 #endif
56 #include <UsageEnvironment.hh>
57 #include <BasicUsageEnvironment.hh>
58 #include <GroupsockHelper.hh>
59 #include <liveMedia.hh>
60 #include <liveMedia_version.hh>
61 #include <Base64.hh>
63 extern "C" {
64 #include "../access/mms/asf.h" /* Who said ugly ? */
67 /*****************************************************************************
68 * Module descriptor
69 *****************************************************************************/
70 static int Open ( vlc_object_t * );
71 static void Close( vlc_object_t * );
73 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
74 #define KASENNA_LONGTEXT N_( "Kasenna servers use an old and nonstandard " \
75 "dialect of RTSP. With this parameter VLC will try this dialect, but "\
76 "then it cannot connect to normal RTSP servers." )
78 #define WMSERVER_TEXT N_("WMServer RTSP dialect")
79 #define WMSERVER_LONGTEXT N_("WMServer uses a nonstandard dialect " \
80 "of RTSP. Selecting this parameter will tell VLC to assume some " \
81 "options contrary to RFC 2326 guidelines.")
83 #define USER_TEXT N_("Username")
84 #define USER_LONGTEXT N_("Sets the username for the connection, " \
85 "if no username or password are set in the url.")
86 #define PASS_TEXT N_("Password")
87 #define PASS_LONGTEXT N_("Sets the password for the connection, " \
88 "if no username or password are set in the url.")
89 #define FRAME_BUFFER_SIZE_TEXT N_("RTSP frame buffer size")
90 #define FRAME_BUFFER_SIZE_LONGTEXT N_("RTSP start frame buffer size of the video " \
91 "track, can be increased in case of broken pictures due " \
92 "to too small buffer.")
93 #define DEFAULT_FRAME_BUFFER_SIZE 100000
95 vlc_module_begin ()
96 set_description( N_("RTP/RTSP/SDP demuxer (using Live555)" ) )
97 set_capability( "demux", 50 )
98 set_shortname( "RTP/RTSP")
99 set_callbacks( Open, Close )
100 add_shortcut( "live", "livedotcom" )
101 set_category( CAT_INPUT )
102 set_subcategory( SUBCAT_INPUT_DEMUX )
104 add_submodule ()
105 set_description( N_("RTSP/RTP access and demux") )
106 add_shortcut( "rtsp", "pnm", "live", "livedotcom" )
107 set_capability( "access_demux", 0 )
108 set_callbacks( Open, Close )
109 add_bool( "rtsp-tcp", false,
110 N_("Use RTP over RTSP (TCP)"),
111 N_("Use RTP over RTSP (TCP)"), true )
112 change_safe()
113 add_integer( "rtp-client-port", -1,
114 N_("Client port"),
115 N_("Port to use for the RTP source of the session"), true )
116 add_bool( "rtsp-mcast", false,
117 N_("Force multicast RTP via RTSP"),
118 N_("Force multicast RTP via RTSP"), true )
119 change_safe()
120 add_bool( "rtsp-http", false,
121 N_("Tunnel RTSP and RTP over HTTP"),
122 N_("Tunnel RTSP and RTP over HTTP"), true )
123 change_safe()
124 add_integer( "rtsp-http-port", 80,
125 N_("HTTP tunnel port"),
126 N_("Port to use for tunneling the RTSP/RTP over HTTP."),
127 true )
128 add_bool( "rtsp-kasenna", false, KASENNA_TEXT,
129 KASENNA_LONGTEXT, true )
130 change_safe()
131 add_bool( "rtsp-wmserver", false, WMSERVER_TEXT,
132 WMSERVER_LONGTEXT, true)
133 change_safe()
134 add_string( "rtsp-user", NULL, USER_TEXT,
135 USER_LONGTEXT, true )
136 change_safe()
137 add_password( "rtsp-pwd", NULL, PASS_TEXT,
138 PASS_LONGTEXT, true )
139 add_integer( "rtsp-frame-buffer-size", DEFAULT_FRAME_BUFFER_SIZE,
140 FRAME_BUFFER_SIZE_TEXT, FRAME_BUFFER_SIZE_LONGTEXT,
141 true )
142 vlc_module_end ()
145 /*****************************************************************************
146 * Local prototypes
147 *****************************************************************************/
149 typedef struct
151 demux_t *p_demux;
152 MediaSubsession *sub;
154 es_format_t fmt;
155 es_out_id_t *p_es;
157 enum
159 SINGLE_STREAM,
160 MULTIPLEXED_STREAM,
161 QUICKTIME_STREAM,
162 ASF_STREAM
163 } format;
165 block_t *p_asf_block;
166 bool b_discard_trunc;
167 vlc_demux_chained_t *p_out_muxed; /* for muxed stream */
169 uint8_t *p_buffer;
170 unsigned int i_buffer;
172 bool b_rtcp_sync;
173 bool b_discontinuity;
174 int i_next_block_flags;
175 char waiting;
176 int64_t i_lastpts;
177 int64_t i_pcr;
178 int64_t i_offset;
179 double f_npt;
181 bool b_selected;
183 } live_track_t;
185 class RTSPClientVlc;
187 struct demux_sys_t
189 char *p_sdp; /* XXX mallocated */
190 char *psz_pl_url; /* password-less URL */
191 vlc_url_t url;
193 MediaSession *ms;
194 TaskScheduler *scheduler;
195 UsageEnvironment *env ;
196 RTSPClientVlc *rtsp;
198 /* */
199 int i_track;
200 live_track_t **track;
202 /* Weird formats */
203 asf_header_t asfh;
204 vlc_demux_chained_t *p_out_asf;
205 bool b_real;
207 /* */
208 int64_t i_pcr; /* The clock */
209 bool b_rtcp_sync; /* At least one track received sync */
210 double f_npt;
211 double f_npt_length;
212 double f_npt_start;
214 /* timeout thread information */
215 vlc_timer_t timer;
216 vlc_mutex_t timeout_mutex; /* Serialise calls to live555 in timeout thread w.r.t. Demux()/Control() */
218 /* */
219 bool b_force_mcast;
220 bool b_multicast; /* if one of the tracks is multicasted */
221 bool b_no_data; /* if we never received any data */
222 int i_no_data_ti; /* consecutive number of TaskInterrupt */
224 char event_rtsp;
225 char event_data;
227 bool b_get_param; /* Does the server support GET_PARAMETER */
228 bool b_paused; /* Are we paused? */
229 bool b_error;
230 int i_live555_ret; /* live555 callback return code */
232 float f_seek_request;/* In case we receive a seek request while paused*/
236 class RTSPClientVlc : public RTSPClient
238 public:
239 RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
240 char const* applicationName, portNumBits tunnelOverHTTPPortNum,
241 demux_sys_t *p_sys) :
242 RTSPClient( env, rtspURL, verbosityLevel, applicationName,
243 tunnelOverHTTPPortNum
244 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1373932800
245 , -1
246 #endif
249 this->p_sys = p_sys;
251 demux_sys_t *p_sys;
254 static int Demux ( demux_t * );
255 static int Control( demux_t *, int, va_list );
257 static int Connect ( demux_t * );
258 static int SessionsSetup( demux_t * );
259 static int Play ( demux_t *);
260 static int ParseASF ( demux_t * );
261 static int RollOverTcp ( demux_t * );
263 static void StreamRead ( void *, unsigned int, unsigned int,
264 struct timeval, unsigned int );
265 static void StreamClose ( void * );
266 static void TaskInterruptData( void * );
267 static void TaskInterruptRTSP( void * );
269 static void TimeoutPrevention( void * );
271 static unsigned char* parseH264ConfigStr( char const* configStr,
272 unsigned int& configSize );
273 static unsigned char* parseVorbisConfigStr( char const* configStr,
274 unsigned int& configSize );
276 static char *passwordLessURL( vlc_url_t *url );
278 /*****************************************************************************
279 * DemuxOpen:
280 *****************************************************************************/
281 static int Open ( vlc_object_t *p_this )
283 demux_t *p_demux = (demux_t*)p_this;
284 demux_sys_t *p_sys = NULL;
286 char *psz_url;
287 int i_return;
288 int i_error = VLC_EGENERIC;
290 /* if the rtsp URL may contain a sat.ip fake DNS, bail-out early and
291 * let the SAT>IP module handle that */
292 if( !strncmp(p_demux->psz_location, "sat.ip", 6) )
294 msg_Err( p_demux, "SAT>IP server, bailing out");
295 return VLC_EGENERIC;
297 /* If satip-host is set on the item, we shall assume it is a rtsp for the
298 * SAT>IP module and bail-out early. */
299 char *psz_host = var_InheritString(p_demux, "satip-host");
300 if (psz_host != NULL) {
301 msg_Err( p_demux, "URL is for SAT>IP, bailing out");
302 free(psz_host);
303 return VLC_EGENERIC;
306 if( p_demux->s )
308 /* See if it looks like a SDP
309 v, o, s fields are mandatory and in this order */
310 const uint8_t *p_peek;
311 if( vlc_stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
313 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
314 memcmp( p_peek, "v=0\n", 4 ) &&
315 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
317 return VLC_EGENERIC;
321 p_demux->pf_demux = Demux;
322 p_demux->pf_control= Control;
323 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
324 if( !p_sys ) return VLC_ENOMEM;
326 if( vlc_timer_create(&p_sys->timer, TimeoutPrevention, p_demux) )
328 free( p_sys );
329 return VLC_ENOMEM;
332 msg_Dbg( p_demux, "version " LIVEMEDIA_LIBRARY_VERSION_STRING );
334 TAB_INIT( p_sys->i_track, p_sys->track );
335 p_sys->b_no_data = true;
336 p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
337 p_sys->f_seek_request = -1;
338 vlc_mutex_init(&p_sys->timeout_mutex);
340 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
341 if( asprintf( &psz_url, "%s://%s", p_demux->psz_access, p_demux->psz_location ) == -1 )
343 i_error = VLC_ENOMEM;
344 goto error;
346 vlc_UrlParse( &p_sys->url, psz_url );
347 free( psz_url );
349 if( ( p_sys->psz_pl_url = passwordLessURL( &p_sys->url ) ) == NULL )
351 i_error = VLC_ENOMEM;
352 goto error;
355 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
357 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
358 goto error;
360 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
362 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
363 goto error;
366 if( strcasecmp( p_demux->psz_access, "sdp" ) )
368 char *p = p_sys->psz_pl_url;
369 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
372 if( p_demux->s != NULL )
374 /* Gather the complete sdp file */
375 int i_sdp = 0;
376 int i_sdp_max = 1000;
377 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
379 if( !p_sdp )
381 i_error = VLC_ENOMEM;
382 goto error;
385 for( ;; )
387 int i_read = vlc_stream_Read( p_demux->s, &p_sdp[i_sdp],
388 i_sdp_max - i_sdp - 1 );
389 if( i_read < 0 )
391 msg_Err( p_demux, "failed to read SDP" );
392 free( p_sdp );
393 goto error;
396 i_sdp += i_read;
398 if( i_read < i_sdp_max - i_sdp - 1 )
400 p_sdp[i_sdp] = '\0';
401 break;
404 i_sdp_max += 1000;
405 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
407 p_sys->p_sdp = (char*)p_sdp;
409 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
411 msg_Err( p_demux, "Failed to connect with %s", p_sys->psz_pl_url );
412 goto error;
415 if( p_sys->p_sdp == NULL )
417 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
418 i_error = VLC_ENOMEM;
419 goto error;
422 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
424 msg_Err( p_demux, "Nothing to play for %s", p_sys->psz_pl_url );
425 goto error;
428 if( p_sys->b_real ) goto error;
430 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
431 goto error;
433 if( p_sys->p_out_asf && ParseASF( p_demux ) )
435 msg_Err( p_demux, "cannot find a usable asf header" );
436 /* TODO Clean tracks */
437 goto error;
440 if( p_sys->i_track <= 0 )
441 goto error;
443 return VLC_SUCCESS;
445 error:
446 Close( p_this );
447 return i_error;
450 /*****************************************************************************
451 * DemuxClose:
452 *****************************************************************************/
453 static void Close( vlc_object_t *p_this )
455 demux_t *p_demux = (demux_t*)p_this;
456 demux_sys_t *p_sys = p_demux->p_sys;
458 vlc_timer_destroy(p_sys->timer);
460 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
461 if( p_sys->ms ) Medium::close( p_sys->ms );
462 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
463 if( p_sys->env ) p_sys->env->reclaim();
465 for( int i = 0; i < p_sys->i_track; i++ )
467 live_track_t *tk = p_sys->track[i];
469 if( tk->p_out_muxed )
470 vlc_demux_chained_Delete( tk->p_out_muxed );
471 es_format_Clean( &tk->fmt );
472 free( tk->p_buffer );
473 free( tk );
475 TAB_CLEAN( p_sys->i_track, p_sys->track );
476 if( p_sys->p_out_asf )
477 vlc_demux_chained_Delete( p_sys->p_out_asf );
478 delete p_sys->scheduler;
479 free( p_sys->p_sdp );
480 free( p_sys->psz_pl_url );
482 vlc_UrlClean( &p_sys->url );
483 vlc_mutex_destroy(&p_sys->timeout_mutex);
485 free( p_sys );
488 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
490 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
492 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
493 demux_sys_t *p_sys = client_vlc->p_sys;
494 delete []result_string;
495 p_sys->i_live555_ret = result_code;
496 p_sys->b_error = p_sys->i_live555_ret != 0;
497 p_sys->event_rtsp = 1;
500 /* return true if the RTSP command succeeded */
501 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
503 TaskToken task;
504 demux_sys_t * p_sys = p_demux->p_sys;
505 p_sys->event_rtsp = 0;
506 if( i_timeout > 0 )
508 /* Create a task that will be called if we wait more than timeout ms */
509 task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000,
510 TaskInterruptRTSP,
511 p_demux );
513 p_sys->event_rtsp = 0;
514 p_sys->b_error = true;
515 p_sys->i_live555_ret = 0;
516 p_sys->scheduler->doEventLoop( &p_sys->event_rtsp );
517 //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
518 if( i_timeout > 0 )
520 /* remove the task */
521 p_sys->scheduler->unscheduleDelayedTask( task );
523 return !p_sys->b_error;
526 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
527 char* result_string )
529 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
530 demux_sys_t *p_sys = client_vlc->p_sys;
531 p_sys->i_live555_ret = result_code;
532 if ( result_code == 0 )
534 char* sdpDescription = result_string;
535 free( p_sys->p_sdp );
536 p_sys->p_sdp = NULL;
537 if( sdpDescription )
539 p_sys->p_sdp = strdup( sdpDescription );
540 p_sys->b_error = false;
543 else
544 p_sys->b_error = true;
545 delete[] result_string;
546 p_sys->event_rtsp = 1;
549 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
550 char* result_string )
552 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
553 demux_sys_t *p_sys = client_vlc->p_sys;
554 p_sys->b_get_param =
555 // If OPTIONS fails, assume GET_PARAMETER is not supported but
556 // still continue on with the stream. Some servers (foscam)
557 // return 501/not implemented for OPTIONS.
558 result_code == 0
559 && result_string != NULL
560 && strstr( result_string, "GET_PARAMETER" ) != NULL;
561 client->sendDescribeCommand( continueAfterDESCRIBE );
562 delete[] result_string;
565 /*****************************************************************************
566 * Connect: connects to the RTSP server to setup the session DESCRIBE
567 *****************************************************************************/
568 static int Connect( demux_t *p_demux )
570 demux_sys_t *p_sys = p_demux->p_sys;
571 Authenticator authenticator;
572 vlc_credential credential;
573 const char *psz_user = NULL;
574 const char *psz_pwd = NULL;
575 int i_http_port = 0;
576 int i_ret = VLC_SUCCESS;
577 const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
579 vlc_credential_init( &credential, &p_sys->url );
581 /* Credentials can be NULL since they may not be needed */
582 if( vlc_credential_get( &credential, p_demux, "rtsp-user", "rtsp-pwd",
583 NULL, NULL) )
585 psz_user = credential.psz_username;
586 psz_pwd = credential.psz_password;
589 createnew:
590 /* FIXME: This is naive and incorrect; it does not prevent the thread
591 * getting stuck in blocking socket operations. */
592 if( vlc_killed() )
594 i_ret = VLC_EGENERIC;
595 goto bailout;
598 if( var_CreateGetBool( p_demux, "rtsp-http" ) )
599 i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
601 p_sys->rtsp = new (std::nothrow) RTSPClientVlc( *p_sys->env, p_sys->psz_pl_url,
602 var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
603 "LibVLC/" VERSION, i_http_port, p_sys );
604 if( !p_sys->rtsp )
606 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
607 p_sys->env->getResultMsg() );
608 i_ret = VLC_EGENERIC;
609 goto bailout;
612 /* Kasenna enables KeepAlive by analysing the User-Agent string.
613 * Appending _KA to the string should be enough to enable this feature,
614 * however, there is a bug where the _KA doesn't get parsed from the
615 * default User-Agent as created by VLC/Live555 code. This is probably due
616 * to spaces in the string or the string being too long. Here we override
617 * the default string with a more compact version.
619 if( var_InheritBool( p_demux, "rtsp-kasenna" ))
621 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
624 describe:
625 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
627 p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
629 if( !wait_Live555_response( p_demux, i_timeout ) )
631 int i_code = p_sys->i_live555_ret;
632 if( i_code == 401 )
634 msg_Dbg( p_demux, "authentication failed" );
636 if( vlc_credential_get( &credential, p_demux, "rtsp-user", "rtsp-pwd",
637 _("RTSP authentication"),
638 _("Please enter a valid login name and a password.") ) )
640 psz_user = credential.psz_username;
641 psz_pwd = credential.psz_password;
642 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
643 goto describe;
646 else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
648 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
649 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
650 var_SetBool( p_demux, "rtsp-http", true );
651 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
652 p_sys->rtsp = NULL;
653 goto createnew;
655 else
657 if( i_code == 0 )
658 msg_Dbg( p_demux, "connection timeout" );
659 else
661 msg_Dbg( p_demux, "connection error %d", i_code );
662 if( i_code == 403 )
663 vlc_dialog_display_error( p_demux, _("RTSP connection failed"),
664 _("Access to the stream is denied by the server configuration.") );
666 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
667 p_sys->rtsp = NULL;
669 i_ret = VLC_EGENERIC;
671 else
672 vlc_credential_store( &credential, p_demux );
674 bailout:
675 vlc_credential_clean( &credential );
677 return i_ret;
680 /*****************************************************************************
681 * SessionsSetup: prepares the subsessions and does the SETUP
682 *****************************************************************************/
683 static int SessionsSetup( demux_t *p_demux )
685 demux_sys_t *p_sys = p_demux->p_sys;
686 MediaSubsessionIterator *iter = NULL;
687 MediaSubsession *sub = NULL;
689 bool b_rtsp_tcp;
690 int i_client_port;
691 int i_return = VLC_SUCCESS;
692 unsigned int i_receive_buffer = 0;
693 int i_frame_buffer = DEFAULT_FRAME_BUFFER_SIZE;
694 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
695 const char *p_sess_lang = NULL;
696 const char *p_lang;
698 b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
699 var_GetBool( p_demux, "rtsp-http" );
700 i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
703 /* Create the session from the SDP */
704 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
706 msg_Err( p_demux, "Could not create the RTSP Session: %s",
707 p_sys->env->getResultMsg() );
708 return VLC_EGENERIC;
711 if( strcmp( p_sys->p_sdp, "m=" ) != 0 )
713 const char *p_sess_attr_end;
715 p_sess_attr_end = strstr( p_sys->p_sdp, "\nm=" );
716 if( !p_sess_attr_end )
717 p_sess_attr_end = strstr( p_sys->p_sdp, "\rm=" );
719 p_sess_lang = p_sess_attr_end ? strstr( p_sys->p_sdp, "a=lang:" ) : NULL;
720 if( p_sess_lang &&
721 p_sess_lang - p_sys->p_sdp > p_sess_attr_end - p_sys->p_sdp )
722 p_sess_lang = NULL;
725 /* Initialise each media subsession */
726 iter = new MediaSubsessionIterator( *p_sys->ms );
727 while( ( sub = iter->next() ) != NULL )
729 Boolean bInit;
730 live_track_t *tk;
732 /* Value taken from mplayer */
733 if( !strcmp( sub->mediumName(), "audio" ) )
734 i_receive_buffer = 100000;
735 else if( !strcmp( sub->mediumName(), "video" ) )
737 int i_var_buf_size = var_InheritInteger( p_demux, "rtsp-frame-buffer-size" );
738 if( i_var_buf_size > 0 )
739 i_frame_buffer = i_var_buf_size;
740 i_receive_buffer = 2000000;
742 else if( !strcmp( sub->mediumName(), "text" ) )
744 else continue;
746 if( strcasestr( sub->codecName(), "REAL" ) )
748 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
749 p_sys->b_real = true; /* This is a problem, we'll handle it later */
750 continue;
753 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
754 bInit = sub->initiate( 0 );
755 else
756 bInit = sub->initiate();
758 if( !bInit )
760 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
761 sub->mediumName(), sub->codecName(),
762 p_sys->env->getResultMsg() );
764 else
766 if( sub->rtpSource() != NULL )
768 int fd = sub->rtpSource()->RTPgs()->socketNum();
770 /* Increase the buffer size */
771 if( i_receive_buffer > 0 )
772 increaseReceiveBufferTo( *p_sys->env, fd, i_receive_buffer );
774 /* Increase the RTP reorder timebuffer just a bit */
775 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
777 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
778 sub->codecName() );
780 /* Issue the SETUP */
781 if( p_sys->rtsp )
784 if( i_client_port != -1 )
786 sub->setClientPortNum( i_client_port );
787 i_client_port += 2;
790 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
791 toBool( b_rtsp_tcp ),
792 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
793 if( !wait_Live555_response( p_demux ) )
795 /* if we get an unsupported transport error, toggle TCP
796 * use and try again */
797 if( p_sys->i_live555_ret == 461 )
798 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
799 !toBool( b_rtsp_tcp ), False );
800 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
802 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
803 sub->mediumName(), sub->codecName(),
804 p_sys->env->getResultMsg() );
805 continue;
807 else
809 var_SetBool( p_demux, "rtsp-tcp", true );
810 b_rtsp_tcp = true;
815 /* Check if we will receive data from this subsession for
816 * this track */
817 if( sub->readSource() == NULL ) continue;
818 if( !p_sys->b_multicast )
820 /* We need different rollover behaviour for multicast */
821 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
824 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
825 if( !tk )
827 delete iter;
828 return VLC_ENOMEM;
830 tk->p_demux = p_demux;
831 tk->sub = sub;
832 tk->p_es = NULL;
833 tk->format = live_track_t::SINGLE_STREAM;
834 tk->p_asf_block = NULL;
835 tk->b_discard_trunc = false;
836 tk->p_out_muxed = NULL;
837 tk->waiting = 0;
838 tk->b_rtcp_sync = false;
839 tk->b_discontinuity = false;
840 tk->i_next_block_flags = 0;
841 tk->i_lastpts = VLC_TS_INVALID;
842 tk->i_pcr = VLC_TS_INVALID;
843 tk->f_npt = 0.;
844 tk->b_selected = true;
845 tk->i_buffer = i_frame_buffer;
846 tk->p_buffer = (uint8_t *)malloc( i_frame_buffer );
848 if( !tk->p_buffer )
850 free( tk );
851 delete iter;
852 return VLC_ENOMEM;
855 /* Value taken from mplayer */
856 if( !strcmp( sub->mediumName(), "audio" ) )
858 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
859 tk->fmt.audio.i_channels = sub->numChannels();
860 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
862 if( !strcmp( sub->codecName(), "MPA" ) ||
863 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
864 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
866 tk->fmt.i_codec = VLC_CODEC_MPGA;
867 tk->fmt.audio.i_rate = 0;
869 else if( !strcmp( sub->codecName(), "AC3" ) )
871 tk->fmt.i_codec = VLC_CODEC_A52;
872 tk->fmt.audio.i_rate = 0;
874 else if( !strcmp( sub->codecName(), "L16" ) )
876 tk->fmt.i_codec = VLC_CODEC_S16B;
877 tk->fmt.audio.i_bitspersample = 16;
879 else if( !strcmp( sub->codecName(), "L20" ) )
881 tk->fmt.i_codec = VLC_CODEC_S20B;
882 tk->fmt.audio.i_bitspersample = 20;
884 else if( !strcmp( sub->codecName(), "L24" ) )
886 tk->fmt.i_codec = VLC_CODEC_S24B;
887 tk->fmt.audio.i_bitspersample = 24;
889 else if( !strcmp( sub->codecName(), "L8" ) )
891 tk->fmt.i_codec = VLC_CODEC_U8;
892 tk->fmt.audio.i_bitspersample = 8;
894 else if( !strcmp( sub->codecName(), "DAT12" ) )
896 tk->fmt.i_codec = VLC_CODEC_DAT12;
897 tk->fmt.audio.i_bitspersample = 12;
899 else if( !strcmp( sub->codecName(), "PCMU" ) )
901 tk->fmt.i_codec = VLC_CODEC_MULAW;
902 tk->fmt.audio.i_bitspersample = 8;
904 else if( !strcmp( sub->codecName(), "PCMA" ) )
906 tk->fmt.i_codec = VLC_CODEC_ALAW;
907 tk->fmt.audio.i_bitspersample = 8;
909 else if( !strncmp( sub->codecName(), "G726", 4 ) )
911 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
912 tk->fmt.audio.i_rate = 8000;
913 tk->fmt.audio.i_channels = 1;
914 if( !strcmp( sub->codecName()+5, "40" ) )
915 tk->fmt.i_bitrate = 40000;
916 else if( !strcmp( sub->codecName()+5, "32" ) )
917 tk->fmt.i_bitrate = 32000;
918 else if( !strcmp( sub->codecName()+5, "24" ) )
919 tk->fmt.i_bitrate = 24000;
920 else if( !strcmp( sub->codecName()+5, "16" ) )
921 tk->fmt.i_bitrate = 16000;
923 else if( !strcmp( sub->codecName(), "AMR" ) )
925 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
927 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
929 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
931 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
933 unsigned int i_extra;
934 uint8_t *p_extra;
936 tk->fmt.i_codec = VLC_CODEC_MP4A;
938 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
939 i_extra ) ) )
941 tk->fmt.i_extra = i_extra;
942 tk->fmt.p_extra = xmalloc( i_extra );
943 memcpy( tk->fmt.p_extra, p_extra, i_extra );
944 delete[] p_extra;
946 /* Because the "faad" decoder does not handle the LATM
947 * data length field at the start of each returned LATM
948 * frame, tell the RTP source to omit. */
949 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
951 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
953 unsigned int i_extra;
954 uint8_t *p_extra;
956 tk->fmt.i_codec = VLC_CODEC_MP4A;
958 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
959 i_extra ) ) )
961 tk->fmt.i_extra = i_extra;
962 tk->fmt.p_extra = xmalloc( i_extra );
963 memcpy( tk->fmt.p_extra, p_extra, i_extra );
964 delete[] p_extra;
967 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
969 tk->format = live_track_t::ASF_STREAM;
970 if( p_sys->p_out_asf == NULL )
971 p_sys->p_out_asf =
972 vlc_demux_chained_New( VLC_OBJECT(p_demux), "asf",
973 p_demux->out );
975 else if( !strcmp( sub->codecName(), "X-QT" ) ||
976 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
978 tk->format = live_track_t::QUICKTIME_STREAM;
980 else if( !strcmp( sub->codecName(), "SPEEX" ) )
982 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
984 else if( !strcmp( sub->codecName(), "VORBIS" ) )
986 tk->fmt.i_codec = VLC_CODEC_VORBIS;
987 unsigned int i_extra;
988 unsigned char *p_extra;
989 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
990 i_extra ) ) )
992 tk->fmt.i_extra = i_extra;
993 tk->fmt.p_extra = p_extra;
995 else
996 msg_Warn( p_demux,"Missing or unsupported vorbis header." );
998 else if( !strcmp( sub->codecName(), "OPUS" ) )
1000 tk->fmt.i_codec = VLC_CODEC_OPUS;
1003 else if( !strcmp( sub->mediumName(), "video" ) )
1005 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
1006 if( !strcmp( sub->codecName(), "MPV" ) )
1008 tk->fmt.i_codec = VLC_CODEC_MPGV;
1009 tk->fmt.b_packetized = false;
1011 else if( !strcmp( sub->codecName(), "H263" ) ||
1012 !strcmp( sub->codecName(), "H263-1998" ) ||
1013 !strcmp( sub->codecName(), "H263-2000" ) )
1015 tk->fmt.i_codec = VLC_CODEC_H263;
1017 else if( !strcmp( sub->codecName(), "H261" ) )
1019 tk->fmt.i_codec = VLC_CODEC_H261;
1021 else if( !strcmp( sub->codecName(), "H264" ) )
1023 unsigned int i_extra = 0;
1024 uint8_t *p_extra = NULL;
1026 tk->fmt.i_codec = VLC_CODEC_H264;
1027 tk->fmt.b_packetized = false;
1029 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
1030 i_extra ) ) )
1032 tk->fmt.i_extra = i_extra;
1033 tk->fmt.p_extra = xmalloc( i_extra );
1034 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1036 delete[] p_extra;
1039 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1393372800 // 2014.02.26
1040 else if( !strcmp( sub->codecName(), "H265" ) )
1042 unsigned int i_extra1 = 0, i_extra2 = 0, i_extra3 = 0, i_extraTot;
1043 uint8_t *p_extra1 = NULL, *p_extra2 = NULL, *p_extra3 = NULL;
1045 tk->fmt.i_codec = VLC_CODEC_HEVC;
1046 tk->fmt.b_packetized = false;
1048 p_extra1 = parseH264ConfigStr( sub->fmtp_spropvps(), i_extra1 );
1049 p_extra2 = parseH264ConfigStr( sub->fmtp_spropsps(), i_extra2 );
1050 p_extra3 = parseH264ConfigStr( sub->fmtp_sproppps(), i_extra3 );
1051 i_extraTot = i_extra1 + i_extra2 + i_extra3;
1052 if( i_extraTot > 0 )
1054 tk->fmt.i_extra = i_extraTot;
1055 tk->fmt.p_extra = xmalloc( i_extraTot );
1056 if( p_extra1 )
1058 memcpy( tk->fmt.p_extra, p_extra1, i_extra1 );
1060 if( p_extra2 )
1062 memcpy( ((char*)tk->fmt.p_extra)+i_extra1, p_extra2, i_extra2 );
1064 if( p_extra3 )
1066 memcpy( ((char*)tk->fmt.p_extra)+i_extra1+i_extra2, p_extra3, i_extra3 );
1069 delete[] p_extra1; delete[] p_extra2; delete[] p_extra3;
1072 #endif
1073 else if( !strcmp( sub->codecName(), "JPEG" ) )
1075 tk->fmt.i_codec = VLC_CODEC_MJPG;
1077 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1079 unsigned int i_extra;
1080 uint8_t *p_extra;
1082 tk->fmt.i_codec = VLC_CODEC_MP4V;
1084 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1085 i_extra ) ) )
1087 tk->fmt.i_extra = i_extra;
1088 tk->fmt.p_extra = xmalloc( i_extra );
1089 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1090 delete[] p_extra;
1093 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1094 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1095 !strcmp( sub->codecName(), "X-QDM" ) ||
1096 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1097 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1099 tk->format = live_track_t::QUICKTIME_STREAM;
1101 else if( !strcmp( sub->codecName(), "MP2T" ) )
1103 tk->format = live_track_t::MULTIPLEXED_STREAM;
1104 tk->p_out_muxed =
1105 vlc_demux_chained_New( VLC_OBJECT(p_demux), "ts",
1106 p_demux->out );
1108 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1109 !strcmp( sub->codecName(), "MP1S" ) )
1111 tk->format = live_track_t::MULTIPLEXED_STREAM;
1112 tk->p_out_muxed =
1113 vlc_demux_chained_New( VLC_OBJECT(p_demux), "ps",
1114 p_demux->out );
1116 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1118 tk->format = live_track_t::ASF_STREAM;
1119 if( p_sys->p_out_asf == NULL )
1120 p_sys->p_out_asf =
1121 vlc_demux_chained_New( VLC_OBJECT(p_demux),
1122 "asf", p_demux->out );
1124 else if( !strcmp( sub->codecName(), "DV" ) )
1126 tk->format = live_track_t::MULTIPLEXED_STREAM;
1127 tk->b_discard_trunc = true;
1128 tk->p_out_muxed =
1129 vlc_demux_chained_New( VLC_OBJECT(p_demux), "rawdv",
1130 p_demux->out );
1132 else if( !strcmp( sub->codecName(), "VP8" ) )
1134 tk->fmt.i_codec = VLC_CODEC_VP8;
1136 else if( !strcmp( sub->codecName(), "THEORA" ) )
1138 tk->fmt.i_codec = VLC_CODEC_THEORA;
1139 unsigned int i_extra;
1140 unsigned char *p_extra;
1141 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
1142 i_extra ) ) )
1144 tk->fmt.i_extra = i_extra;
1145 tk->fmt.p_extra = p_extra;
1147 else
1148 msg_Warn( p_demux,"Missing or unsupported theora header." );
1151 else if( !strcmp( sub->mediumName(), "text" ) )
1153 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1155 if( !strcmp( sub->codecName(), "T140" ) )
1157 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1161 /* Try and parse a=lang: attribute */
1162 p_lang = strstr( sub->savedSDPLines(), "a=lang:" );
1163 if( !p_lang )
1164 p_lang = p_sess_lang;
1166 if( p_lang )
1168 unsigned i_lang_len;
1169 p_lang += 7;
1170 i_lang_len = strcspn( p_lang, " \r\n" );
1171 tk->fmt.psz_language = strndup( p_lang, i_lang_len );
1174 if( tk->format == live_track_t::SINGLE_STREAM )
1176 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1179 if( sub->rtcpInstance() != NULL )
1181 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1184 if( tk->p_es ||
1185 tk->format == live_track_t::QUICKTIME_STREAM ||
1186 (tk->format == live_track_t::MULTIPLEXED_STREAM && tk->p_out_muxed ) ||
1187 (tk->format == live_track_t::ASF_STREAM && p_sys->p_out_asf ) )
1189 TAB_APPEND_CAST( (live_track_t **), p_sys->i_track, p_sys->track, tk );
1191 else
1193 /* BUG ??? */
1194 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1195 es_format_Clean( &tk->fmt );
1196 free( tk );
1200 delete iter;
1201 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1203 /* Retrieve the starttime if possible */
1204 p_sys->f_npt_start = p_sys->ms->playStartTime();
1206 /* Retrieve the duration if possible */
1207 p_sys->f_npt_length = p_sys->ms->playEndTime();
1209 /* */
1210 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1212 /* */
1213 p_sys->b_no_data = true;
1214 p_sys->i_no_data_ti = 0;
1215 p_sys->b_rtcp_sync = false;
1216 p_sys->i_pcr = VLC_TS_INVALID;
1218 return i_return;
1221 /*****************************************************************************
1222 * Play: starts the actual playback of the stream
1223 *****************************************************************************/
1224 static int Play( demux_t *p_demux )
1226 demux_sys_t *p_sys = p_demux->p_sys;
1228 if( p_sys->rtsp )
1230 /* The PLAY */
1231 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_npt_start, -1, 1 );
1233 if( !wait_Live555_response(p_demux) )
1235 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1236 return VLC_EGENERIC;
1239 /* Retrieve the timeout value and set up a timeout prevention thread */
1240 int timeout = p_sys->rtsp->sessionTimeoutParameter();
1241 if( timeout <= 2 )
1242 timeout = 60; /* default value from RFC2326 */
1243 msg_Dbg( p_demux, "We have a timeout of %d seconds", timeout );
1245 mtime_t interval = (timeout - 2) * CLOCK_FREQ;
1246 vlc_timer_schedule( p_sys->timer, false, interval, interval);
1248 p_sys->i_pcr = VLC_TS_INVALID;
1250 /* Retrieve the starttime if possible */
1251 p_sys->f_npt_start = p_sys->ms->playStartTime();
1252 if( p_sys->ms->playEndTime() > 0 )
1253 p_sys->f_npt_length = p_sys->ms->playEndTime();
1255 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1256 return VLC_SUCCESS;
1260 /*****************************************************************************
1261 * Demux:
1262 *****************************************************************************/
1263 static int Demux( demux_t *p_demux )
1265 demux_sys_t *p_sys = p_demux->p_sys;
1266 TaskToken task;
1268 bool b_send_pcr = true;
1269 int i;
1271 /* Protect Live555 from simultaneous calls in TimeoutPrevention()
1272 during pause */
1273 vlc_mutex_locker locker(&p_sys->timeout_mutex);
1275 for( i = 0; i < p_sys->i_track; i++ )
1277 live_track_t *tk = p_sys->track[i];
1279 if( tk->p_es )
1281 bool b;
1282 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1283 if( !b && tk->b_selected && p_sys->rtsp )
1285 tk->b_selected = false;
1286 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1288 else if( b && !tk->b_selected)
1290 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1291 var_GetBool( p_demux, "rtsp-http" );
1292 p_sys->rtsp->sendSetupCommand( *tk->sub, default_live555_callback, False,
1293 toBool( b_rtsp_tcp ),
1294 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
1295 if( !wait_Live555_response( p_demux ) )
1297 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
1298 tk->sub->mediumName(), tk->sub->codecName(),
1299 p_sys->env->getResultMsg() );
1301 else
1303 p_sys->rtsp->sendPlayCommand( *tk->sub, default_live555_callback, -1, -1, p_sys->ms->scale() );
1304 if( !wait_Live555_response(p_demux) )
1306 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1307 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1309 else
1310 tk->b_selected = true;
1312 if( !tk->b_selected )
1313 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1317 if( tk->format == live_track_t::ASF_STREAM ||
1318 tk->format == live_track_t::MULTIPLEXED_STREAM )
1320 b_send_pcr = false;
1324 /* First warn we want to read data */
1325 p_sys->event_data = 0;
1326 for( i = 0; i < p_sys->i_track; i++ )
1328 live_track_t *tk = p_sys->track[i];
1330 if( tk->waiting == 0 )
1332 tk->waiting = 1;
1333 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1334 StreamRead, tk, StreamClose, tk );
1337 /* Create a task that will be called if we wait more than 300ms */
1338 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1340 /* Do the read */
1341 p_sys->scheduler->doEventLoop( &p_sys->event_data );
1343 /* remove the task */
1344 p_sys->scheduler->unscheduleDelayedTask( task );
1346 if( b_send_pcr )
1348 mtime_t i_minpcr = VLC_TS_INVALID;
1349 bool b_discontinuity = false;
1351 /* Check for gap in pts value */
1352 for( i = 0; i < p_sys->i_track; i++ )
1354 live_track_t *tk = p_sys->track[i];
1356 if( !tk->b_selected ||
1357 (p_sys->b_rtcp_sync && !tk->b_rtcp_sync) )
1358 continue;
1360 /* Check for gap in pts value */
1361 b_discontinuity |= (tk->b_discontinuity);
1363 if( i_minpcr == VLC_TS_INVALID || i_minpcr > tk->i_pcr )
1364 i_minpcr = tk->i_pcr;
1367 if( p_sys->i_pcr > VLC_TS_INVALID && b_discontinuity )
1369 es_out_Control( p_demux->out, ES_OUT_MODIFY_PCR_SYSTEM, true, VLC_TS_0 + i_minpcr );
1370 p_sys->i_pcr = i_minpcr;
1371 p_sys->f_npt = 0.;
1373 for( i = 0; i < p_sys->i_track; i++ )
1375 live_track_t *tk = p_sys->track[i];
1376 tk->i_lastpts = VLC_TS_INVALID;
1377 tk->i_offset = 0;
1378 tk->i_pcr = VLC_TS_INVALID;
1379 tk->f_npt = 0.;
1380 tk->b_discontinuity = false;
1381 tk->i_next_block_flags = BLOCK_FLAG_DISCONTINUITY;
1383 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
1385 else if( p_sys->i_pcr == VLC_TS_INVALID ||
1386 i_minpcr > p_sys->i_pcr + CLOCK_FREQ / 4 )
1388 p_sys->i_pcr = i_minpcr;
1389 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
1393 if( p_sys->b_multicast && p_sys->b_no_data &&
1394 ( p_sys->i_no_data_ti > 120 ) )
1396 /* FIXME Make this configurable
1397 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1398 return 0;
1401 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1402 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1404 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1405 var_GetBool( p_demux, "rtsp-http" );
1407 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1409 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1410 if( RollOverTcp( p_demux ) )
1412 msg_Err( p_demux, "TCP rollover failed, aborting" );
1413 return 0;
1415 return 1;
1417 msg_Err( p_demux, "no data received in 10s, aborting" );
1418 return 0;
1420 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1421 ( p_sys->i_no_data_ti > 34 ) )
1423 /* EOF ? */
1424 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1425 return 0;
1427 return p_sys->b_error ? 0 : 1;
1430 /*****************************************************************************
1431 * Control:
1432 *****************************************************************************/
1433 static int Control( demux_t *p_demux, int i_query, va_list args )
1435 demux_sys_t *p_sys = p_demux->p_sys;
1436 int64_t *pi64, i64;
1437 double *pf, f;
1438 bool *pb;
1440 vlc_mutex_locker locker(&p_sys->timeout_mutex); /* (see same in Demux) */
1442 switch( i_query )
1444 case DEMUX_GET_TIME:
1445 pi64 = va_arg( args, int64_t * );
1446 if( p_sys->f_npt > 0 )
1448 *pi64 = (int64_t)(p_sys->f_npt * 1000000.);
1449 return VLC_SUCCESS;
1451 return VLC_EGENERIC;
1453 case DEMUX_GET_LENGTH:
1454 pi64 = va_arg( args, int64_t * );
1455 if( p_sys->f_npt_length > 0 )
1457 double d_length = p_sys->f_npt_length * 1000000.0;
1458 if( d_length >= INT64_MAX )
1459 *pi64 = INT64_MAX;
1460 else
1461 *pi64 = (int64_t)d_length;
1462 return VLC_SUCCESS;
1464 return VLC_EGENERIC;
1466 case DEMUX_GET_POSITION:
1467 pf = va_arg( args, double * );
1468 if( (p_sys->f_npt_length > 0) && (p_sys->f_npt > 0) )
1470 *pf = p_sys->f_npt / p_sys->f_npt_length;
1471 return VLC_SUCCESS;
1473 return VLC_EGENERIC;
1475 case DEMUX_SET_POSITION:
1476 case DEMUX_SET_TIME:
1477 if( p_sys->rtsp && (p_sys->f_npt_length > 0) )
1479 float time;
1481 if( (i_query == DEMUX_SET_TIME) && (p_sys->f_npt > 0) )
1483 i64 = va_arg( args, int64_t );
1484 time = (float)(i64 / 1000000.0); /* in second */
1486 else if( i_query == DEMUX_SET_TIME )
1487 return VLC_EGENERIC;
1488 else
1490 f = va_arg( args, double );
1491 time = f * p_sys->f_npt_length; /* in second */
1494 if( p_sys->b_paused )
1496 p_sys->f_seek_request = time;
1497 return VLC_SUCCESS;
1500 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1502 if( !wait_Live555_response( p_demux ) )
1504 msg_Err( p_demux, "PAUSE before seek failed %s",
1505 p_sys->env->getResultMsg() );
1506 return VLC_EGENERIC;
1509 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1511 if( !wait_Live555_response( p_demux ) )
1513 msg_Err( p_demux, "seek PLAY failed %s",
1514 p_sys->env->getResultMsg() );
1515 return VLC_EGENERIC;
1517 p_sys->i_pcr = VLC_TS_INVALID;
1519 for( int i = 0; i < p_sys->i_track; i++ )
1521 p_sys->track[i]->b_rtcp_sync = false;
1522 p_sys->track[i]->i_lastpts = VLC_TS_INVALID;
1523 p_sys->track[i]->i_pcr = VLC_TS_INVALID;
1526 /* Retrieve the starttime if possible */
1527 p_sys->f_npt = p_sys->f_npt_start = p_sys->ms->playStartTime();
1529 /* Retrieve the duration if possible */
1530 if( p_sys->ms->playEndTime() > 0 )
1531 p_sys->f_npt_length = p_sys->ms->playEndTime();
1533 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1534 return VLC_SUCCESS;
1536 return VLC_EGENERIC;
1538 /* Special for access_demux */
1539 case DEMUX_CAN_PAUSE:
1540 case DEMUX_CAN_SEEK:
1541 pb = va_arg( args, bool * );
1542 if( p_sys->rtsp && p_sys->f_npt_length > 0 )
1543 /* Not always true, but will be handled in SET_PAUSE_STATE */
1544 *pb = true;
1545 else
1546 *pb = false;
1547 return VLC_SUCCESS;
1549 case DEMUX_CAN_CONTROL_PACE:
1550 pb = va_arg( args, bool * );
1552 #if 1 /* Disable for now until we have a clock synchro algo
1553 * which works with something else than MPEG over UDP */
1554 *pb = false;
1555 #else
1556 *pb = true;
1557 #endif
1558 return VLC_SUCCESS;
1560 case DEMUX_CAN_CONTROL_RATE:
1561 pb = va_arg( args, bool * );
1563 *pb = (p_sys->rtsp != NULL) &&
1564 (p_sys->f_npt_length > 0) &&
1565 ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1566 !var_GetBool( p_demux, "rtsp-wmserver" ) );
1567 return VLC_SUCCESS;
1569 case DEMUX_SET_RATE:
1571 int *pi_int;
1572 double f_scale, f_old_scale;
1574 if( !p_sys->rtsp || (p_sys->f_npt_length <= 0) ||
1575 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1576 var_GetBool( p_demux, "rtsp-wmserver" ) )
1577 return VLC_EGENERIC;
1579 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1580 * supports Scale:
1582 * "[...] should try to approximate the viewing rate, but
1583 * may restrict the range of scale values that it supports.
1584 * The response MUST contain the actual scale value chosen
1585 * by the server."
1587 * Scale = 1 indicates normal play
1588 * Scale > 1 indicates fast forward
1589 * Scale < 1 && Scale > 0 indicates slow motion
1590 * Scale < 0 value indicates rewind
1593 pi_int = va_arg( args, int * );
1594 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1595 f_old_scale = p_sys->ms->scale();
1597 /* Passing -1 for the start and end time will mean liveMedia won't
1598 * create a Range: section for the RTSP message. The server should
1599 * pick up from the current position */
1600 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1602 if( !wait_Live555_response( p_demux ) )
1604 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1605 p_sys->env->getResultMsg() );
1606 return VLC_EGENERIC;
1609 if( p_sys->ms->scale() == f_old_scale )
1611 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1612 p_sys->ms->scale() );
1613 return VLC_EGENERIC;
1616 /* ReSync the stream */
1617 p_sys->f_npt_start = 0;
1618 p_sys->i_pcr = VLC_TS_INVALID;
1619 p_sys->f_npt = 0.0;
1621 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1622 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1623 return VLC_SUCCESS;
1626 case DEMUX_SET_PAUSE_STATE:
1628 bool b_pause = (bool)va_arg( args, int );
1629 if( p_sys->rtsp == NULL )
1630 return VLC_EGENERIC;
1632 if( b_pause == p_sys->b_paused )
1633 return VLC_SUCCESS;
1634 if( b_pause )
1635 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1636 else
1637 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1638 -1.0f, p_sys->ms->scale() );
1640 if( !wait_Live555_response( p_demux ) )
1642 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1643 return VLC_EGENERIC;
1645 p_sys->f_seek_request = -1;
1646 p_sys->b_paused = b_pause;
1648 if( !p_sys->b_paused )
1650 for( int i = 0; i < p_sys->i_track; i++ )
1652 live_track_t *tk = p_sys->track[i];
1653 tk->b_rtcp_sync = false;
1654 tk->b_discontinuity = false;
1655 tk->i_lastpts = VLC_TS_INVALID;
1656 tk->i_pcr = VLC_TS_INVALID;
1658 p_sys->i_pcr = VLC_TS_INVALID;
1659 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1662 /* Reset data received counter */
1663 p_sys->i_no_data_ti = 0;
1665 /* Retrieve the starttime if possible */
1666 p_sys->f_npt_start = p_sys->ms->playStartTime();
1668 /* Retrieve the duration if possible */
1669 if( p_sys->ms->playEndTime() )
1670 p_sys->f_npt_length = p_sys->ms->playEndTime();
1672 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1674 return VLC_SUCCESS;
1676 case DEMUX_GET_TITLE_INFO:
1677 case DEMUX_SET_TITLE:
1678 case DEMUX_SET_SEEKPOINT:
1679 return VLC_EGENERIC;
1681 case DEMUX_GET_PTS_DELAY:
1682 pi64 = va_arg( args, int64_t * );
1683 *pi64 = INT64_C(1000)
1684 * var_InheritInteger( p_demux, "network-caching" );
1685 return VLC_SUCCESS;
1687 default:
1688 return VLC_EGENERIC;
1692 /*****************************************************************************
1693 * RollOverTcp: reopen the rtsp into TCP mode
1694 * XXX: ugly, a lot of code are duplicated from Open()
1695 * This should REALLY be fixed
1696 *****************************************************************************/
1697 static int RollOverTcp( demux_t *p_demux )
1699 demux_sys_t *p_sys = p_demux->p_sys;
1700 int i, i_return;
1702 var_SetBool( p_demux, "rtsp-tcp", true );
1704 /* We close the old RTSP session */
1705 vlc_timer_schedule(p_sys->timer, false, 0, 0);
1706 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1707 Medium::close( p_sys->ms );
1708 RTSPClient::close( p_sys->rtsp );
1710 for( i = 0; i < p_sys->i_track; i++ )
1712 live_track_t *tk = p_sys->track[i];
1714 if( tk->p_out_muxed ) vlc_demux_chained_Delete( tk->p_out_muxed );
1715 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1716 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1717 es_format_Clean( &tk->fmt );
1718 free( tk->p_buffer );
1719 free( tk );
1721 TAB_CLEAN( p_sys->i_track, p_sys->track );
1722 if( p_sys->p_out_asf ) vlc_demux_chained_Delete( p_sys->p_out_asf );
1724 p_sys->ms = NULL;
1725 p_sys->rtsp = NULL;
1726 p_sys->b_no_data = true;
1727 p_sys->i_no_data_ti = 0;
1728 p_sys->p_out_asf = NULL;
1730 /* Reopen rtsp client */
1731 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1733 msg_Err( p_demux, "Failed to connect with %s", p_sys->psz_pl_url );
1734 goto error;
1737 if( p_sys->p_sdp == NULL )
1739 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1740 goto error;
1743 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1745 msg_Err( p_demux, "Nothing to play for %s", p_sys->psz_pl_url );
1746 goto error;
1749 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1750 goto error;
1752 return VLC_SUCCESS;
1754 error:
1755 return VLC_EGENERIC;
1759 /*****************************************************************************
1761 *****************************************************************************/
1762 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1763 bool b_marker,
1764 const uint8_t *p_data, unsigned i_size )
1766 const unsigned i_packet_size = p_demux->p_sys->asfh.i_min_data_packet_size;
1767 block_t *p_list = NULL;
1769 while( i_size >= 4 )
1771 unsigned i_flags = p_data[0];
1772 unsigned i_length_offset = (p_data[1] << 16) |
1773 (p_data[2] << 8) |
1774 (p_data[3] );
1775 bool b_length = i_flags & 0x40;
1776 bool b_relative_ts = i_flags & 0x20;
1777 bool b_duration = i_flags & 0x10;
1778 bool b_location_id = i_flags & 0x08;
1780 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1781 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1782 unsigned i_header_size = 4;
1783 if( b_relative_ts )
1784 i_header_size += 4;
1785 if( b_duration )
1786 i_header_size += 4;
1787 if( b_location_id )
1788 i_header_size += 4;
1790 if( i_header_size > i_size )
1792 msg_Warn( p_demux, "Invalid header size" );
1793 break;
1796 /* XXX
1797 * When b_length is true, the streams I found do not seems to respect
1798 * the documentation.
1799 * From them, I have failed to find which choice between '__MIN()' or
1800 * 'i_length_offset - i_header_size' is the right one.
1802 unsigned i_payload;
1803 if( b_length )
1804 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1805 else
1806 i_payload = i_size - i_header_size;
1808 if( !tk->p_asf_block )
1810 tk->p_asf_block = block_Alloc( i_packet_size );
1811 if( !tk->p_asf_block )
1812 break;
1813 tk->p_asf_block->i_buffer = 0;
1815 unsigned i_offset = b_length ? 0 : i_length_offset;
1816 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1818 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1819 tk->p_asf_block->i_buffer += i_payload;
1820 if( b_marker )
1822 /* We have a complete packet */
1823 tk->p_asf_block->i_buffer = i_packet_size;
1824 block_ChainAppend( &p_list, tk->p_asf_block );
1825 tk->p_asf_block = NULL;
1828 else
1830 /* Reset on broken stream */
1831 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1832 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1833 tk->p_asf_block->i_buffer = 0;
1836 /* */
1837 p_data += i_header_size + i_payload;
1838 i_size -= i_header_size + i_payload;
1840 return p_list;
1843 /*****************************************************************************
1845 *****************************************************************************/
1846 static void StreamRead( void *p_private, unsigned int i_size,
1847 unsigned int i_truncated_bytes, struct timeval pts,
1848 unsigned int duration )
1850 VLC_UNUSED( duration );
1852 live_track_t *tk = (live_track_t*)p_private;
1853 demux_t *p_demux = tk->p_demux;
1854 demux_sys_t *p_sys = p_demux->p_sys;
1855 block_t *p_block;
1857 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1859 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1860 (int64_t)pts.tv_usec;
1862 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1863 i_pts &= INT64_C(0x00ffffffffffffff);
1865 /* Retrieve NPT for this pts */
1866 tk->f_npt = tk->sub->getNormalPlayTime(pts);
1868 if( tk->format == live_track_t::QUICKTIME_STREAM && tk->p_es == NULL )
1870 QuickTimeGenericRTPSource *qtRTPSource =
1871 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1872 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1873 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1875 /* Get codec information from the quicktime atoms :
1876 * http://developer.apple.com/quicktime/icefloe/dispatch026.html */
1877 if( tk->fmt.i_cat == VIDEO_ES ) {
1878 if( qtState.sdAtomSize < 16 + 32 )
1880 /* invalid */
1881 p_sys->event_data = 0xff;
1882 tk->waiting = 0;
1883 return;
1885 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1886 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1887 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1889 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1891 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1892 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1893 + qtRTPSource->qtState.sdAtomSize;
1894 while (pos+8 < endpos) {
1895 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1896 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1897 if( memcmp(pos+4, "avcC", 4) == 0 &&
1898 atomLength > 8 &&
1899 atomLength <= INT_MAX )
1901 tk->fmt.i_extra = atomLength-8;
1902 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1903 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1904 break;
1906 pos += atomLength;
1909 else
1911 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1912 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1913 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1916 else {
1917 if( qtState.sdAtomSize < 24 )
1919 /* invalid */
1920 p_sys->event_data = 0xff;
1921 tk->waiting = 0;
1922 return;
1924 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1925 tk->fmt.audio.i_bitspersample = (sdAtom[22] << 8) | sdAtom[23];
1927 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1930 #if 0
1931 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1932 i_size,
1933 pts.tv_sec * 1000000LL + pts.tv_usec );
1934 #endif
1936 /* grow buffer if it looks like buffer is too small, but don't eat
1937 * up all the memory on strange streams */
1938 if( i_truncated_bytes > 0 )
1940 if( tk->i_buffer < 2000000 )
1942 void *p_tmp;
1943 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1944 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1945 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1946 if( p_tmp == NULL )
1948 msg_Warn( p_demux, "realloc failed" );
1950 else
1952 tk->p_buffer = (uint8_t*)p_tmp;
1953 tk->i_buffer *= 2;
1957 if( tk->b_discard_trunc )
1959 p_sys->event_data = 0xff;
1960 tk->waiting = 0;
1961 return;
1965 assert( i_size <= tk->i_buffer );
1967 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1968 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1970 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1972 if( (p_block = block_Alloc( i_size + 1 )) )
1974 p_block->p_buffer[0] = amrSource->lastFrameHeader();
1975 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1978 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1980 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1981 uint32_t header = h261Source->lastSpecialHeader();
1982 if( (p_block = block_Alloc( i_size + 4 )) )
1984 memcpy( p_block->p_buffer, &header, 4 );
1985 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1988 else if( tk->fmt.i_codec == VLC_CODEC_H264 || tk->fmt.i_codec == VLC_CODEC_HEVC )
1990 if( tk->fmt.i_codec == VLC_CODEC_H264 && (tk->p_buffer[0] & 0x1f) >= 24 )
1991 msg_Warn( p_demux, "unsupported NAL type for H264" );
1992 else if( tk->fmt.i_codec == VLC_CODEC_HEVC && ((tk->p_buffer[0] & 0x7e)>>1) >= 48 )
1993 msg_Warn( p_demux, "unsupported NAL type for H265" );
1995 /* Normal NAL type */
1996 if( (p_block = block_Alloc( i_size + 4 )) )
1998 p_block->p_buffer[0] = 0x00;
1999 p_block->p_buffer[1] = 0x00;
2000 p_block->p_buffer[2] = 0x00;
2001 p_block->p_buffer[3] = 0x01;
2002 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
2005 else if( tk->format == live_track_t::ASF_STREAM )
2007 p_block = StreamParseAsf( p_demux, tk,
2008 tk->sub->rtpSource()->curPacketMarkerBit(),
2009 tk->p_buffer, i_size );
2011 else
2013 if( (p_block = block_Alloc( i_size )) )
2014 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
2017 /* No data sent. Always in sync then */
2018 if( !tk->b_rtcp_sync && tk->sub->rtpSource() &&
2019 tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
2021 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
2022 p_sys->b_rtcp_sync = tk->b_rtcp_sync = true;
2023 if( tk->i_pcr < i_pts )
2025 tk->i_offset = (tk->i_pcr > 0) ? i_pts + tk->i_pcr : 0;
2027 else
2029 tk->b_discontinuity = ( tk->i_pcr > VLC_TS_INVALID );
2030 tk->i_pcr = VLC_TS_INVALID;
2034 i_pts -= tk->i_offset;
2036 /* Update our global npt value */
2037 if( tk->f_npt > 0 &&
2038 ( tk->f_npt < p_sys->f_npt_length || p_sys->f_npt_length <= 0 ) )
2039 p_sys->f_npt = tk->f_npt;
2041 if( p_block )
2043 switch( tk->format )
2045 case live_track_t::ASF_STREAM:
2046 vlc_demux_chained_Send( p_sys->p_out_asf, p_block );
2047 break;
2048 case live_track_t::MULTIPLEXED_STREAM:
2049 vlc_demux_chained_Send( tk->p_out_muxed, p_block );
2050 break;
2051 default:
2052 if( i_pts != tk->i_lastpts )
2053 p_block->i_pts = VLC_TS_0 + i_pts;
2054 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
2055 p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? VLC_TS_INVALID : (VLC_TS_0 + i_pts);
2056 if( unlikely(tk->i_next_block_flags) )
2058 p_block->i_flags |= tk->i_next_block_flags;
2059 tk->i_next_block_flags = 0;
2061 es_out_Send( p_demux->out, tk->p_es, p_block );
2062 if( i_pts > 0 )
2064 if( tk->i_pcr < i_pts )
2065 tk->i_pcr = i_pts;
2066 tk->i_lastpts = i_pts;
2068 break;
2072 /* warn that's ok */
2073 p_sys->event_data = 0xff;
2075 /* we have read data */
2076 tk->waiting = 0;
2077 p_demux->p_sys->b_no_data = false;
2078 p_demux->p_sys->i_no_data_ti = 0;
2081 /*****************************************************************************
2083 *****************************************************************************/
2084 static void StreamClose( void *p_private )
2086 live_track_t *tk = (live_track_t*)p_private;
2087 demux_t *p_demux = tk->p_demux;
2088 demux_sys_t *p_sys = p_demux->p_sys;
2089 tk->b_selected = false;
2090 p_sys->event_rtsp = 0xff;
2091 p_sys->event_data = 0xff;
2093 if( tk->p_es )
2094 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
2096 int nb_tracks = 0;
2097 for( int i = 0; i < p_sys->i_track; i++ )
2099 if( p_sys->track[i]->b_selected )
2100 nb_tracks++;
2102 msg_Dbg( p_demux, "RTSP track Close, %d track remaining", nb_tracks );
2103 if( !nb_tracks )
2104 p_sys->b_error = true;
2108 /*****************************************************************************
2110 *****************************************************************************/
2111 static void TaskInterruptRTSP( void *p_private )
2113 demux_t *p_demux = (demux_t*)p_private;
2115 /* Avoid lock */
2116 p_demux->p_sys->event_rtsp = 0xff;
2119 static void TaskInterruptData( void *p_private )
2121 demux_t *p_demux = (demux_t*)p_private;
2123 p_demux->p_sys->i_no_data_ti++;
2125 /* Avoid lock */
2126 p_demux->p_sys->event_data = 0xff;
2129 /*****************************************************************************
2131 *****************************************************************************/
2132 static void TimeoutPrevention( void *p_data )
2134 demux_t *p_demux = (demux_t *) p_data;
2135 demux_sys_t *p_sys = p_demux->p_sys;
2136 char *bye = NULL;
2138 /* Protect Live555 from us calling their functions simultaneously
2139 with Demux() or Control() */
2140 vlc_mutex_locker locker(&p_sys->timeout_mutex);
2142 /* If the timer fires while the demuxer owns the lock, and the demuxer
2143 * then torns the session down, the pointers will become NULL. By the time
2144 * this timer callback obtains the callback, either a new session was
2145 * created and the timer is rescheduled, or the pointers are still NULL
2146 * and the timer is descheduled. In the second case, bail out (then wait
2147 * for the timer to be rescheduled or destroyed). In the first case, this
2148 * might send an early refresh - that´s harmless but suboptimal (FIXME). */
2149 if( p_sys->rtsp == NULL || p_sys->ms == NULL )
2150 return;
2152 bool use_get_param = p_sys->b_get_param;
2154 /* Use GET_PARAMETERS if supported. wmserver dialect supports
2155 * it, but does not report this properly. */
2156 if( var_GetBool( p_demux, "rtsp-wmserver" ) )
2157 use_get_param = true;
2159 if( use_get_param )
2160 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms,
2161 default_live555_callback, bye );
2162 else
2163 p_sys->rtsp->sendOptionsCommand( default_live555_callback, NULL );
2165 if( !wait_Live555_response( p_demux ) )
2167 msg_Err( p_demux, "keep-alive failed: %s",
2168 p_sys->env->getResultMsg() );
2169 /* Just continue, worst case is we get timed out later */
2173 /*****************************************************************************
2175 *****************************************************************************/
2176 static int ParseASF( demux_t *p_demux )
2178 demux_sys_t *p_sys = p_demux->p_sys;
2180 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
2181 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2182 char *psz_end;
2183 block_t *p_header;
2185 /* Parse the asf header */
2186 if( psz_asf == NULL )
2187 return VLC_EGENERIC;
2189 psz_asf += strlen( psz_marker );
2190 psz_asf = strdup( psz_asf ); /* Duplicate it */
2191 psz_end = strchr( psz_asf, '\n' );
2193 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2194 *psz_end-- = '\0';
2196 if( psz_asf >= psz_end )
2198 free( psz_asf );
2199 return VLC_EGENERIC;
2202 /* Always smaller */
2203 p_header = block_Alloc( psz_end - psz_asf );
2204 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2205 p_header->i_buffer, psz_asf );
2206 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2207 if( p_header->i_buffer <= 0 )
2209 free( psz_asf );
2210 return VLC_EGENERIC;
2213 /* Parse it to get packet size */
2214 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2216 /* Send it to demuxer */
2217 vlc_demux_chained_Send( p_sys->p_out_asf, p_header );
2219 free( psz_asf );
2220 return VLC_SUCCESS;
2224 static unsigned char* parseH264ConfigStr( char const* configStr,
2225 unsigned int& configSize )
2227 char *dup, *psz;
2228 size_t i_records = 1;
2230 configSize = 0;
2232 if( configStr == NULL || *configStr == '\0' )
2233 return NULL;
2235 psz = dup = strdup( configStr );
2237 /* Count the number of commas */
2238 for( psz = dup; *psz != '\0'; ++psz )
2240 if( *psz == ',')
2242 ++i_records;
2243 *psz = '\0';
2247 size_t configMax = 5*strlen(dup);
2248 unsigned char *cfg = new unsigned char[configMax];
2249 psz = dup;
2250 for( size_t i = 0; i < i_records; ++i )
2252 cfg[configSize++] = 0x00;
2253 cfg[configSize++] = 0x00;
2254 cfg[configSize++] = 0x00;
2255 cfg[configSize++] = 0x01;
2257 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2258 configMax-configSize, psz );
2259 psz += strlen(psz)+1;
2262 free( dup );
2263 return cfg;
2266 static uint8_t *parseVorbisConfigStr( char const* configStr,
2267 unsigned int& configSize )
2269 configSize = 0;
2270 if( configStr == NULL || *configStr == '\0' )
2271 return NULL;
2272 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1332115200 // 2012.03.20
2273 unsigned char *p_cfg = base64Decode( configStr, configSize );
2274 #else
2275 char* configStr_dup = strdup( configStr );
2276 unsigned char *p_cfg = base64Decode( configStr_dup, configSize );
2277 free( configStr_dup );
2278 #endif
2279 uint8_t *p_extra = NULL;
2280 /* skip header count, ident number and length (cf. RFC 5215) */
2281 const unsigned int headerSkip = 9;
2282 if( configSize > headerSkip && ((uint8_t*)p_cfg)[3] == 1 )
2284 configSize -= headerSkip;
2285 p_extra = (uint8_t*)xmalloc( configSize );
2286 memcpy( p_extra, p_cfg+headerSkip, configSize );
2288 delete[] p_cfg;
2289 return p_extra;
2292 static char *passwordLessURL( vlc_url_t *p_url )
2294 vlc_url_t url;
2296 memcpy( &url, p_url, sizeof( vlc_url_t ) );
2298 url.psz_username = NULL;
2299 url.psz_password = NULL;
2300 if( url.i_port == 0 )
2301 url.i_port = 554;
2302 return vlc_uri_compose( &url );