access: srt: add support stream encryption
[vlc.git] / modules / access / live555.cpp
blobe4dd30422f45c3362b17e108a4b39c5bbe4b6197
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 250000
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_flushing_discontinuity;
174 int i_next_block_flags;
175 char waiting;
176 int64_t i_lastpts;
177 int64_t i_pcr;
178 double f_npt;
180 enum
182 STATE_NONE,
183 STATE_SELECTED,
184 STATE_IGNORED,
185 STATE_TEARDOWN,
186 } state;
188 } live_track_t;
190 class RTSPClientVlc;
192 #define CAP_RATE_CONTROL (1 << 1)
193 #define CAP_SUBSESSION_TEARDOWN (1 << 2)
194 #define CAP_SUBSESSION_PAUSE (1 << 3)
195 #define CAPS_DEFAULT CAP_RATE_CONTROL
197 struct demux_sys_t
199 char *p_sdp; /* XXX mallocated */
200 char *psz_pl_url; /* password-less URL */
201 vlc_url_t url;
203 MediaSession *ms;
204 TaskScheduler *scheduler;
205 UsageEnvironment *env ;
206 RTSPClientVlc *rtsp;
207 int capabilities; /* Server capabilities workaround */
209 /* */
210 int i_track;
211 live_track_t **track;
213 /* Weird formats */
214 asf_header_t asfh;
215 vlc_demux_chained_t *p_out_asf;
216 bool b_real;
218 /* */
219 int64_t i_pcr; /* The clock */
220 bool b_rtcp_sync; /* At least one track received sync */
221 double f_npt;
222 double f_npt_length;
223 double f_npt_start;
225 /* timeout thread information */
226 vlc_timer_t timer;
227 vlc_mutex_t timeout_mutex; /* Serialise calls to live555 in timeout thread w.r.t. Demux()/Control() */
229 /* */
230 bool b_force_mcast;
231 bool b_multicast; /* if one of the tracks is multicasted */
232 bool b_no_data; /* if we never received any data */
233 int i_no_data_ti; /* consecutive number of TaskInterrupt */
235 char event_rtsp;
236 char event_data;
238 bool b_get_param; /* Does the server support GET_PARAMETER */
239 bool b_paused; /* Are we paused? */
240 bool b_error;
241 int i_live555_ret; /* live555 callback return code */
243 float f_seek_request;/* In case we receive a seek request while paused*/
247 class RTSPClientVlc : public RTSPClient
249 public:
250 RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
251 char const* applicationName, portNumBits tunnelOverHTTPPortNum,
252 demux_sys_t *p_sys) :
253 RTSPClient( env, rtspURL, verbosityLevel, applicationName,
254 tunnelOverHTTPPortNum
255 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1373932800
256 , -1
257 #endif
260 this->p_sys = p_sys;
262 demux_sys_t *p_sys;
265 static int Demux ( demux_t * );
266 static int Control( demux_t *, int, va_list );
268 static int Connect ( demux_t * );
269 static int SessionsSetup( demux_t * );
270 static int Play ( demux_t *);
271 static int ParseASF ( demux_t * );
272 static int RollOverTcp ( demux_t * );
274 static void StreamRead ( void *, unsigned int, unsigned int,
275 struct timeval, unsigned int );
276 static void StreamClose ( void * );
277 static void TaskInterruptData( void * );
278 static void TaskInterruptRTSP( void * );
280 static void TimeoutPrevention( void * );
282 static unsigned char* parseH264ConfigStr( char const* configStr,
283 unsigned int& configSize );
284 static unsigned char* parseVorbisConfigStr( char const* configStr,
285 unsigned int& configSize );
287 static char *passwordLessURL( vlc_url_t *url );
289 #define PCR_OBS (CLOCK_FREQ / 4)
290 #define PCR_OFF PCR_OBS
292 /*****************************************************************************
293 * DemuxOpen:
294 *****************************************************************************/
295 static int Open ( vlc_object_t *p_this )
297 demux_t *p_demux = (demux_t*)p_this;
298 demux_sys_t *p_sys = NULL;
300 int i_return;
301 int i_error = VLC_EGENERIC;
303 /* if the rtsp URL may contain a sat.ip fake DNS, bail-out early and
304 * let the SAT>IP module handle that */
305 if( !strncmp(p_demux->psz_location, "sat.ip", 6) )
307 msg_Err( p_demux, "SAT>IP server, bailing out");
308 return VLC_EGENERIC;
310 /* If satip-host is set on the item, we shall assume it is a rtsp for the
311 * SAT>IP module and bail-out early. */
312 char *psz_host = var_InheritString(p_demux, "satip-host");
313 if (psz_host != NULL) {
314 msg_Err( p_demux, "URL is for SAT>IP, bailing out");
315 free(psz_host);
316 return VLC_EGENERIC;
319 if( p_demux->s )
321 /* See if it looks like a SDP
322 v, o, s fields are mandatory and in this order */
323 const uint8_t *p_peek;
324 if( vlc_stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
326 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
327 memcmp( p_peek, "v=0\n", 4 ) &&
328 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
330 return VLC_EGENERIC;
334 p_demux->pf_demux = Demux;
335 p_demux->pf_control= Control;
336 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
337 if( !p_sys ) return VLC_ENOMEM;
339 if( vlc_timer_create(&p_sys->timer, TimeoutPrevention, p_demux) )
341 free( p_sys );
342 return VLC_ENOMEM;
345 msg_Dbg( p_demux, "version " LIVEMEDIA_LIBRARY_VERSION_STRING );
347 p_sys->capabilities = CAPS_DEFAULT;
348 if( var_GetBool( p_demux, "rtsp-kasenna" ) ||
349 var_GetBool( p_demux, "rtsp-wmserver" ) )
351 p_sys->capabilities &= ~CAP_RATE_CONTROL;
354 TAB_INIT( p_sys->i_track, p_sys->track );
355 p_sys->b_no_data = true;
356 p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
357 p_sys->f_seek_request = -1;
358 vlc_mutex_init(&p_sys->timeout_mutex);
360 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
361 vlc_UrlParse( &p_sys->url, p_demux->psz_url );
363 if( ( p_sys->psz_pl_url = passwordLessURL( &p_sys->url ) ) == NULL )
365 i_error = VLC_ENOMEM;
366 goto error;
369 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
371 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
372 goto error;
374 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
376 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
377 goto error;
380 if( p_demux->s != NULL )
382 char *p = p_sys->psz_pl_url;
383 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
386 if( p_demux->s != NULL )
388 /* Gather the complete sdp file */
389 int i_sdp = 0;
390 int i_sdp_max = 1000;
391 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
393 if( !p_sdp )
395 i_error = VLC_ENOMEM;
396 goto error;
399 for( ;; )
401 int i_read = vlc_stream_Read( p_demux->s, &p_sdp[i_sdp],
402 i_sdp_max - i_sdp - 1 );
403 if( i_read < 0 )
405 msg_Err( p_demux, "failed to read SDP" );
406 free( p_sdp );
407 goto error;
410 i_sdp += i_read;
412 if( i_read < i_sdp_max - i_sdp - 1 )
414 p_sdp[i_sdp] = '\0';
415 break;
418 i_sdp_max += 1000;
419 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
421 p_sys->p_sdp = (char*)p_sdp;
423 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
425 msg_Err( p_demux, "Failed to connect with %s", p_sys->psz_pl_url );
426 goto error;
429 if( p_sys->p_sdp == NULL )
431 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
432 i_error = VLC_ENOMEM;
433 goto error;
436 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
438 msg_Err( p_demux, "Nothing to play for %s", p_sys->psz_pl_url );
439 goto error;
442 if( p_sys->b_real ) goto error;
444 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
445 goto error;
447 if( p_sys->p_out_asf && ParseASF( p_demux ) )
449 msg_Err( p_demux, "cannot find a usable asf header" );
450 /* TODO Clean tracks */
451 goto error;
454 if( p_sys->i_track <= 0 )
455 goto error;
457 return VLC_SUCCESS;
459 error:
460 Close( p_this );
461 return i_error;
464 /*****************************************************************************
465 * DemuxClose:
466 *****************************************************************************/
467 static void Close( vlc_object_t *p_this )
469 demux_t *p_demux = (demux_t*)p_this;
470 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
472 vlc_timer_destroy(p_sys->timer);
474 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
475 if( p_sys->ms ) Medium::close( p_sys->ms );
476 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
477 if( p_sys->env ) p_sys->env->reclaim();
479 for( int i = 0; i < p_sys->i_track; i++ )
481 live_track_t *tk = p_sys->track[i];
483 if( tk->p_out_muxed )
484 vlc_demux_chained_Delete( tk->p_out_muxed );
485 es_format_Clean( &tk->fmt );
486 free( tk->p_buffer );
487 free( tk );
489 TAB_CLEAN( p_sys->i_track, p_sys->track );
490 if( p_sys->p_out_asf )
491 vlc_demux_chained_Delete( p_sys->p_out_asf );
492 delete p_sys->scheduler;
493 free( p_sys->p_sdp );
494 free( p_sys->psz_pl_url );
496 vlc_UrlClean( &p_sys->url );
497 vlc_mutex_destroy(&p_sys->timeout_mutex);
499 free( p_sys );
502 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
504 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
506 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
507 demux_sys_t *p_sys = client_vlc->p_sys;
508 delete []result_string;
509 p_sys->i_live555_ret = result_code;
510 p_sys->b_error = p_sys->i_live555_ret != 0;
511 p_sys->event_rtsp = 1;
514 /* return true if the RTSP command succeeded */
515 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
517 TaskToken task;
518 demux_sys_t * p_sys = (demux_sys_t *)p_demux->p_sys;
519 p_sys->event_rtsp = 0;
520 if( i_timeout > 0 )
522 /* Create a task that will be called if we wait more than timeout ms */
523 task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000,
524 TaskInterruptRTSP,
525 p_demux );
527 p_sys->event_rtsp = 0;
528 p_sys->b_error = true;
529 p_sys->i_live555_ret = 0;
530 p_sys->scheduler->doEventLoop( &p_sys->event_rtsp );
531 //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
532 if( i_timeout > 0 )
534 /* remove the task */
535 p_sys->scheduler->unscheduleDelayedTask( task );
537 return !p_sys->b_error;
540 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
541 char* result_string )
543 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
544 demux_sys_t *p_sys = client_vlc->p_sys;
545 p_sys->i_live555_ret = result_code;
546 if ( result_code == 0 )
548 char* sdpDescription = result_string;
549 free( p_sys->p_sdp );
550 p_sys->p_sdp = NULL;
551 if( sdpDescription )
553 p_sys->p_sdp = strdup( sdpDescription );
554 p_sys->b_error = false;
557 else
558 p_sys->b_error = true;
559 delete[] result_string;
560 p_sys->event_rtsp = 1;
561 #ifdef VLC_PATCH_RTSPCLIENT_SERVERSTRING
562 if( client_vlc->serverString() )
564 if( !strncmp(client_vlc->serverString(), "Kasenna", 7) ||
565 !strncmp(client_vlc->serverString(), "WMServer", 8) )
566 p_sys->capabilities &= ~CAP_RATE_CONTROL;
567 if( !strncmp(client_vlc->serverString(), "VLC/", 4) )
568 p_sys->capabilities |= (CAP_SUBSESSION_TEARDOWN|CAP_SUBSESSION_PAUSE);
570 #endif
573 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
574 char* result_string )
576 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
577 demux_sys_t *p_sys = client_vlc->p_sys;
578 p_sys->b_get_param =
579 // If OPTIONS fails, assume GET_PARAMETER is not supported but
580 // still continue on with the stream. Some servers (foscam)
581 // return 501/not implemented for OPTIONS.
582 result_code == 0
583 && result_string != NULL
584 && strstr( result_string, "GET_PARAMETER" ) != NULL;
585 client->sendDescribeCommand( continueAfterDESCRIBE );
586 delete[] result_string;
589 /*****************************************************************************
590 * Connect: connects to the RTSP server to setup the session DESCRIBE
591 *****************************************************************************/
592 static int Connect( demux_t *p_demux )
594 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
595 Authenticator authenticator;
596 vlc_credential credential;
597 const char *psz_user = NULL;
598 const char *psz_pwd = NULL;
599 int i_http_port = 0;
600 int i_ret = VLC_SUCCESS;
601 const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
603 vlc_credential_init( &credential, &p_sys->url );
605 /* Credentials can be NULL since they may not be needed */
606 if( vlc_credential_get( &credential, p_demux, "rtsp-user", "rtsp-pwd",
607 NULL, NULL) )
609 psz_user = credential.psz_username;
610 psz_pwd = credential.psz_password;
613 createnew:
614 /* FIXME: This is naive and incorrect; it does not prevent the thread
615 * getting stuck in blocking socket operations. */
616 if( vlc_killed() )
618 i_ret = VLC_EGENERIC;
619 goto bailout;
622 if( var_CreateGetBool( p_demux, "rtsp-http" ) )
623 i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
625 p_sys->rtsp = new (std::nothrow) RTSPClientVlc( *p_sys->env, p_sys->psz_pl_url,
626 var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
627 "LibVLC/" VERSION, i_http_port, p_sys );
628 if( !p_sys->rtsp )
630 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
631 p_sys->env->getResultMsg() );
632 i_ret = VLC_EGENERIC;
633 goto bailout;
636 /* Kasenna enables KeepAlive by analysing the User-Agent string.
637 * Appending _KA to the string should be enough to enable this feature,
638 * however, there is a bug where the _KA doesn't get parsed from the
639 * default User-Agent as created by VLC/Live555 code. This is probably due
640 * to spaces in the string or the string being too long. Here we override
641 * the default string with a more compact version.
643 if( var_InheritBool( p_demux, "rtsp-kasenna" ))
645 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
648 describe:
649 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
651 p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
653 if( !wait_Live555_response( p_demux, i_timeout ) )
655 int i_code = p_sys->i_live555_ret;
656 if( i_code == 401 )
658 msg_Dbg( p_demux, "authentication failed" );
660 if( vlc_credential_get( &credential, p_demux, "rtsp-user", "rtsp-pwd",
661 _("RTSP authentication"),
662 _("Please enter a valid login name and a password.") ) )
664 psz_user = credential.psz_username;
665 psz_pwd = credential.psz_password;
666 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
667 goto describe;
670 else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
672 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
673 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
674 var_SetBool( p_demux, "rtsp-http", true );
675 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
676 p_sys->rtsp = NULL;
677 goto createnew;
679 else
681 if( i_code == 0 )
682 msg_Dbg( p_demux, "connection timeout" );
683 else
685 msg_Dbg( p_demux, "connection error %d", i_code );
686 if( i_code == 403 )
687 vlc_dialog_display_error( p_demux, _("RTSP connection failed"),
688 _("Access to the stream is denied by the server configuration.") );
690 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
691 p_sys->rtsp = NULL;
693 i_ret = VLC_EGENERIC;
695 else
696 vlc_credential_store( &credential, p_demux );
698 bailout:
699 vlc_credential_clean( &credential );
701 return i_ret;
704 /*****************************************************************************
705 * SessionsSetup: prepares the subsessions and does the SETUP
706 *****************************************************************************/
707 static int SessionsSetup( demux_t *p_demux )
709 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
710 MediaSubsessionIterator *iter = NULL;
711 MediaSubsession *sub = NULL;
713 bool b_rtsp_tcp;
714 int i_client_port;
715 int i_return = VLC_SUCCESS;
716 unsigned int i_receive_buffer = 0;
717 int i_frame_buffer = DEFAULT_FRAME_BUFFER_SIZE;
718 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
719 const char *p_sess_lang = NULL;
720 const char *p_lang;
722 b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
723 var_GetBool( p_demux, "rtsp-http" );
724 i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
727 /* Create the session from the SDP */
728 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
730 msg_Err( p_demux, "Could not create the RTSP Session: %s",
731 p_sys->env->getResultMsg() );
732 return VLC_EGENERIC;
735 if( strcmp( p_sys->p_sdp, "m=" ) != 0 )
737 const char *p_sess_attr_end;
739 p_sess_attr_end = strstr( p_sys->p_sdp, "\nm=" );
740 if( !p_sess_attr_end )
741 p_sess_attr_end = strstr( p_sys->p_sdp, "\rm=" );
743 p_sess_lang = p_sess_attr_end ? strstr( p_sys->p_sdp, "a=lang:" ) : NULL;
744 if( p_sess_lang &&
745 p_sess_lang - p_sys->p_sdp > p_sess_attr_end - p_sys->p_sdp )
746 p_sess_lang = NULL;
749 /* Initialise each media subsession */
750 iter = new MediaSubsessionIterator( *p_sys->ms );
751 while( ( sub = iter->next() ) != NULL )
753 Boolean bInit;
754 live_track_t *tk;
756 /* Value taken from mplayer */
757 if( !strcmp( sub->mediumName(), "audio" ) )
758 i_receive_buffer = 100000;
759 else if( !strcmp( sub->mediumName(), "video" ) )
761 int i_var_buf_size = var_InheritInteger( p_demux, "rtsp-frame-buffer-size" );
762 if( i_var_buf_size > 0 )
763 i_frame_buffer = i_var_buf_size;
764 i_receive_buffer = 2000000;
766 else if( !strcmp( sub->mediumName(), "text" ) )
768 else continue;
770 if( strcasestr( sub->codecName(), "REAL" ) )
772 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
773 p_sys->b_real = true; /* This is a problem, we'll handle it later */
774 continue;
777 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
778 bInit = sub->initiate( 0 );
779 else
780 bInit = sub->initiate();
782 if( !bInit )
784 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
785 sub->mediumName(), sub->codecName(),
786 p_sys->env->getResultMsg() );
788 else
790 if( sub->rtpSource() != NULL )
792 int fd = sub->rtpSource()->RTPgs()->socketNum();
794 /* Increase the buffer size */
795 if( i_receive_buffer > 0 )
796 increaseReceiveBufferTo( *p_sys->env, fd, i_receive_buffer );
798 /* Increase the RTP reorder timebuffer just a bit */
799 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
801 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
802 sub->codecName() );
804 /* Issue the SETUP */
805 if( p_sys->rtsp )
808 if( i_client_port != -1 )
810 sub->setClientPortNum( i_client_port );
811 i_client_port += 2;
814 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
815 toBool( b_rtsp_tcp ),
816 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
817 if( !wait_Live555_response( p_demux ) )
819 /* if we get an unsupported transport error, toggle TCP
820 * use and try again */
821 if( p_sys->i_live555_ret == 461 )
822 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
823 !toBool( b_rtsp_tcp ), False );
824 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
826 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
827 sub->mediumName(), sub->codecName(),
828 p_sys->env->getResultMsg() );
829 continue;
831 else
833 var_SetBool( p_demux, "rtsp-tcp", true );
834 b_rtsp_tcp = true;
839 /* Check if we will receive data from this subsession for
840 * this track */
841 if( sub->readSource() == NULL ) continue;
842 if( !p_sys->b_multicast )
844 /* We need different rollover behaviour for multicast */
845 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
848 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
849 if( !tk )
851 delete iter;
852 return VLC_ENOMEM;
854 tk->p_demux = p_demux;
855 tk->sub = sub;
856 tk->p_es = NULL;
857 tk->format = live_track_t::SINGLE_STREAM;
858 tk->p_asf_block = NULL;
859 tk->b_discard_trunc = false;
860 tk->p_out_muxed = NULL;
861 tk->waiting = 0;
862 tk->b_rtcp_sync = false;
863 tk->b_flushing_discontinuity = false;
864 tk->i_next_block_flags = 0;
865 tk->i_lastpts = VLC_TS_INVALID;
866 tk->i_pcr = VLC_TS_INVALID;
867 tk->f_npt = 0.;
868 tk->state = live_track_t::STATE_SELECTED;
869 tk->i_buffer = i_frame_buffer;
870 tk->p_buffer = (uint8_t *)malloc( i_frame_buffer );
872 if( !tk->p_buffer )
874 free( tk );
875 delete iter;
876 return VLC_ENOMEM;
879 /* Value taken from mplayer */
880 if( !strcmp( sub->mediumName(), "audio" ) )
882 es_format_Init( &tk->fmt, AUDIO_ES, VLC_CODEC_UNKNOWN );
883 tk->fmt.audio.i_channels = sub->numChannels();
884 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
886 if( !strcmp( sub->codecName(), "MPA" ) ||
887 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
888 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
890 tk->fmt.i_codec = VLC_CODEC_MPGA;
891 tk->fmt.audio.i_rate = 0;
893 else if( !strcmp( sub->codecName(), "AC3" ) )
895 tk->fmt.i_codec = VLC_CODEC_A52;
896 tk->fmt.audio.i_rate = 0;
898 else if( !strcmp( sub->codecName(), "L16" ) )
900 tk->fmt.i_codec = VLC_CODEC_S16B;
901 tk->fmt.audio.i_bitspersample = 16;
903 else if( !strcmp( sub->codecName(), "L20" ) )
905 tk->fmt.i_codec = VLC_CODEC_S20B;
906 tk->fmt.audio.i_bitspersample = 20;
908 else if( !strcmp( sub->codecName(), "L24" ) )
910 tk->fmt.i_codec = VLC_CODEC_S24B;
911 tk->fmt.audio.i_bitspersample = 24;
913 else if( !strcmp( sub->codecName(), "L8" ) )
915 tk->fmt.i_codec = VLC_CODEC_U8;
916 tk->fmt.audio.i_bitspersample = 8;
918 else if( !strcmp( sub->codecName(), "DAT12" ) )
920 tk->fmt.i_codec = VLC_CODEC_DAT12;
921 tk->fmt.audio.i_bitspersample = 12;
923 else if( !strcmp( sub->codecName(), "PCMU" ) )
925 tk->fmt.i_codec = VLC_CODEC_MULAW;
926 tk->fmt.audio.i_bitspersample = 8;
928 else if( !strcmp( sub->codecName(), "PCMA" ) )
930 tk->fmt.i_codec = VLC_CODEC_ALAW;
931 tk->fmt.audio.i_bitspersample = 8;
933 else if( !strncmp( sub->codecName(), "G726", 4 ) )
935 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
936 tk->fmt.audio.i_rate = 8000;
937 tk->fmt.audio.i_channels = 1;
938 if( !strcmp( sub->codecName()+5, "40" ) )
939 tk->fmt.i_bitrate = 40000;
940 else if( !strcmp( sub->codecName()+5, "32" ) )
941 tk->fmt.i_bitrate = 32000;
942 else if( !strcmp( sub->codecName()+5, "24" ) )
943 tk->fmt.i_bitrate = 24000;
944 else if( !strcmp( sub->codecName()+5, "16" ) )
945 tk->fmt.i_bitrate = 16000;
947 else if( !strcmp( sub->codecName(), "AMR" ) )
949 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
951 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
953 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
955 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
957 unsigned int i_extra;
958 uint8_t *p_extra;
960 tk->fmt.i_codec = VLC_CODEC_MP4A;
962 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
963 i_extra ) ) )
965 tk->fmt.i_extra = i_extra;
966 tk->fmt.p_extra = xmalloc( i_extra );
967 memcpy( tk->fmt.p_extra, p_extra, i_extra );
968 delete[] p_extra;
970 /* Because the "faad" decoder does not handle the LATM
971 * data length field at the start of each returned LATM
972 * frame, tell the RTP source to omit. */
973 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
975 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
977 unsigned int i_extra;
978 uint8_t *p_extra;
980 tk->fmt.i_codec = VLC_CODEC_MP4A;
982 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
983 i_extra ) ) )
985 tk->fmt.i_extra = i_extra;
986 tk->fmt.p_extra = xmalloc( i_extra );
987 memcpy( tk->fmt.p_extra, p_extra, i_extra );
988 delete[] p_extra;
991 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
993 tk->format = live_track_t::ASF_STREAM;
994 if( p_sys->p_out_asf == NULL )
995 p_sys->p_out_asf =
996 vlc_demux_chained_New( VLC_OBJECT(p_demux), "asf",
997 p_demux->out );
999 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1000 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
1002 tk->format = live_track_t::QUICKTIME_STREAM;
1004 else if( !strcmp( sub->codecName(), "SPEEX" ) )
1006 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
1008 else if( !strcmp( sub->codecName(), "VORBIS" ) )
1010 tk->fmt.i_codec = VLC_CODEC_VORBIS;
1011 unsigned int i_extra;
1012 unsigned char *p_extra;
1013 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
1014 i_extra ) ) )
1016 tk->fmt.i_extra = i_extra;
1017 tk->fmt.p_extra = p_extra;
1019 else
1020 msg_Warn( p_demux,"Missing or unsupported vorbis header." );
1022 else if( !strcmp( sub->codecName(), "OPUS" ) )
1024 tk->fmt.i_codec = VLC_CODEC_OPUS;
1027 else if( !strcmp( sub->mediumName(), "video" ) )
1029 es_format_Init( &tk->fmt, VIDEO_ES, VLC_CODEC_UNKNOWN );
1030 if( !strcmp( sub->codecName(), "MPV" ) )
1032 tk->fmt.i_codec = VLC_CODEC_MPGV;
1033 tk->fmt.b_packetized = false;
1035 else if( !strcmp( sub->codecName(), "H263" ) ||
1036 !strcmp( sub->codecName(), "H263-1998" ) ||
1037 !strcmp( sub->codecName(), "H263-2000" ) )
1039 tk->fmt.i_codec = VLC_CODEC_H263;
1041 else if( !strcmp( sub->codecName(), "H261" ) )
1043 tk->fmt.i_codec = VLC_CODEC_H261;
1045 else if( !strcmp( sub->codecName(), "H264" ) )
1047 unsigned int i_extra = 0;
1048 uint8_t *p_extra = NULL;
1050 tk->fmt.i_codec = VLC_CODEC_H264;
1051 tk->fmt.b_packetized = false;
1053 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
1054 i_extra ) ) )
1056 tk->fmt.i_extra = i_extra;
1057 tk->fmt.p_extra = xmalloc( i_extra );
1058 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1060 delete[] p_extra;
1063 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1393372800 // 2014.02.26
1064 else if( !strcmp( sub->codecName(), "H265" ) )
1066 unsigned int i_extra1 = 0, i_extra2 = 0, i_extra3 = 0, i_extraTot;
1067 uint8_t *p_extra1 = NULL, *p_extra2 = NULL, *p_extra3 = NULL;
1069 tk->fmt.i_codec = VLC_CODEC_HEVC;
1070 tk->fmt.b_packetized = false;
1072 p_extra1 = parseH264ConfigStr( sub->fmtp_spropvps(), i_extra1 );
1073 p_extra2 = parseH264ConfigStr( sub->fmtp_spropsps(), i_extra2 );
1074 p_extra3 = parseH264ConfigStr( sub->fmtp_sproppps(), i_extra3 );
1075 i_extraTot = i_extra1 + i_extra2 + i_extra3;
1076 if( i_extraTot > 0 )
1078 tk->fmt.i_extra = i_extraTot;
1079 tk->fmt.p_extra = xmalloc( i_extraTot );
1080 if( p_extra1 )
1082 memcpy( tk->fmt.p_extra, p_extra1, i_extra1 );
1084 if( p_extra2 )
1086 memcpy( ((char*)tk->fmt.p_extra)+i_extra1, p_extra2, i_extra2 );
1088 if( p_extra3 )
1090 memcpy( ((char*)tk->fmt.p_extra)+i_extra1+i_extra2, p_extra3, i_extra3 );
1093 delete[] p_extra1; delete[] p_extra2; delete[] p_extra3;
1096 #endif
1097 else if( !strcmp( sub->codecName(), "JPEG" ) )
1099 tk->fmt.i_codec = VLC_CODEC_MJPG;
1101 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1103 unsigned int i_extra;
1104 uint8_t *p_extra;
1106 tk->fmt.i_codec = VLC_CODEC_MP4V;
1108 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1109 i_extra ) ) )
1111 tk->fmt.i_extra = i_extra;
1112 tk->fmt.p_extra = xmalloc( i_extra );
1113 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1114 delete[] p_extra;
1117 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1118 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1119 !strcmp( sub->codecName(), "X-QDM" ) ||
1120 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1121 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1123 tk->format = live_track_t::QUICKTIME_STREAM;
1125 else if( !strcmp( sub->codecName(), "MP2T" ) )
1127 tk->format = live_track_t::MULTIPLEXED_STREAM;
1128 tk->p_out_muxed =
1129 vlc_demux_chained_New( VLC_OBJECT(p_demux), "ts",
1130 p_demux->out );
1132 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1133 !strcmp( sub->codecName(), "MP1S" ) )
1135 tk->format = live_track_t::MULTIPLEXED_STREAM;
1136 tk->p_out_muxed =
1137 vlc_demux_chained_New( VLC_OBJECT(p_demux), "ps",
1138 p_demux->out );
1140 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1142 tk->format = live_track_t::ASF_STREAM;
1143 if( p_sys->p_out_asf == NULL )
1144 p_sys->p_out_asf =
1145 vlc_demux_chained_New( VLC_OBJECT(p_demux),
1146 "asf", p_demux->out );
1148 else if( !strcmp( sub->codecName(), "DV" ) )
1150 tk->format = live_track_t::MULTIPLEXED_STREAM;
1151 tk->b_discard_trunc = true;
1152 tk->p_out_muxed =
1153 vlc_demux_chained_New( VLC_OBJECT(p_demux), "rawdv",
1154 p_demux->out );
1156 else if( !strcmp( sub->codecName(), "VP8" ) )
1158 tk->fmt.i_codec = VLC_CODEC_VP8;
1160 else if( !strcmp( sub->codecName(), "THEORA" ) )
1162 tk->fmt.i_codec = VLC_CODEC_THEORA;
1163 unsigned int i_extra;
1164 unsigned char *p_extra;
1165 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
1166 i_extra ) ) )
1168 tk->fmt.i_extra = i_extra;
1169 tk->fmt.p_extra = p_extra;
1171 else
1172 msg_Warn( p_demux,"Missing or unsupported theora header." );
1175 else if( !strcmp( sub->mediumName(), "text" ) )
1177 es_format_Init( &tk->fmt, SPU_ES, VLC_CODEC_UNKNOWN );
1179 if( !strcmp( sub->codecName(), "T140" ) )
1181 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1185 /* Try and parse a=lang: attribute */
1186 p_lang = strstr( sub->savedSDPLines(), "a=lang:" );
1187 if( !p_lang )
1188 p_lang = p_sess_lang;
1190 if( p_lang )
1192 unsigned i_lang_len;
1193 p_lang += 7;
1194 i_lang_len = strcspn( p_lang, " \r\n" );
1195 tk->fmt.psz_language = strndup( p_lang, i_lang_len );
1198 if( tk->format == live_track_t::SINGLE_STREAM )
1200 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1203 if( sub->rtcpInstance() != NULL )
1205 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1208 if( tk->p_es ||
1209 tk->format == live_track_t::QUICKTIME_STREAM ||
1210 (tk->format == live_track_t::MULTIPLEXED_STREAM && tk->p_out_muxed ) ||
1211 (tk->format == live_track_t::ASF_STREAM && p_sys->p_out_asf ) )
1213 TAB_APPEND_CAST( (live_track_t **), p_sys->i_track, p_sys->track, tk );
1215 else
1217 /* BUG ??? */
1218 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1219 es_format_Clean( &tk->fmt );
1220 free( tk );
1224 delete iter;
1225 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1227 /* Retrieve the starttime if possible */
1228 p_sys->f_npt_start = p_sys->ms->playStartTime();
1230 /* Retrieve the duration if possible */
1231 p_sys->f_npt_length = p_sys->ms->playEndTime();
1233 /* */
1234 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1236 /* */
1237 p_sys->b_no_data = true;
1238 p_sys->i_no_data_ti = 0;
1239 p_sys->b_rtcp_sync = false;
1240 p_sys->i_pcr = VLC_TS_INVALID;
1242 return i_return;
1245 /*****************************************************************************
1246 * Play: starts the actual playback of the stream
1247 *****************************************************************************/
1248 static int Play( demux_t *p_demux )
1250 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1252 if( p_sys->rtsp )
1254 /* The PLAY */
1255 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_npt_start, -1, 1 );
1257 if( !wait_Live555_response(p_demux) )
1259 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1260 return VLC_EGENERIC;
1263 /* Retrieve the timeout value and set up a timeout prevention thread */
1264 int timeout = p_sys->rtsp->sessionTimeoutParameter();
1265 if( timeout <= 2 )
1266 timeout = 60; /* default value from RFC2326 */
1267 msg_Dbg( p_demux, "We have a timeout of %d seconds", timeout );
1269 mtime_t interval = (timeout - 2) * CLOCK_FREQ;
1270 vlc_timer_schedule( p_sys->timer, false, interval, interval);
1272 p_sys->i_pcr = VLC_TS_INVALID;
1274 /* Retrieve the starttime if possible */
1275 p_sys->f_npt_start = p_sys->ms->playStartTime();
1276 if( p_sys->ms->playEndTime() > 0 )
1277 p_sys->f_npt_length = p_sys->ms->playEndTime();
1279 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1280 return VLC_SUCCESS;
1283 /*****************************************************************************
1284 * HasSharedSession: returns if the session is shared with another stream
1285 *****************************************************************************/
1286 static bool HasSharedSession( MediaSubsession *session )
1288 MediaSubsessionIterator *it =
1289 new MediaSubsessionIterator( session->parentSession() );
1290 MediaSubsession *subsession;
1291 bool b_shared = false;
1292 while( (subsession = it->next()) != NULL )
1294 if( session == subsession )
1295 continue;
1296 if( !strcmp( session->sessionId(), subsession->sessionId() ) )
1298 b_shared = true;
1299 break;
1302 delete it;
1303 return b_shared;
1306 /*****************************************************************************
1307 * ResumeTrack: setup or resume a silenced track
1308 *****************************************************************************/
1309 static void ResumeTrack( demux_t *p_demux, live_track_t *tk )
1311 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1313 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1314 var_GetBool( p_demux, "rtsp-http" );
1315 p_sys->rtsp->sendSetupCommand( *tk->sub, default_live555_callback, False,
1316 toBool( b_rtsp_tcp ),
1317 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
1318 if( !wait_Live555_response( p_demux ) )
1320 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
1321 tk->sub->mediumName(), tk->sub->codecName(),
1322 p_sys->env->getResultMsg() );
1324 else
1326 p_sys->rtsp->sendPlayCommand( *tk->sub, default_live555_callback, -1, -1, p_sys->ms->scale() );
1327 if( !wait_Live555_response(p_demux) )
1329 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1330 if( (p_sys->capabilities & CAP_SUBSESSION_TEARDOWN) ||
1331 !HasSharedSession( tk->sub ) )
1333 tk->state = live_track_t::STATE_TEARDOWN;
1334 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1337 else
1338 tk->state = live_track_t::STATE_SELECTED;
1342 /*****************************************************************************
1343 * Demux:
1344 *****************************************************************************/
1345 static int Demux( demux_t *p_demux )
1347 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1348 TaskToken task;
1350 bool b_send_pcr = true;
1351 int i;
1353 /* Protect Live555 from simultaneous calls in TimeoutPrevention()
1354 during pause */
1355 vlc_mutex_locker locker(&p_sys->timeout_mutex);
1357 for( i = 0; i < p_sys->i_track; i++ )
1359 live_track_t *tk = p_sys->track[i];
1361 if( tk->p_es )
1363 bool b;
1364 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1365 if( !b && (tk->state == live_track_t::STATE_SELECTED) && p_sys->rtsp )
1367 if( (p_sys->capabilities & CAP_SUBSESSION_TEARDOWN) ||
1368 !HasSharedSession( tk->sub ) )
1370 tk->state = live_track_t::STATE_TEARDOWN;
1371 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1373 else tk->state = live_track_t::STATE_IGNORED;
1375 else if( b && tk->state != live_track_t::STATE_SELECTED )
1377 if( tk->state != live_track_t::STATE_IGNORED )
1378 ResumeTrack( p_demux, tk );
1379 else
1380 tk->state = live_track_t::STATE_SELECTED;
1382 if( tk->state != live_track_t::STATE_SELECTED )
1383 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1387 if( tk->format == live_track_t::ASF_STREAM ||
1388 tk->format == live_track_t::MULTIPLEXED_STREAM )
1390 b_send_pcr = false;
1394 /* First warn we want to read data */
1395 p_sys->event_data = 0;
1396 for( i = 0; i < p_sys->i_track; i++ )
1398 live_track_t *tk = p_sys->track[i];
1400 if( tk->waiting == 0 )
1402 tk->waiting = 1;
1403 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1404 StreamRead, tk, StreamClose, tk );
1407 /* Create a task that will be called if we wait more than 300ms */
1408 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1410 /* Do the read */
1411 p_sys->scheduler->doEventLoop( &p_sys->event_data );
1413 /* remove the task */
1414 p_sys->scheduler->unscheduleDelayedTask( task );
1416 if( b_send_pcr )
1418 mtime_t i_minpcr = VLC_TS_INVALID;
1419 bool b_need_flush = false;
1421 /* Check for gap in pts value */
1422 for( i = 0; i < p_sys->i_track; i++ )
1424 live_track_t *tk = p_sys->track[i];
1426 if( tk->state != live_track_t::STATE_SELECTED ||
1427 (p_sys->b_rtcp_sync && !tk->b_rtcp_sync) )
1428 continue;
1430 /* Check for gap in pts value */
1431 b_need_flush |= (tk->b_flushing_discontinuity);
1433 if( i_minpcr == VLC_TS_INVALID || ( tk->i_pcr != VLC_TS_INVALID && i_minpcr > tk->i_pcr ) )
1434 i_minpcr = tk->i_pcr;
1437 if( p_sys->i_pcr > VLC_TS_INVALID && b_need_flush )
1439 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1440 p_sys->i_pcr = i_minpcr;
1441 p_sys->f_npt = 0.;
1443 for( i = 0; i < p_sys->i_track; i++ )
1445 live_track_t *tk = p_sys->track[i];
1446 tk->i_lastpts = VLC_TS_INVALID;
1447 tk->i_pcr = VLC_TS_INVALID;
1448 tk->f_npt = 0.;
1449 tk->b_flushing_discontinuity = false;
1450 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1452 if( p_sys->i_pcr != VLC_TS_INVALID )
1453 es_out_SetPCR( p_demux->out, VLC_TS_0 +
1454 __MAX(0, p_sys->i_pcr - PCR_OFF) );
1456 else if( p_sys->i_pcr == VLC_TS_INVALID ||
1457 i_minpcr > p_sys->i_pcr + PCR_OBS )
1459 p_sys->i_pcr = __MAX(0, i_minpcr - PCR_OFF);
1460 if( p_sys->i_pcr != VLC_TS_INVALID )
1461 es_out_SetPCR( p_demux->out, VLC_TS_0 + p_sys->i_pcr );
1465 if( p_sys->b_multicast && p_sys->b_no_data &&
1466 ( p_sys->i_no_data_ti > 120 ) )
1468 /* FIXME Make this configurable
1469 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1470 return 0;
1473 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1474 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1476 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1477 var_GetBool( p_demux, "rtsp-http" );
1479 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1481 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1482 if( RollOverTcp( p_demux ) )
1484 msg_Err( p_demux, "TCP rollover failed, aborting" );
1485 return 0;
1487 return 1;
1489 msg_Err( p_demux, "no data received in 10s, aborting" );
1490 return 0;
1492 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1493 ( p_sys->i_no_data_ti > 34 ) )
1495 /* EOF ? */
1496 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1497 return 0;
1499 return p_sys->b_error ? 0 : 1;
1502 /*****************************************************************************
1503 * Control:
1504 *****************************************************************************/
1505 static int Control( demux_t *p_demux, int i_query, va_list args )
1507 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1508 int64_t *pi64, i64;
1509 double *pf, f;
1510 bool *pb;
1512 vlc_mutex_locker locker(&p_sys->timeout_mutex); /* (see same in Demux) */
1514 switch( i_query )
1516 case DEMUX_GET_TIME:
1517 pi64 = va_arg( args, int64_t * );
1518 if( p_sys->f_npt > 0 )
1520 *pi64 = (int64_t)(p_sys->f_npt * 1000000.);
1521 return VLC_SUCCESS;
1523 return VLC_EGENERIC;
1525 case DEMUX_GET_LENGTH:
1526 pi64 = va_arg( args, int64_t * );
1527 if( p_sys->f_npt_length > 0 )
1529 double d_length = p_sys->f_npt_length * 1000000.0;
1530 if( d_length >= INT64_MAX )
1531 *pi64 = INT64_MAX;
1532 else
1533 *pi64 = (int64_t)d_length;
1534 return VLC_SUCCESS;
1536 return VLC_EGENERIC;
1538 case DEMUX_GET_POSITION:
1539 pf = va_arg( args, double * );
1540 if( (p_sys->f_npt_length > 0) && (p_sys->f_npt > 0) )
1542 *pf = p_sys->f_npt / p_sys->f_npt_length;
1543 return VLC_SUCCESS;
1545 return VLC_EGENERIC;
1547 case DEMUX_SET_POSITION:
1548 case DEMUX_SET_TIME:
1549 if( p_sys->rtsp && (p_sys->f_npt_length > 0) )
1551 float time;
1553 if( (i_query == DEMUX_SET_TIME) && (p_sys->f_npt > 0) )
1555 i64 = va_arg( args, int64_t );
1556 time = (float)(i64 / 1000000.0); /* in second */
1558 else if( i_query == DEMUX_SET_TIME )
1559 return VLC_EGENERIC;
1560 else
1562 f = va_arg( args, double );
1563 time = f * p_sys->f_npt_length; /* in second */
1566 if( p_sys->b_paused )
1568 p_sys->f_seek_request = time;
1569 return VLC_SUCCESS;
1572 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1574 if( !wait_Live555_response( p_demux ) )
1576 msg_Err( p_demux, "PAUSE before seek failed %s",
1577 p_sys->env->getResultMsg() );
1578 return VLC_EGENERIC;
1581 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1583 if( !wait_Live555_response( p_demux ) )
1585 msg_Err( p_demux, "seek PLAY failed %s",
1586 p_sys->env->getResultMsg() );
1587 return VLC_EGENERIC;
1589 p_sys->i_pcr = VLC_TS_INVALID;
1591 for( int i = 0; i < p_sys->i_track; i++ )
1593 p_sys->track[i]->b_rtcp_sync = false;
1594 p_sys->track[i]->i_lastpts = VLC_TS_INVALID;
1595 p_sys->track[i]->i_pcr = VLC_TS_INVALID;
1598 /* Retrieve the starttime if possible */
1599 p_sys->f_npt = p_sys->f_npt_start = p_sys->ms->playStartTime();
1601 /* Retrieve the duration if possible */
1602 if( p_sys->ms->playEndTime() > 0 )
1603 p_sys->f_npt_length = p_sys->ms->playEndTime();
1605 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1606 return VLC_SUCCESS;
1608 return VLC_EGENERIC;
1610 /* Special for access_demux */
1611 case DEMUX_CAN_PAUSE:
1612 case DEMUX_CAN_SEEK:
1613 pb = va_arg( args, bool * );
1614 if( p_sys->rtsp && p_sys->f_npt_length > 0 )
1615 /* Not always true, but will be handled in SET_PAUSE_STATE */
1616 *pb = true;
1617 else
1618 *pb = false;
1619 return VLC_SUCCESS;
1621 case DEMUX_CAN_CONTROL_PACE:
1622 pb = va_arg( args, bool * );
1624 #if 1 /* Disable for now until we have a clock synchro algo
1625 * which works with something else than MPEG over UDP */
1626 *pb = false;
1627 #else
1628 *pb = true;
1629 #endif
1630 return VLC_SUCCESS;
1632 case DEMUX_CAN_CONTROL_RATE:
1633 pb = va_arg( args, bool * );
1635 *pb = (p_sys->rtsp != NULL) &&
1636 (p_sys->f_npt_length > 0) &&
1637 (p_sys->capabilities & CAP_RATE_CONTROL);
1638 return VLC_SUCCESS;
1640 case DEMUX_SET_RATE:
1642 int *pi_int;
1643 double f_scale, f_old_scale;
1645 if( !p_sys->rtsp || (p_sys->f_npt_length <= 0) ||
1646 !(p_sys->capabilities & CAP_RATE_CONTROL) )
1647 return VLC_EGENERIC;
1649 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1650 * supports Scale:
1652 * "[...] should try to approximate the viewing rate, but
1653 * may restrict the range of scale values that it supports.
1654 * The response MUST contain the actual scale value chosen
1655 * by the server."
1657 * Scale = 1 indicates normal play
1658 * Scale > 1 indicates fast forward
1659 * Scale < 1 && Scale > 0 indicates slow motion
1660 * Scale < 0 value indicates rewind
1663 pi_int = va_arg( args, int * );
1664 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1665 f_old_scale = p_sys->ms->scale();
1667 /* Passing -1 for the start and end time will mean liveMedia won't
1668 * create a Range: section for the RTSP message. The server should
1669 * pick up from the current position */
1670 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1672 if( !wait_Live555_response( p_demux ) )
1674 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1675 p_sys->env->getResultMsg() );
1676 return VLC_EGENERIC;
1679 if( p_sys->ms->scale() == f_old_scale )
1681 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1682 p_sys->ms->scale() );
1683 return VLC_EGENERIC;
1686 /* ReSync the stream */
1687 p_sys->f_npt_start = 0;
1688 p_sys->i_pcr = VLC_TS_INVALID;
1689 p_sys->f_npt = 0.0;
1691 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1692 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1693 return VLC_SUCCESS;
1696 case DEMUX_SET_PAUSE_STATE:
1698 bool b_pause = (bool)va_arg( args, int );
1699 if( p_sys->rtsp == NULL )
1700 return VLC_EGENERIC;
1702 if( b_pause == p_sys->b_paused )
1703 return VLC_SUCCESS;
1704 if( b_pause )
1705 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1706 else
1707 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1708 -1.0f, p_sys->ms->scale() );
1710 if( !wait_Live555_response( p_demux ) )
1712 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1713 return VLC_EGENERIC;
1715 p_sys->f_seek_request = -1;
1716 p_sys->b_paused = b_pause;
1718 if( !p_sys->b_paused )
1720 for( int i = 0; i < p_sys->i_track; i++ )
1722 live_track_t *tk = p_sys->track[i];
1723 tk->b_rtcp_sync = false;
1724 tk->b_flushing_discontinuity = false;
1725 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1726 tk->i_lastpts = VLC_TS_INVALID;
1727 tk->i_pcr = VLC_TS_INVALID;
1729 p_sys->i_pcr = VLC_TS_INVALID;
1730 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1733 /* Reset data received counter */
1734 p_sys->i_no_data_ti = 0;
1736 /* Retrieve the starttime if possible */
1737 p_sys->f_npt_start = p_sys->ms->playStartTime();
1739 /* Retrieve the duration if possible */
1740 if( p_sys->ms->playEndTime() )
1741 p_sys->f_npt_length = p_sys->ms->playEndTime();
1743 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1745 return VLC_SUCCESS;
1747 case DEMUX_GET_TITLE_INFO:
1748 case DEMUX_SET_TITLE:
1749 case DEMUX_SET_SEEKPOINT:
1750 return VLC_EGENERIC;
1752 case DEMUX_GET_PTS_DELAY:
1753 pi64 = va_arg( args, int64_t * );
1754 *pi64 = INT64_C(1000)
1755 * var_InheritInteger( p_demux, "network-caching" );
1756 return VLC_SUCCESS;
1758 default:
1759 return VLC_EGENERIC;
1763 /*****************************************************************************
1764 * RollOverTcp: reopen the rtsp into TCP mode
1765 * XXX: ugly, a lot of code are duplicated from Open()
1766 * This should REALLY be fixed
1767 *****************************************************************************/
1768 static int RollOverTcp( demux_t *p_demux )
1770 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1771 int i, i_return;
1773 var_SetBool( p_demux, "rtsp-tcp", true );
1775 /* We close the old RTSP session */
1776 vlc_timer_schedule(p_sys->timer, false, 0, 0);
1777 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1778 Medium::close( p_sys->ms );
1779 RTSPClient::close( p_sys->rtsp );
1781 for( i = 0; i < p_sys->i_track; i++ )
1783 live_track_t *tk = p_sys->track[i];
1785 if( tk->p_out_muxed ) vlc_demux_chained_Delete( tk->p_out_muxed );
1786 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1787 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1788 es_format_Clean( &tk->fmt );
1789 free( tk->p_buffer );
1790 free( tk );
1792 TAB_CLEAN( p_sys->i_track, p_sys->track );
1793 if( p_sys->p_out_asf ) vlc_demux_chained_Delete( p_sys->p_out_asf );
1795 p_sys->ms = NULL;
1796 p_sys->rtsp = NULL;
1797 p_sys->b_no_data = true;
1798 p_sys->i_no_data_ti = 0;
1799 p_sys->p_out_asf = NULL;
1801 /* Reopen rtsp client */
1802 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1804 msg_Err( p_demux, "Failed to connect with %s", p_sys->psz_pl_url );
1805 goto error;
1808 if( p_sys->p_sdp == NULL )
1810 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1811 goto error;
1814 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1816 msg_Err( p_demux, "Nothing to play for %s", p_sys->psz_pl_url );
1817 goto error;
1820 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1821 goto error;
1823 return VLC_SUCCESS;
1825 error:
1826 return VLC_EGENERIC;
1830 /*****************************************************************************
1832 *****************************************************************************/
1833 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1834 bool b_marker,
1835 const uint8_t *p_data, unsigned i_size )
1837 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1838 const unsigned i_packet_size = p_sys->asfh.i_min_data_packet_size;
1839 block_t *p_list = NULL;
1841 while( i_size >= 4 )
1843 unsigned i_flags = p_data[0];
1844 unsigned i_length_offset = (p_data[1] << 16) |
1845 (p_data[2] << 8) |
1846 (p_data[3] );
1847 bool b_length = i_flags & 0x40;
1848 bool b_relative_ts = i_flags & 0x20;
1849 bool b_duration = i_flags & 0x10;
1850 bool b_location_id = i_flags & 0x08;
1852 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1853 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1854 unsigned i_header_size = 4;
1855 if( b_relative_ts )
1856 i_header_size += 4;
1857 if( b_duration )
1858 i_header_size += 4;
1859 if( b_location_id )
1860 i_header_size += 4;
1862 if( i_header_size > i_size )
1864 msg_Warn( p_demux, "Invalid header size" );
1865 break;
1868 /* XXX
1869 * When b_length is true, the streams I found do not seems to respect
1870 * the documentation.
1871 * From them, I have failed to find which choice between '__MIN()' or
1872 * 'i_length_offset - i_header_size' is the right one.
1874 unsigned i_payload;
1875 if( b_length )
1876 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1877 else
1878 i_payload = i_size - i_header_size;
1880 if( !tk->p_asf_block )
1882 tk->p_asf_block = block_Alloc( i_packet_size );
1883 if( !tk->p_asf_block )
1884 break;
1885 tk->p_asf_block->i_buffer = 0;
1887 unsigned i_offset = b_length ? 0 : i_length_offset;
1888 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1890 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1891 tk->p_asf_block->i_buffer += i_payload;
1892 if( b_marker )
1894 /* We have a complete packet */
1895 tk->p_asf_block->i_buffer = i_packet_size;
1896 block_ChainAppend( &p_list, tk->p_asf_block );
1897 tk->p_asf_block = NULL;
1900 else
1902 /* Reset on broken stream */
1903 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1904 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1905 tk->p_asf_block->i_buffer = 0;
1908 /* */
1909 p_data += i_header_size + i_payload;
1910 i_size -= i_header_size + i_payload;
1912 return p_list;
1915 /*****************************************************************************
1917 *****************************************************************************/
1918 static void StreamRead( void *p_private, unsigned int i_size,
1919 unsigned int i_truncated_bytes, struct timeval pts,
1920 unsigned int duration )
1922 VLC_UNUSED( duration );
1924 live_track_t *tk = (live_track_t*)p_private;
1925 demux_t *p_demux = tk->p_demux;
1926 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1927 block_t *p_block;
1929 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1931 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1932 (int64_t)pts.tv_usec;
1934 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1935 i_pts &= INT64_C(0x00ffffffffffffff);
1937 /* Retrieve NPT for this pts */
1938 tk->f_npt = tk->sub->getNormalPlayTime(pts);
1940 if( tk->format == live_track_t::QUICKTIME_STREAM && tk->p_es == NULL )
1942 QuickTimeGenericRTPSource *qtRTPSource =
1943 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1944 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1945 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1947 /* Get codec information from the quicktime atoms :
1948 * http://developer.apple.com/quicktime/icefloe/dispatch026.html */
1949 if( tk->fmt.i_cat == VIDEO_ES ) {
1950 if( qtState.sdAtomSize < 16 + 32 )
1952 /* invalid */
1953 p_sys->event_data = 0xff;
1954 tk->waiting = 0;
1955 return;
1957 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1958 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1959 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1961 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1963 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1964 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1965 + qtRTPSource->qtState.sdAtomSize;
1966 while (pos+8 < endpos) {
1967 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1968 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1969 if( memcmp(pos+4, "avcC", 4) == 0 &&
1970 atomLength > 8 &&
1971 atomLength <= INT_MAX )
1973 tk->fmt.i_extra = atomLength-8;
1974 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1975 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1976 break;
1978 pos += atomLength;
1981 else
1983 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1984 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1985 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1988 else {
1989 if( qtState.sdAtomSize < 24 )
1991 /* invalid */
1992 p_sys->event_data = 0xff;
1993 tk->waiting = 0;
1994 return;
1996 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1997 tk->fmt.audio.i_bitspersample = (sdAtom[22] << 8) | sdAtom[23];
1999 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
2002 #if 0
2003 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
2004 i_size,
2005 pts.tv_sec * 1000000LL + pts.tv_usec );
2006 #endif
2008 /* grow buffer if it looks like buffer is too small, but don't eat
2009 * up all the memory on strange streams */
2010 if( i_truncated_bytes > 0 )
2012 if( tk->i_buffer < 2000000 )
2014 void *p_tmp;
2015 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
2016 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
2017 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
2018 if( p_tmp == NULL )
2020 msg_Warn( p_demux, "realloc failed" );
2022 else
2024 tk->p_buffer = (uint8_t*)p_tmp;
2025 tk->i_buffer *= 2;
2029 if( tk->b_discard_trunc )
2031 p_sys->event_data = 0xff;
2032 tk->waiting = 0;
2033 return;
2037 assert( i_size <= tk->i_buffer );
2039 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
2040 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
2042 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
2044 if( (p_block = block_Alloc( i_size + 1 )) )
2046 p_block->p_buffer[0] = amrSource->lastFrameHeader();
2047 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
2050 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
2052 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
2053 uint32_t header = h261Source->lastSpecialHeader();
2054 if( (p_block = block_Alloc( i_size + 4 )) )
2056 memcpy( p_block->p_buffer, &header, 4 );
2057 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
2060 else if( tk->fmt.i_codec == VLC_CODEC_H264 || tk->fmt.i_codec == VLC_CODEC_HEVC )
2062 if( tk->fmt.i_codec == VLC_CODEC_H264 && (tk->p_buffer[0] & 0x1f) >= 24 )
2063 msg_Warn( p_demux, "unsupported NAL type for H264" );
2064 else if( tk->fmt.i_codec == VLC_CODEC_HEVC && ((tk->p_buffer[0] & 0x7e)>>1) >= 48 )
2065 msg_Warn( p_demux, "unsupported NAL type for H265" );
2067 /* Normal NAL type */
2068 if( (p_block = block_Alloc( i_size + 4 )) )
2070 p_block->p_buffer[0] = 0x00;
2071 p_block->p_buffer[1] = 0x00;
2072 p_block->p_buffer[2] = 0x00;
2073 p_block->p_buffer[3] = 0x01;
2074 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
2077 else if( tk->format == live_track_t::ASF_STREAM )
2079 p_block = StreamParseAsf( p_demux, tk,
2080 tk->sub->rtpSource()->curPacketMarkerBit(),
2081 tk->p_buffer, i_size );
2083 else
2085 if( (p_block = block_Alloc( i_size )) )
2086 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
2089 /* No data sent. Always in sync then */
2090 if( !tk->b_rtcp_sync && tk->sub->rtpSource() &&
2091 tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
2093 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
2094 p_sys->b_rtcp_sync = tk->b_rtcp_sync = true;
2095 if( tk->i_pcr != VLC_TS_INVALID )
2097 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
2098 const int64_t i_max_diff = CLOCK_FREQ * (( tk->fmt.i_cat == SPU_ES ) ? 60 : 1);
2099 tk->b_flushing_discontinuity = (llabs(i_pts - tk->i_pcr) > i_max_diff);
2100 tk->i_pcr = i_pts;
2104 /* Update our global npt value */
2105 if( tk->f_npt > 0 &&
2106 ( tk->f_npt < p_sys->f_npt_length || p_sys->f_npt_length <= 0 ) )
2107 p_sys->f_npt = tk->f_npt;
2109 if( p_block )
2111 switch( tk->format )
2113 case live_track_t::ASF_STREAM:
2114 vlc_demux_chained_Send( p_sys->p_out_asf, p_block );
2115 break;
2116 case live_track_t::MULTIPLEXED_STREAM:
2117 vlc_demux_chained_Send( tk->p_out_muxed, p_block );
2118 break;
2119 default:
2120 if( i_pts != tk->i_lastpts )
2121 p_block->i_pts = VLC_TS_0 + i_pts;
2122 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
2123 switch( tk->fmt.i_codec )
2125 case VLC_CODEC_MPGV:
2126 case VLC_CODEC_H264:
2127 case VLC_CODEC_HEVC:
2128 case VLC_CODEC_VP8:
2129 p_block->i_dts = VLC_TS_INVALID;
2130 break;
2131 default:
2132 p_block->i_dts = VLC_TS_0 + i_pts;
2133 break;
2136 if( i_truncated_bytes )
2137 p_block->i_flags |= BLOCK_FLAG_CORRUPTED;
2139 if( unlikely(tk->i_next_block_flags) )
2141 p_block->i_flags |= tk->i_next_block_flags;
2142 tk->i_next_block_flags = 0;
2144 es_out_Send( p_demux->out, tk->p_es, p_block );
2145 if( i_pts > 0 )
2147 if( tk->i_pcr < i_pts )
2148 tk->i_pcr = i_pts;
2149 tk->i_lastpts = i_pts;
2151 break;
2155 /* warn that's ok */
2156 p_sys->event_data = 0xff;
2158 /* we have read data */
2159 tk->waiting = 0;
2160 p_sys->b_no_data = false;
2161 p_sys->i_no_data_ti = 0;
2164 /*****************************************************************************
2166 *****************************************************************************/
2167 static void StreamClose( void *p_private )
2169 live_track_t *tk = (live_track_t*)p_private;
2170 demux_t *p_demux = tk->p_demux;
2171 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2172 tk->state = live_track_t::STATE_IGNORED;
2173 p_sys->event_rtsp = 0xff;
2174 p_sys->event_data = 0xff;
2176 if( tk->p_es )
2177 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
2179 int nb_tracks = 0;
2180 for( int i = 0; i < p_sys->i_track; i++ )
2182 if( p_sys->track[i]->state == live_track_t::STATE_SELECTED )
2183 nb_tracks++;
2185 msg_Dbg( p_demux, "RTSP track Close, %d track remaining", nb_tracks );
2186 if( !nb_tracks )
2187 p_sys->b_error = true;
2191 /*****************************************************************************
2193 *****************************************************************************/
2194 static void TaskInterruptRTSP( void *p_private )
2196 demux_t *p_demux = (demux_t*)p_private;
2197 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2199 /* Avoid lock */
2200 p_sys->event_rtsp = 0xff;
2203 static void TaskInterruptData( void *p_private )
2205 demux_t *p_demux = (demux_t*)p_private;
2206 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2208 p_sys->i_no_data_ti++;
2210 /* Avoid lock */
2211 p_sys->event_data = 0xff;
2214 /*****************************************************************************
2216 *****************************************************************************/
2217 static void TimeoutPrevention( void *p_data )
2219 demux_t *p_demux = (demux_t *) p_data;
2220 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2221 char *bye = NULL;
2223 /* Protect Live555 from us calling their functions simultaneously
2224 with Demux() or Control() */
2225 vlc_mutex_locker locker(&p_sys->timeout_mutex);
2227 /* If the timer fires while the demuxer owns the lock, and the demuxer
2228 * then torns the session down, the pointers will become NULL. By the time
2229 * this timer callback obtains the callback, either a new session was
2230 * created and the timer is rescheduled, or the pointers are still NULL
2231 * and the timer is descheduled. In the second case, bail out (then wait
2232 * for the timer to be rescheduled or destroyed). In the first case, this
2233 * might send an early refresh - that´s harmless but suboptimal (FIXME). */
2234 if( p_sys->rtsp == NULL || p_sys->ms == NULL )
2235 return;
2237 bool use_get_param = p_sys->b_get_param;
2239 /* Use GET_PARAMETERS if supported. wmserver dialect supports
2240 * it, but does not report this properly. */
2241 if( var_GetBool( p_demux, "rtsp-wmserver" ) )
2242 use_get_param = true;
2244 if( use_get_param )
2245 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms,
2246 default_live555_callback, bye );
2247 else
2248 p_sys->rtsp->sendOptionsCommand( default_live555_callback, NULL );
2250 if( !wait_Live555_response( p_demux ) )
2252 msg_Err( p_demux, "keep-alive failed: %s",
2253 p_sys->env->getResultMsg() );
2254 /* Just continue, worst case is we get timed out later */
2258 /*****************************************************************************
2260 *****************************************************************************/
2261 static int ParseASF( demux_t *p_demux )
2263 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2265 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
2266 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2267 char *psz_end;
2268 block_t *p_header;
2270 /* Parse the asf header */
2271 if( psz_asf == NULL )
2272 return VLC_EGENERIC;
2274 psz_asf += strlen( psz_marker );
2275 psz_asf = strdup( psz_asf ); /* Duplicate it */
2276 psz_end = strchr( psz_asf, '\n' );
2278 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2279 *psz_end-- = '\0';
2281 if( psz_asf >= psz_end )
2283 free( psz_asf );
2284 return VLC_EGENERIC;
2287 /* Always smaller */
2288 p_header = block_Alloc( psz_end - psz_asf );
2289 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2290 p_header->i_buffer, psz_asf );
2291 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2292 if( p_header->i_buffer <= 0 )
2294 free( psz_asf );
2295 return VLC_EGENERIC;
2298 /* Parse it to get packet size */
2299 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2301 /* Send it to demuxer */
2302 vlc_demux_chained_Send( p_sys->p_out_asf, p_header );
2304 free( psz_asf );
2305 return VLC_SUCCESS;
2309 static unsigned char* parseH264ConfigStr( char const* configStr,
2310 unsigned int& configSize )
2312 char *dup, *psz;
2313 size_t i_records = 1;
2315 configSize = 0;
2317 if( configStr == NULL || *configStr == '\0' )
2318 return NULL;
2320 psz = dup = strdup( configStr );
2322 /* Count the number of commas */
2323 for( psz = dup; *psz != '\0'; ++psz )
2325 if( *psz == ',')
2327 ++i_records;
2328 *psz = '\0';
2332 size_t configMax = 5*strlen(dup);
2333 unsigned char *cfg = new unsigned char[configMax];
2334 psz = dup;
2335 for( size_t i = 0; i < i_records; ++i )
2337 cfg[configSize++] = 0x00;
2338 cfg[configSize++] = 0x00;
2339 cfg[configSize++] = 0x00;
2340 cfg[configSize++] = 0x01;
2342 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2343 configMax-configSize, psz );
2344 psz += strlen(psz)+1;
2347 free( dup );
2348 return cfg;
2351 static uint8_t *parseVorbisConfigStr( char const* configStr,
2352 unsigned int& configSize )
2354 configSize = 0;
2355 if( configStr == NULL || *configStr == '\0' )
2356 return NULL;
2357 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1332115200 // 2012.03.20
2358 unsigned char *p_cfg = base64Decode( configStr, configSize );
2359 #else
2360 char* configStr_dup = strdup( configStr );
2361 unsigned char *p_cfg = base64Decode( configStr_dup, configSize );
2362 free( configStr_dup );
2363 #endif
2364 uint8_t *p_extra = NULL;
2365 /* skip header count, ident number and length (cf. RFC 5215) */
2366 const unsigned int headerSkip = 9;
2367 if( configSize > headerSkip && ((uint8_t*)p_cfg)[3] == 1 )
2369 configSize -= headerSkip;
2370 p_extra = (uint8_t*)xmalloc( configSize );
2371 memcpy( p_extra, p_cfg+headerSkip, configSize );
2373 delete[] p_cfg;
2374 return p_extra;
2377 static char *passwordLessURL( vlc_url_t *p_url )
2379 vlc_url_t url;
2381 memcpy( &url, p_url, sizeof( vlc_url_t ) );
2383 url.psz_username = NULL;
2384 url.psz_password = NULL;
2385 if( url.i_port == 0 )
2386 url.i_port = 554;
2387 return vlc_uri_compose( &url );