contrib: soxr: enable by default
[vlc.git] / modules / access / live555.cpp
blobe7b7a83090ddd8e10dd6aac9ed4d37035422aff1
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", 300 )
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( p_sys->rtsp && i_client_port != -1 )
779 sub->setClientPortNum( i_client_port );
780 i_client_port += 2;
783 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
784 bInit = sub->initiate( 0 );
785 else
786 bInit = sub->initiate();
788 if( !bInit )
790 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
791 sub->mediumName(), sub->codecName(),
792 p_sys->env->getResultMsg() );
794 else
796 if( sub->rtpSource() != NULL )
798 int fd = sub->rtpSource()->RTPgs()->socketNum();
800 /* Increase the buffer size */
801 if( i_receive_buffer > 0 )
802 increaseReceiveBufferTo( *p_sys->env, fd, i_receive_buffer );
804 /* Increase the RTP reorder timebuffer just a bit */
805 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
807 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
808 sub->codecName() );
810 /* Issue the SETUP */
811 if( p_sys->rtsp )
813 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
814 toBool( b_rtsp_tcp ),
815 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
816 if( !wait_Live555_response( p_demux ) )
818 /* if we get an unsupported transport error, toggle TCP
819 * use and try again */
820 if( p_sys->i_live555_ret == 461 )
821 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
822 !toBool( b_rtsp_tcp ), False );
823 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
825 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
826 sub->mediumName(), sub->codecName(),
827 p_sys->env->getResultMsg() );
828 continue;
830 else
832 var_SetBool( p_demux, "rtsp-tcp", true );
833 b_rtsp_tcp = true;
838 /* Check if we will receive data from this subsession for
839 * this track */
840 if( sub->readSource() == NULL ) continue;
841 if( !p_sys->b_multicast )
843 /* We need different rollover behaviour for multicast */
844 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
847 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
848 if( !tk )
850 delete iter;
851 return VLC_ENOMEM;
853 tk->p_demux = p_demux;
854 tk->sub = sub;
855 tk->p_es = NULL;
856 tk->format = live_track_t::SINGLE_STREAM;
857 tk->p_asf_block = NULL;
858 tk->b_discard_trunc = false;
859 tk->p_out_muxed = NULL;
860 tk->waiting = 0;
861 tk->b_rtcp_sync = false;
862 tk->b_flushing_discontinuity = false;
863 tk->i_next_block_flags = 0;
864 tk->i_lastpts = VLC_TS_INVALID;
865 tk->i_pcr = VLC_TS_INVALID;
866 tk->f_npt = 0.;
867 tk->state = live_track_t::STATE_SELECTED;
868 tk->i_buffer = i_frame_buffer;
869 tk->p_buffer = (uint8_t *)malloc( i_frame_buffer );
871 if( !tk->p_buffer )
873 free( tk );
874 delete iter;
875 return VLC_ENOMEM;
878 /* Value taken from mplayer */
879 if( !strcmp( sub->mediumName(), "audio" ) )
881 es_format_Init( &tk->fmt, AUDIO_ES, VLC_CODEC_UNKNOWN );
882 tk->fmt.audio.i_channels = sub->numChannels();
883 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
885 if( !strcmp( sub->codecName(), "MPA" ) ||
886 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
887 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
889 tk->fmt.i_codec = VLC_CODEC_MPGA;
890 tk->fmt.audio.i_rate = 0;
892 else if( !strcmp( sub->codecName(), "AC3" ) )
894 tk->fmt.i_codec = VLC_CODEC_A52;
895 tk->fmt.audio.i_rate = 0;
897 else if( !strcmp( sub->codecName(), "L16" ) )
899 tk->fmt.i_codec = VLC_CODEC_S16B;
900 tk->fmt.audio.i_bitspersample = 16;
902 else if( !strcmp( sub->codecName(), "L20" ) )
904 tk->fmt.i_codec = VLC_CODEC_S20B;
905 tk->fmt.audio.i_bitspersample = 20;
907 else if( !strcmp( sub->codecName(), "L24" ) )
909 tk->fmt.i_codec = VLC_CODEC_S24B;
910 tk->fmt.audio.i_bitspersample = 24;
912 else if( !strcmp( sub->codecName(), "L8" ) )
914 tk->fmt.i_codec = VLC_CODEC_U8;
915 tk->fmt.audio.i_bitspersample = 8;
917 else if( !strcmp( sub->codecName(), "DAT12" ) )
919 tk->fmt.i_codec = VLC_CODEC_DAT12;
920 tk->fmt.audio.i_bitspersample = 12;
922 else if( !strcmp( sub->codecName(), "PCMU" ) )
924 tk->fmt.i_codec = VLC_CODEC_MULAW;
925 tk->fmt.audio.i_bitspersample = 8;
927 else if( !strcmp( sub->codecName(), "PCMA" ) )
929 tk->fmt.i_codec = VLC_CODEC_ALAW;
930 tk->fmt.audio.i_bitspersample = 8;
932 else if( !strncmp( sub->codecName(), "G726", 4 ) )
934 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
935 tk->fmt.audio.i_rate = 8000;
936 tk->fmt.audio.i_channels = 1;
937 if( !strcmp( sub->codecName()+5, "40" ) )
938 tk->fmt.i_bitrate = 40000;
939 else if( !strcmp( sub->codecName()+5, "32" ) )
940 tk->fmt.i_bitrate = 32000;
941 else if( !strcmp( sub->codecName()+5, "24" ) )
942 tk->fmt.i_bitrate = 24000;
943 else if( !strcmp( sub->codecName()+5, "16" ) )
944 tk->fmt.i_bitrate = 16000;
946 else if( !strcmp( sub->codecName(), "AMR" ) )
948 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
950 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
952 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
954 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
956 unsigned int i_extra;
957 uint8_t *p_extra;
959 tk->fmt.i_codec = VLC_CODEC_MP4A;
961 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
962 i_extra ) ) )
964 tk->fmt.i_extra = i_extra;
965 tk->fmt.p_extra = xmalloc( i_extra );
966 memcpy( tk->fmt.p_extra, p_extra, i_extra );
967 delete[] p_extra;
969 /* Because the "faad" decoder does not handle the LATM
970 * data length field at the start of each returned LATM
971 * frame, tell the RTP source to omit. */
972 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
974 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
976 unsigned int i_extra;
977 uint8_t *p_extra;
979 tk->fmt.i_codec = VLC_CODEC_MP4A;
981 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
982 i_extra ) ) )
984 tk->fmt.i_extra = i_extra;
985 tk->fmt.p_extra = xmalloc( i_extra );
986 memcpy( tk->fmt.p_extra, p_extra, i_extra );
987 delete[] p_extra;
990 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
992 tk->format = live_track_t::ASF_STREAM;
993 if( p_sys->p_out_asf == NULL )
994 p_sys->p_out_asf =
995 vlc_demux_chained_New( VLC_OBJECT(p_demux), "asf",
996 p_demux->out );
998 else if( !strcmp( sub->codecName(), "X-QT" ) ||
999 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
1001 tk->format = live_track_t::QUICKTIME_STREAM;
1003 else if( !strcmp( sub->codecName(), "SPEEX" ) )
1005 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
1007 else if( !strcmp( sub->codecName(), "VORBIS" ) )
1009 tk->fmt.i_codec = VLC_CODEC_VORBIS;
1010 unsigned int i_extra;
1011 unsigned char *p_extra;
1012 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
1013 i_extra ) ) )
1015 tk->fmt.i_extra = i_extra;
1016 tk->fmt.p_extra = p_extra;
1018 else
1019 msg_Warn( p_demux,"Missing or unsupported vorbis header." );
1021 else if( !strcmp( sub->codecName(), "OPUS" ) )
1023 tk->fmt.i_codec = VLC_CODEC_OPUS;
1026 else if( !strcmp( sub->mediumName(), "video" ) )
1028 es_format_Init( &tk->fmt, VIDEO_ES, VLC_CODEC_UNKNOWN );
1029 if( !strcmp( sub->codecName(), "MPV" ) )
1031 tk->fmt.i_codec = VLC_CODEC_MPGV;
1032 tk->fmt.b_packetized = false;
1034 else if( !strcmp( sub->codecName(), "H263" ) ||
1035 !strcmp( sub->codecName(), "H263-1998" ) ||
1036 !strcmp( sub->codecName(), "H263-2000" ) )
1038 tk->fmt.i_codec = VLC_CODEC_H263;
1040 else if( !strcmp( sub->codecName(), "H261" ) )
1042 tk->fmt.i_codec = VLC_CODEC_H261;
1044 else if( !strcmp( sub->codecName(), "H264" ) )
1046 unsigned int i_extra = 0;
1047 uint8_t *p_extra = NULL;
1049 tk->fmt.i_codec = VLC_CODEC_H264;
1050 tk->fmt.b_packetized = false;
1052 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
1053 i_extra ) ) )
1055 tk->fmt.i_extra = i_extra;
1056 tk->fmt.p_extra = xmalloc( i_extra );
1057 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1059 delete[] p_extra;
1062 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1393372800 // 2014.02.26
1063 else if( !strcmp( sub->codecName(), "H265" ) )
1065 unsigned int i_extra1 = 0, i_extra2 = 0, i_extra3 = 0, i_extraTot;
1066 uint8_t *p_extra1 = NULL, *p_extra2 = NULL, *p_extra3 = NULL;
1068 tk->fmt.i_codec = VLC_CODEC_HEVC;
1069 tk->fmt.b_packetized = false;
1071 p_extra1 = parseH264ConfigStr( sub->fmtp_spropvps(), i_extra1 );
1072 p_extra2 = parseH264ConfigStr( sub->fmtp_spropsps(), i_extra2 );
1073 p_extra3 = parseH264ConfigStr( sub->fmtp_sproppps(), i_extra3 );
1074 i_extraTot = i_extra1 + i_extra2 + i_extra3;
1075 if( i_extraTot > 0 )
1077 tk->fmt.i_extra = i_extraTot;
1078 tk->fmt.p_extra = xmalloc( i_extraTot );
1079 if( p_extra1 )
1081 memcpy( tk->fmt.p_extra, p_extra1, i_extra1 );
1083 if( p_extra2 )
1085 memcpy( ((char*)tk->fmt.p_extra)+i_extra1, p_extra2, i_extra2 );
1087 if( p_extra3 )
1089 memcpy( ((char*)tk->fmt.p_extra)+i_extra1+i_extra2, p_extra3, i_extra3 );
1092 delete[] p_extra1; delete[] p_extra2; delete[] p_extra3;
1095 #endif
1096 else if( !strcmp( sub->codecName(), "JPEG" ) )
1098 tk->fmt.i_codec = VLC_CODEC_MJPG;
1100 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1102 unsigned int i_extra;
1103 uint8_t *p_extra;
1105 tk->fmt.i_codec = VLC_CODEC_MP4V;
1107 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1108 i_extra ) ) )
1110 tk->fmt.i_extra = i_extra;
1111 tk->fmt.p_extra = xmalloc( i_extra );
1112 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1113 delete[] p_extra;
1116 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1117 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1118 !strcmp( sub->codecName(), "X-QDM" ) ||
1119 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1120 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1122 tk->format = live_track_t::QUICKTIME_STREAM;
1124 else if( !strcmp( sub->codecName(), "MP2T" ) )
1126 tk->format = live_track_t::MULTIPLEXED_STREAM;
1127 tk->p_out_muxed =
1128 vlc_demux_chained_New( VLC_OBJECT(p_demux), "ts",
1129 p_demux->out );
1131 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1132 !strcmp( sub->codecName(), "MP1S" ) )
1134 tk->format = live_track_t::MULTIPLEXED_STREAM;
1135 tk->p_out_muxed =
1136 vlc_demux_chained_New( VLC_OBJECT(p_demux), "ps",
1137 p_demux->out );
1139 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1141 tk->format = live_track_t::ASF_STREAM;
1142 if( p_sys->p_out_asf == NULL )
1143 p_sys->p_out_asf =
1144 vlc_demux_chained_New( VLC_OBJECT(p_demux),
1145 "asf", p_demux->out );
1147 else if( !strcmp( sub->codecName(), "DV" ) )
1149 tk->format = live_track_t::MULTIPLEXED_STREAM;
1150 tk->b_discard_trunc = true;
1151 tk->p_out_muxed =
1152 vlc_demux_chained_New( VLC_OBJECT(p_demux), "rawdv",
1153 p_demux->out );
1155 else if( !strcmp( sub->codecName(), "VP8" ) )
1157 tk->fmt.i_codec = VLC_CODEC_VP8;
1159 else if( !strcmp( sub->codecName(), "THEORA" ) )
1161 tk->fmt.i_codec = VLC_CODEC_THEORA;
1162 unsigned int i_extra;
1163 unsigned char *p_extra;
1164 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
1165 i_extra ) ) )
1167 tk->fmt.i_extra = i_extra;
1168 tk->fmt.p_extra = p_extra;
1170 else
1171 msg_Warn( p_demux,"Missing or unsupported theora header." );
1174 else if( !strcmp( sub->mediumName(), "text" ) )
1176 es_format_Init( &tk->fmt, SPU_ES, VLC_CODEC_UNKNOWN );
1178 if( !strcmp( sub->codecName(), "T140" ) )
1180 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1184 /* Try and parse a=lang: attribute */
1185 p_lang = strstr( sub->savedSDPLines(), "a=lang:" );
1186 if( !p_lang )
1187 p_lang = p_sess_lang;
1189 if( p_lang )
1191 unsigned i_lang_len;
1192 p_lang += 7;
1193 i_lang_len = strcspn( p_lang, " \r\n" );
1194 tk->fmt.psz_language = strndup( p_lang, i_lang_len );
1197 if( tk->format == live_track_t::SINGLE_STREAM )
1199 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1202 if( sub->rtcpInstance() != NULL )
1204 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1207 if( tk->p_es ||
1208 tk->format == live_track_t::QUICKTIME_STREAM ||
1209 (tk->format == live_track_t::MULTIPLEXED_STREAM && tk->p_out_muxed ) ||
1210 (tk->format == live_track_t::ASF_STREAM && p_sys->p_out_asf ) )
1212 TAB_APPEND_CAST( (live_track_t **), p_sys->i_track, p_sys->track, tk );
1214 else
1216 /* BUG ??? */
1217 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1218 es_format_Clean( &tk->fmt );
1219 free( tk );
1223 delete iter;
1224 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1226 /* Retrieve the starttime if possible */
1227 p_sys->f_npt_start = p_sys->ms->playStartTime();
1229 /* Retrieve the duration if possible */
1230 p_sys->f_npt_length = p_sys->ms->playEndTime();
1232 /* */
1233 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1235 /* */
1236 p_sys->b_no_data = true;
1237 p_sys->i_no_data_ti = 0;
1238 p_sys->b_rtcp_sync = false;
1239 p_sys->i_pcr = VLC_TS_INVALID;
1241 return i_return;
1244 /*****************************************************************************
1245 * Play: starts the actual playback of the stream
1246 *****************************************************************************/
1247 static int Play( demux_t *p_demux )
1249 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1251 if( p_sys->rtsp )
1253 /* The PLAY */
1254 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_npt_start, -1, 1 );
1256 if( !wait_Live555_response(p_demux) )
1258 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1259 return VLC_EGENERIC;
1262 /* Retrieve the timeout value and set up a timeout prevention thread */
1263 int timeout = p_sys->rtsp->sessionTimeoutParameter();
1264 if( timeout <= 2 )
1265 timeout = 60; /* default value from RFC2326 */
1266 msg_Dbg( p_demux, "We have a timeout of %d seconds", timeout );
1268 mtime_t interval = (timeout - 2) * CLOCK_FREQ;
1269 vlc_timer_schedule( p_sys->timer, false, interval, interval);
1271 p_sys->i_pcr = VLC_TS_INVALID;
1273 /* Retrieve the starttime if possible */
1274 p_sys->f_npt_start = p_sys->ms->playStartTime();
1275 if( p_sys->ms->playEndTime() > 0 )
1276 p_sys->f_npt_length = p_sys->ms->playEndTime();
1278 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1279 return VLC_SUCCESS;
1282 /*****************************************************************************
1283 * HasSharedSession: returns if the session is shared with another stream
1284 *****************************************************************************/
1285 static bool HasSharedSession( MediaSubsession *session )
1287 MediaSubsessionIterator *it =
1288 new MediaSubsessionIterator( session->parentSession() );
1289 MediaSubsession *subsession;
1290 bool b_shared = false;
1291 while( (subsession = it->next()) != NULL )
1293 if( session == subsession )
1294 continue;
1295 if( !strcmp( session->sessionId(), subsession->sessionId() ) )
1297 b_shared = true;
1298 break;
1301 delete it;
1302 return b_shared;
1305 /*****************************************************************************
1306 * ResumeTrack: setup or resume a silenced track
1307 *****************************************************************************/
1308 static void ResumeTrack( demux_t *p_demux, live_track_t *tk )
1310 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1312 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1313 var_GetBool( p_demux, "rtsp-http" );
1314 p_sys->rtsp->sendSetupCommand( *tk->sub, default_live555_callback, False,
1315 toBool( b_rtsp_tcp ),
1316 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
1317 if( !wait_Live555_response( p_demux ) )
1319 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
1320 tk->sub->mediumName(), tk->sub->codecName(),
1321 p_sys->env->getResultMsg() );
1323 else
1325 p_sys->rtsp->sendPlayCommand( *tk->sub, default_live555_callback, -1, -1, p_sys->ms->scale() );
1326 if( !wait_Live555_response(p_demux) )
1328 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1329 if( (p_sys->capabilities & CAP_SUBSESSION_TEARDOWN) ||
1330 !HasSharedSession( tk->sub ) )
1332 tk->state = live_track_t::STATE_TEARDOWN;
1333 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1336 else
1337 tk->state = live_track_t::STATE_SELECTED;
1341 /*****************************************************************************
1342 * Demux:
1343 *****************************************************************************/
1344 static int Demux( demux_t *p_demux )
1346 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1347 TaskToken task;
1349 bool b_send_pcr = true;
1350 int i;
1352 /* Protect Live555 from simultaneous calls in TimeoutPrevention()
1353 during pause */
1354 vlc_mutex_locker locker(&p_sys->timeout_mutex);
1356 for( i = 0; i < p_sys->i_track; i++ )
1358 live_track_t *tk = p_sys->track[i];
1360 if( tk->p_es )
1362 bool b;
1363 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1364 if( !b && (tk->state == live_track_t::STATE_SELECTED) && p_sys->rtsp )
1366 if( (p_sys->capabilities & CAP_SUBSESSION_TEARDOWN) ||
1367 !HasSharedSession( tk->sub ) )
1369 tk->state = live_track_t::STATE_TEARDOWN;
1370 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1372 else tk->state = live_track_t::STATE_IGNORED;
1374 else if( b && tk->state != live_track_t::STATE_SELECTED )
1376 if( tk->state != live_track_t::STATE_IGNORED )
1377 ResumeTrack( p_demux, tk );
1378 else
1379 tk->state = live_track_t::STATE_SELECTED;
1381 if( tk->state != live_track_t::STATE_SELECTED )
1382 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1386 if( tk->format == live_track_t::ASF_STREAM ||
1387 tk->format == live_track_t::MULTIPLEXED_STREAM )
1389 b_send_pcr = false;
1393 /* First warn we want to read data */
1394 p_sys->event_data = 0;
1395 for( i = 0; i < p_sys->i_track; i++ )
1397 live_track_t *tk = p_sys->track[i];
1399 if( tk->waiting == 0 )
1401 tk->waiting = 1;
1402 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1403 StreamRead, tk, StreamClose, tk );
1406 /* Create a task that will be called if we wait more than 300ms */
1407 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1409 /* Do the read */
1410 p_sys->scheduler->doEventLoop( &p_sys->event_data );
1412 /* remove the task */
1413 p_sys->scheduler->unscheduleDelayedTask( task );
1415 if( b_send_pcr )
1417 mtime_t i_minpcr = VLC_TS_INVALID;
1418 bool b_need_flush = false;
1420 /* Check for gap in pts value */
1421 for( i = 0; i < p_sys->i_track; i++ )
1423 live_track_t *tk = p_sys->track[i];
1425 if( tk->state != live_track_t::STATE_SELECTED ||
1426 (p_sys->b_rtcp_sync && !tk->b_rtcp_sync) )
1427 continue;
1429 /* Check for gap in pts value */
1430 b_need_flush |= (tk->b_flushing_discontinuity);
1432 if( i_minpcr == VLC_TS_INVALID || ( tk->i_pcr != VLC_TS_INVALID && i_minpcr > tk->i_pcr ) )
1433 i_minpcr = tk->i_pcr;
1436 if( p_sys->i_pcr > VLC_TS_INVALID && b_need_flush )
1438 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1439 p_sys->i_pcr = i_minpcr;
1440 p_sys->f_npt = 0.;
1442 for( i = 0; i < p_sys->i_track; i++ )
1444 live_track_t *tk = p_sys->track[i];
1445 tk->i_lastpts = VLC_TS_INVALID;
1446 tk->i_pcr = VLC_TS_INVALID;
1447 tk->f_npt = 0.;
1448 tk->b_flushing_discontinuity = false;
1449 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1451 if( p_sys->i_pcr != VLC_TS_INVALID )
1452 es_out_SetPCR( p_demux->out, VLC_TS_0 +
1453 __MAX(0, p_sys->i_pcr - PCR_OFF) );
1455 else if( p_sys->i_pcr == VLC_TS_INVALID ||
1456 i_minpcr > p_sys->i_pcr + PCR_OBS )
1458 p_sys->i_pcr = __MAX(0, i_minpcr - PCR_OFF);
1459 if( p_sys->i_pcr != VLC_TS_INVALID )
1460 es_out_SetPCR( p_demux->out, VLC_TS_0 + p_sys->i_pcr );
1464 if( p_sys->b_multicast && p_sys->b_no_data &&
1465 ( p_sys->i_no_data_ti > 120 ) )
1467 /* FIXME Make this configurable
1468 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1469 return 0;
1472 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1473 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1475 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1476 var_GetBool( p_demux, "rtsp-http" );
1478 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1480 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1481 if( RollOverTcp( p_demux ) )
1483 msg_Err( p_demux, "TCP rollover failed, aborting" );
1484 return 0;
1486 return 1;
1488 msg_Err( p_demux, "no data received in 10s, aborting" );
1489 return 0;
1491 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1492 ( p_sys->i_no_data_ti > 34 ) )
1494 /* EOF ? */
1495 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1496 return 0;
1498 return p_sys->b_error ? 0 : 1;
1501 /*****************************************************************************
1502 * Control:
1503 *****************************************************************************/
1504 static int Control( demux_t *p_demux, int i_query, va_list args )
1506 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1507 int64_t *pi64, i64;
1508 double *pf, f;
1509 bool *pb;
1511 vlc_mutex_locker locker(&p_sys->timeout_mutex); /* (see same in Demux) */
1513 switch( i_query )
1515 case DEMUX_GET_TIME:
1516 pi64 = va_arg( args, int64_t * );
1517 if( p_sys->f_npt > 0 )
1519 *pi64 = (int64_t)(p_sys->f_npt * 1000000.);
1520 return VLC_SUCCESS;
1522 return VLC_EGENERIC;
1524 case DEMUX_GET_LENGTH:
1525 pi64 = va_arg( args, int64_t * );
1526 if( p_sys->f_npt_length > 0 )
1528 double d_length = p_sys->f_npt_length * 1000000.0;
1529 if( d_length >= INT64_MAX )
1530 *pi64 = INT64_MAX;
1531 else
1532 *pi64 = (int64_t)d_length;
1533 return VLC_SUCCESS;
1535 return VLC_EGENERIC;
1537 case DEMUX_GET_POSITION:
1538 pf = va_arg( args, double * );
1539 if( (p_sys->f_npt_length > 0) && (p_sys->f_npt > 0) )
1541 *pf = p_sys->f_npt / p_sys->f_npt_length;
1542 return VLC_SUCCESS;
1544 return VLC_EGENERIC;
1546 case DEMUX_SET_POSITION:
1547 case DEMUX_SET_TIME:
1548 if( p_sys->rtsp && (p_sys->f_npt_length > 0) )
1550 float time;
1552 if( (i_query == DEMUX_SET_TIME) && (p_sys->f_npt > 0) )
1554 i64 = va_arg( args, int64_t );
1555 time = (float)(i64 / 1000000.0); /* in second */
1557 else if( i_query == DEMUX_SET_TIME )
1558 return VLC_EGENERIC;
1559 else
1561 f = va_arg( args, double );
1562 time = f * p_sys->f_npt_length; /* in second */
1565 if( p_sys->b_paused )
1567 p_sys->f_seek_request = time;
1568 return VLC_SUCCESS;
1571 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1573 if( !wait_Live555_response( p_demux ) )
1575 msg_Err( p_demux, "PAUSE before seek failed %s",
1576 p_sys->env->getResultMsg() );
1577 return VLC_EGENERIC;
1580 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1582 if( !wait_Live555_response( p_demux ) )
1584 msg_Err( p_demux, "seek PLAY failed %s",
1585 p_sys->env->getResultMsg() );
1586 return VLC_EGENERIC;
1588 p_sys->i_pcr = VLC_TS_INVALID;
1590 for( int i = 0; i < p_sys->i_track; i++ )
1592 p_sys->track[i]->b_rtcp_sync = false;
1593 p_sys->track[i]->i_lastpts = VLC_TS_INVALID;
1594 p_sys->track[i]->i_pcr = VLC_TS_INVALID;
1597 /* Retrieve the starttime if possible */
1598 p_sys->f_npt = p_sys->f_npt_start = p_sys->ms->playStartTime();
1600 /* Retrieve the duration if possible */
1601 if( p_sys->ms->playEndTime() > 0 )
1602 p_sys->f_npt_length = p_sys->ms->playEndTime();
1604 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1605 return VLC_SUCCESS;
1607 return VLC_EGENERIC;
1609 /* Special for access_demux */
1610 case DEMUX_CAN_PAUSE:
1611 case DEMUX_CAN_SEEK:
1612 pb = va_arg( args, bool * );
1613 if( p_sys->rtsp && p_sys->f_npt_length > 0 )
1614 /* Not always true, but will be handled in SET_PAUSE_STATE */
1615 *pb = true;
1616 else
1617 *pb = false;
1618 return VLC_SUCCESS;
1620 case DEMUX_CAN_CONTROL_PACE:
1621 pb = va_arg( args, bool * );
1623 #if 1 /* Disable for now until we have a clock synchro algo
1624 * which works with something else than MPEG over UDP */
1625 *pb = false;
1626 #else
1627 *pb = true;
1628 #endif
1629 return VLC_SUCCESS;
1631 case DEMUX_CAN_CONTROL_RATE:
1632 pb = va_arg( args, bool * );
1634 *pb = (p_sys->rtsp != NULL) &&
1635 (p_sys->f_npt_length > 0) &&
1636 (p_sys->capabilities & CAP_RATE_CONTROL);
1637 return VLC_SUCCESS;
1639 case DEMUX_SET_RATE:
1641 int *pi_int;
1642 double f_scale, f_old_scale;
1644 if( !p_sys->rtsp || (p_sys->f_npt_length <= 0) ||
1645 !(p_sys->capabilities & CAP_RATE_CONTROL) )
1646 return VLC_EGENERIC;
1648 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1649 * supports Scale:
1651 * "[...] should try to approximate the viewing rate, but
1652 * may restrict the range of scale values that it supports.
1653 * The response MUST contain the actual scale value chosen
1654 * by the server."
1656 * Scale = 1 indicates normal play
1657 * Scale > 1 indicates fast forward
1658 * Scale < 1 && Scale > 0 indicates slow motion
1659 * Scale < 0 value indicates rewind
1662 pi_int = va_arg( args, int * );
1663 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1664 f_old_scale = p_sys->ms->scale();
1666 /* Passing -1 for the start and end time will mean liveMedia won't
1667 * create a Range: section for the RTSP message. The server should
1668 * pick up from the current position */
1669 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1671 if( !wait_Live555_response( p_demux ) )
1673 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1674 p_sys->env->getResultMsg() );
1675 return VLC_EGENERIC;
1678 if( p_sys->ms->scale() == f_old_scale )
1680 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1681 p_sys->ms->scale() );
1682 return VLC_EGENERIC;
1685 /* ReSync the stream */
1686 p_sys->f_npt_start = 0;
1687 p_sys->i_pcr = VLC_TS_INVALID;
1688 p_sys->f_npt = 0.0;
1690 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1691 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1692 return VLC_SUCCESS;
1695 case DEMUX_SET_PAUSE_STATE:
1697 bool b_pause = (bool)va_arg( args, int );
1698 if( p_sys->rtsp == NULL )
1699 return VLC_EGENERIC;
1701 if( b_pause == p_sys->b_paused )
1702 return VLC_SUCCESS;
1703 if( b_pause )
1704 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1705 else
1706 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1707 -1.0f, p_sys->ms->scale() );
1709 if( !wait_Live555_response( p_demux ) )
1711 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1712 return VLC_EGENERIC;
1714 p_sys->f_seek_request = -1;
1715 p_sys->b_paused = b_pause;
1717 if( !p_sys->b_paused )
1719 for( int i = 0; i < p_sys->i_track; i++ )
1721 live_track_t *tk = p_sys->track[i];
1722 tk->b_rtcp_sync = false;
1723 tk->b_flushing_discontinuity = false;
1724 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1725 tk->i_lastpts = VLC_TS_INVALID;
1726 tk->i_pcr = VLC_TS_INVALID;
1728 p_sys->i_pcr = VLC_TS_INVALID;
1729 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1732 /* Reset data received counter */
1733 p_sys->i_no_data_ti = 0;
1735 /* Retrieve the starttime if possible */
1736 p_sys->f_npt_start = p_sys->ms->playStartTime();
1738 /* Retrieve the duration if possible */
1739 if( p_sys->ms->playEndTime() )
1740 p_sys->f_npt_length = p_sys->ms->playEndTime();
1742 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1744 return VLC_SUCCESS;
1746 case DEMUX_GET_TITLE_INFO:
1747 case DEMUX_SET_TITLE:
1748 case DEMUX_SET_SEEKPOINT:
1749 return VLC_EGENERIC;
1751 case DEMUX_GET_PTS_DELAY:
1752 pi64 = va_arg( args, int64_t * );
1753 *pi64 = INT64_C(1000)
1754 * var_InheritInteger( p_demux, "network-caching" );
1755 return VLC_SUCCESS;
1757 default:
1758 return VLC_EGENERIC;
1762 /*****************************************************************************
1763 * RollOverTcp: reopen the rtsp into TCP mode
1764 * XXX: ugly, a lot of code are duplicated from Open()
1765 * This should REALLY be fixed
1766 *****************************************************************************/
1767 static int RollOverTcp( demux_t *p_demux )
1769 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1770 int i, i_return;
1772 var_SetBool( p_demux, "rtsp-tcp", true );
1774 /* We close the old RTSP session */
1775 vlc_timer_schedule(p_sys->timer, false, 0, 0);
1776 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1777 Medium::close( p_sys->ms );
1778 RTSPClient::close( p_sys->rtsp );
1780 for( i = 0; i < p_sys->i_track; i++ )
1782 live_track_t *tk = p_sys->track[i];
1784 if( tk->p_out_muxed ) vlc_demux_chained_Delete( tk->p_out_muxed );
1785 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1786 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1787 es_format_Clean( &tk->fmt );
1788 free( tk->p_buffer );
1789 free( tk );
1791 TAB_CLEAN( p_sys->i_track, p_sys->track );
1792 if( p_sys->p_out_asf ) vlc_demux_chained_Delete( p_sys->p_out_asf );
1794 p_sys->ms = NULL;
1795 p_sys->rtsp = NULL;
1796 p_sys->b_no_data = true;
1797 p_sys->i_no_data_ti = 0;
1798 p_sys->p_out_asf = NULL;
1800 /* Reopen rtsp client */
1801 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1803 msg_Err( p_demux, "Failed to connect with %s", p_sys->psz_pl_url );
1804 goto error;
1807 if( p_sys->p_sdp == NULL )
1809 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1810 goto error;
1813 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1815 msg_Err( p_demux, "Nothing to play for %s", p_sys->psz_pl_url );
1816 goto error;
1819 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1820 goto error;
1822 return VLC_SUCCESS;
1824 error:
1825 return VLC_EGENERIC;
1829 /*****************************************************************************
1831 *****************************************************************************/
1832 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1833 bool b_marker,
1834 const uint8_t *p_data, unsigned i_size )
1836 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1837 const unsigned i_packet_size = p_sys->asfh.i_min_data_packet_size;
1838 block_t *p_list = NULL;
1840 while( i_size >= 4 )
1842 unsigned i_flags = p_data[0];
1843 unsigned i_length_offset = (p_data[1] << 16) |
1844 (p_data[2] << 8) |
1845 (p_data[3] );
1846 bool b_length = i_flags & 0x40;
1847 bool b_relative_ts = i_flags & 0x20;
1848 bool b_duration = i_flags & 0x10;
1849 bool b_location_id = i_flags & 0x08;
1851 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1852 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1853 unsigned i_header_size = 4;
1854 if( b_relative_ts )
1855 i_header_size += 4;
1856 if( b_duration )
1857 i_header_size += 4;
1858 if( b_location_id )
1859 i_header_size += 4;
1861 if( i_header_size > i_size )
1863 msg_Warn( p_demux, "Invalid header size" );
1864 break;
1867 /* XXX
1868 * When b_length is true, the streams I found do not seems to respect
1869 * the documentation.
1870 * From them, I have failed to find which choice between '__MIN()' or
1871 * 'i_length_offset - i_header_size' is the right one.
1873 unsigned i_payload;
1874 if( b_length )
1875 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1876 else
1877 i_payload = i_size - i_header_size;
1879 if( !tk->p_asf_block )
1881 tk->p_asf_block = block_Alloc( i_packet_size );
1882 if( !tk->p_asf_block )
1883 break;
1884 tk->p_asf_block->i_buffer = 0;
1886 unsigned i_offset = b_length ? 0 : i_length_offset;
1887 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1889 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1890 tk->p_asf_block->i_buffer += i_payload;
1891 if( b_marker )
1893 /* We have a complete packet */
1894 tk->p_asf_block->i_buffer = i_packet_size;
1895 block_ChainAppend( &p_list, tk->p_asf_block );
1896 tk->p_asf_block = NULL;
1899 else
1901 /* Reset on broken stream */
1902 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1903 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1904 tk->p_asf_block->i_buffer = 0;
1907 /* */
1908 p_data += i_header_size + i_payload;
1909 i_size -= i_header_size + i_payload;
1911 return p_list;
1914 /*****************************************************************************
1916 *****************************************************************************/
1917 static void StreamRead( void *p_private, unsigned int i_size,
1918 unsigned int i_truncated_bytes, struct timeval pts,
1919 unsigned int duration )
1921 VLC_UNUSED( duration );
1923 live_track_t *tk = (live_track_t*)p_private;
1924 demux_t *p_demux = tk->p_demux;
1925 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1926 block_t *p_block;
1928 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1930 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1931 (int64_t)pts.tv_usec;
1933 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1934 i_pts &= INT64_C(0x00ffffffffffffff);
1936 /* Retrieve NPT for this pts */
1937 tk->f_npt = tk->sub->getNormalPlayTime(pts);
1939 if( tk->format == live_track_t::QUICKTIME_STREAM && tk->p_es == NULL )
1941 QuickTimeGenericRTPSource *qtRTPSource =
1942 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1943 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1944 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1946 /* Get codec information from the quicktime atoms :
1947 * http://developer.apple.com/quicktime/icefloe/dispatch026.html */
1948 if( tk->fmt.i_cat == VIDEO_ES ) {
1949 if( qtState.sdAtomSize < 16 + 32 )
1951 /* invalid */
1952 p_sys->event_data = 0xff;
1953 tk->waiting = 0;
1954 return;
1956 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1957 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1958 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1960 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1962 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1963 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1964 + qtRTPSource->qtState.sdAtomSize;
1965 while (pos+8 < endpos) {
1966 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1967 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1968 if( memcmp(pos+4, "avcC", 4) == 0 &&
1969 atomLength > 8 &&
1970 atomLength <= INT_MAX )
1972 tk->fmt.i_extra = atomLength-8;
1973 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1974 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1975 break;
1977 pos += atomLength;
1980 else
1982 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1983 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1984 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1987 else {
1988 if( qtState.sdAtomSize < 24 )
1990 /* invalid */
1991 p_sys->event_data = 0xff;
1992 tk->waiting = 0;
1993 return;
1995 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1996 tk->fmt.audio.i_bitspersample = (sdAtom[22] << 8) | sdAtom[23];
1998 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
2001 #if 0
2002 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
2003 i_size,
2004 pts.tv_sec * 1000000LL + pts.tv_usec );
2005 #endif
2007 /* grow buffer if it looks like buffer is too small, but don't eat
2008 * up all the memory on strange streams */
2009 if( i_truncated_bytes > 0 )
2011 if( tk->i_buffer < 2000000 )
2013 void *p_tmp;
2014 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
2015 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
2016 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
2017 if( p_tmp == NULL )
2019 msg_Warn( p_demux, "realloc failed" );
2021 else
2023 tk->p_buffer = (uint8_t*)p_tmp;
2024 tk->i_buffer *= 2;
2028 if( tk->b_discard_trunc )
2030 p_sys->event_data = 0xff;
2031 tk->waiting = 0;
2032 return;
2036 assert( i_size <= tk->i_buffer );
2038 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
2039 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
2041 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
2043 if( (p_block = block_Alloc( i_size + 1 )) )
2045 p_block->p_buffer[0] = amrSource->lastFrameHeader();
2046 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
2049 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
2051 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
2052 uint32_t header = h261Source->lastSpecialHeader();
2053 if( (p_block = block_Alloc( i_size + 4 )) )
2055 memcpy( p_block->p_buffer, &header, 4 );
2056 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
2059 else if( tk->fmt.i_codec == VLC_CODEC_H264 || tk->fmt.i_codec == VLC_CODEC_HEVC )
2061 if( tk->fmt.i_codec == VLC_CODEC_H264 && (tk->p_buffer[0] & 0x1f) >= 24 )
2062 msg_Warn( p_demux, "unsupported NAL type for H264" );
2063 else if( tk->fmt.i_codec == VLC_CODEC_HEVC && ((tk->p_buffer[0] & 0x7e)>>1) >= 48 )
2064 msg_Warn( p_demux, "unsupported NAL type for H265" );
2066 /* Normal NAL type */
2067 if( (p_block = block_Alloc( i_size + 4 )) )
2069 p_block->p_buffer[0] = 0x00;
2070 p_block->p_buffer[1] = 0x00;
2071 p_block->p_buffer[2] = 0x00;
2072 p_block->p_buffer[3] = 0x01;
2073 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
2076 else if( tk->format == live_track_t::ASF_STREAM )
2078 p_block = StreamParseAsf( p_demux, tk,
2079 tk->sub->rtpSource()->curPacketMarkerBit(),
2080 tk->p_buffer, i_size );
2082 else
2084 if( (p_block = block_Alloc( i_size )) )
2085 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
2088 /* No data sent. Always in sync then */
2089 if( !tk->b_rtcp_sync && tk->sub->rtpSource() &&
2090 tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
2092 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
2093 p_sys->b_rtcp_sync = tk->b_rtcp_sync = true;
2094 if( tk->i_pcr != VLC_TS_INVALID )
2096 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
2097 const int64_t i_max_diff = CLOCK_FREQ * (( tk->fmt.i_cat == SPU_ES ) ? 60 : 1);
2098 tk->b_flushing_discontinuity = (llabs(i_pts - tk->i_pcr) > i_max_diff);
2099 tk->i_pcr = i_pts;
2103 /* Update our global npt value */
2104 if( tk->f_npt > 0 &&
2105 ( tk->f_npt < p_sys->f_npt_length || p_sys->f_npt_length <= 0 ) )
2106 p_sys->f_npt = tk->f_npt;
2108 if( p_block )
2110 switch( tk->format )
2112 case live_track_t::ASF_STREAM:
2113 vlc_demux_chained_Send( p_sys->p_out_asf, p_block );
2114 break;
2115 case live_track_t::MULTIPLEXED_STREAM:
2116 vlc_demux_chained_Send( tk->p_out_muxed, p_block );
2117 break;
2118 default:
2119 if( i_pts != tk->i_lastpts )
2120 p_block->i_pts = VLC_TS_0 + i_pts;
2121 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
2122 switch( tk->fmt.i_codec )
2124 case VLC_CODEC_MPGV:
2125 case VLC_CODEC_H264:
2126 case VLC_CODEC_HEVC:
2127 case VLC_CODEC_VP8:
2128 p_block->i_dts = VLC_TS_INVALID;
2129 break;
2130 default:
2131 p_block->i_dts = VLC_TS_0 + i_pts;
2132 break;
2135 if( i_truncated_bytes )
2136 p_block->i_flags |= BLOCK_FLAG_CORRUPTED;
2138 if( unlikely(tk->i_next_block_flags) )
2140 p_block->i_flags |= tk->i_next_block_flags;
2141 tk->i_next_block_flags = 0;
2143 es_out_Send( p_demux->out, tk->p_es, p_block );
2144 if( i_pts > 0 )
2146 if( tk->i_pcr < i_pts )
2147 tk->i_pcr = i_pts;
2148 tk->i_lastpts = i_pts;
2150 break;
2154 /* warn that's ok */
2155 p_sys->event_data = 0xff;
2157 /* we have read data */
2158 tk->waiting = 0;
2159 p_sys->b_no_data = false;
2160 p_sys->i_no_data_ti = 0;
2163 /*****************************************************************************
2165 *****************************************************************************/
2166 static void StreamClose( void *p_private )
2168 live_track_t *tk = (live_track_t*)p_private;
2169 demux_t *p_demux = tk->p_demux;
2170 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2171 tk->state = live_track_t::STATE_IGNORED;
2172 p_sys->event_rtsp = 0xff;
2173 p_sys->event_data = 0xff;
2175 if( tk->p_es )
2176 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
2178 int nb_tracks = 0;
2179 for( int i = 0; i < p_sys->i_track; i++ )
2181 if( p_sys->track[i]->state == live_track_t::STATE_SELECTED )
2182 nb_tracks++;
2184 msg_Dbg( p_demux, "RTSP track Close, %d track remaining", nb_tracks );
2185 if( !nb_tracks )
2186 p_sys->b_error = true;
2190 /*****************************************************************************
2192 *****************************************************************************/
2193 static void TaskInterruptRTSP( void *p_private )
2195 demux_t *p_demux = (demux_t*)p_private;
2196 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2198 /* Avoid lock */
2199 p_sys->event_rtsp = 0xff;
2202 static void TaskInterruptData( void *p_private )
2204 demux_t *p_demux = (demux_t*)p_private;
2205 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2207 p_sys->i_no_data_ti++;
2209 /* Avoid lock */
2210 p_sys->event_data = 0xff;
2213 /*****************************************************************************
2215 *****************************************************************************/
2216 static void TimeoutPrevention( void *p_data )
2218 demux_t *p_demux = (demux_t *) p_data;
2219 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2220 char *bye = NULL;
2222 /* Protect Live555 from us calling their functions simultaneously
2223 with Demux() or Control() */
2224 vlc_mutex_locker locker(&p_sys->timeout_mutex);
2226 /* If the timer fires while the demuxer owns the lock, and the demuxer
2227 * then torns the session down, the pointers will become NULL. By the time
2228 * this timer callback obtains the callback, either a new session was
2229 * created and the timer is rescheduled, or the pointers are still NULL
2230 * and the timer is descheduled. In the second case, bail out (then wait
2231 * for the timer to be rescheduled or destroyed). In the first case, this
2232 * might send an early refresh - that´s harmless but suboptimal (FIXME). */
2233 if( p_sys->rtsp == NULL || p_sys->ms == NULL )
2234 return;
2236 bool use_get_param = p_sys->b_get_param;
2238 /* Use GET_PARAMETERS if supported. wmserver dialect supports
2239 * it, but does not report this properly. */
2240 if( var_GetBool( p_demux, "rtsp-wmserver" ) )
2241 use_get_param = true;
2243 if( use_get_param )
2244 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms,
2245 default_live555_callback, bye );
2246 else
2247 p_sys->rtsp->sendOptionsCommand( default_live555_callback, NULL );
2249 if( !wait_Live555_response( p_demux ) )
2251 msg_Err( p_demux, "keep-alive failed: %s",
2252 p_sys->env->getResultMsg() );
2253 /* Just continue, worst case is we get timed out later */
2257 /*****************************************************************************
2259 *****************************************************************************/
2260 static int ParseASF( demux_t *p_demux )
2262 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2264 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
2265 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2266 char *psz_end;
2267 block_t *p_header;
2269 /* Parse the asf header */
2270 if( psz_asf == NULL )
2271 return VLC_EGENERIC;
2273 psz_asf += strlen( psz_marker );
2274 psz_asf = strdup( psz_asf ); /* Duplicate it */
2275 psz_end = strchr( psz_asf, '\n' );
2277 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2278 *psz_end-- = '\0';
2280 if( psz_asf >= psz_end )
2282 free( psz_asf );
2283 return VLC_EGENERIC;
2286 /* Always smaller */
2287 p_header = block_Alloc( psz_end - psz_asf );
2288 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2289 p_header->i_buffer, psz_asf );
2290 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2291 if( p_header->i_buffer <= 0 )
2293 free( psz_asf );
2294 return VLC_EGENERIC;
2297 /* Parse it to get packet size */
2298 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2300 /* Send it to demuxer */
2301 vlc_demux_chained_Send( p_sys->p_out_asf, p_header );
2303 free( psz_asf );
2304 return VLC_SUCCESS;
2308 static unsigned char* parseH264ConfigStr( char const* configStr,
2309 unsigned int& configSize )
2311 char *dup, *psz;
2312 size_t i_records = 1;
2314 configSize = 0;
2316 if( configStr == NULL || *configStr == '\0' )
2317 return NULL;
2319 psz = dup = strdup( configStr );
2321 /* Count the number of commas */
2322 for( psz = dup; *psz != '\0'; ++psz )
2324 if( *psz == ',')
2326 ++i_records;
2327 *psz = '\0';
2331 size_t configMax = 5*strlen(dup);
2332 unsigned char *cfg = new unsigned char[configMax];
2333 psz = dup;
2334 for( size_t i = 0; i < i_records; ++i )
2336 cfg[configSize++] = 0x00;
2337 cfg[configSize++] = 0x00;
2338 cfg[configSize++] = 0x00;
2339 cfg[configSize++] = 0x01;
2341 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2342 configMax-configSize, psz );
2343 psz += strlen(psz)+1;
2346 free( dup );
2347 return cfg;
2350 static uint8_t *parseVorbisConfigStr( char const* configStr,
2351 unsigned int& configSize )
2353 configSize = 0;
2354 if( configStr == NULL || *configStr == '\0' )
2355 return NULL;
2356 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1332115200 // 2012.03.20
2357 unsigned char *p_cfg = base64Decode( configStr, configSize );
2358 #else
2359 char* configStr_dup = strdup( configStr );
2360 unsigned char *p_cfg = base64Decode( configStr_dup, configSize );
2361 free( configStr_dup );
2362 #endif
2363 uint8_t *p_extra = NULL;
2364 /* skip header count, ident number and length (cf. RFC 5215) */
2365 const unsigned int headerSkip = 9;
2366 if( configSize > headerSkip && ((uint8_t*)p_cfg)[3] == 1 )
2368 configSize -= headerSkip;
2369 p_extra = (uint8_t*)xmalloc( configSize );
2370 memcpy( p_extra, p_cfg+headerSkip, configSize );
2372 delete[] p_cfg;
2373 return p_extra;
2376 static char *passwordLessURL( vlc_url_t *p_url )
2378 vlc_url_t url;
2380 memcpy( &url, p_url, sizeof( vlc_url_t ) );
2382 url.psz_username = NULL;
2383 url.psz_password = NULL;
2384 if( url.i_port == 0 )
2385 url.i_port = 554;
2386 return vlc_uri_compose( &url );