demux: mkv: handle WAVE_FORMAT_MPEG_ADTS_AAC
[vlc.git] / modules / access / live555.cpp
bloba071f53e82f89416c6fb0bf724968da6f71e7b17
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 bool b_selected;
182 } live_track_t;
184 class RTSPClientVlc;
186 struct demux_sys_t
188 char *p_sdp; /* XXX mallocated */
189 char *psz_pl_url; /* password-less URL */
190 vlc_url_t url;
192 MediaSession *ms;
193 TaskScheduler *scheduler;
194 UsageEnvironment *env ;
195 RTSPClientVlc *rtsp;
197 /* */
198 int i_track;
199 live_track_t **track;
201 /* Weird formats */
202 asf_header_t asfh;
203 vlc_demux_chained_t *p_out_asf;
204 bool b_real;
206 /* */
207 int64_t i_pcr; /* The clock */
208 bool b_rtcp_sync; /* At least one track received sync */
209 double f_npt;
210 double f_npt_length;
211 double f_npt_start;
213 /* timeout thread information */
214 vlc_timer_t timer;
215 vlc_mutex_t timeout_mutex; /* Serialise calls to live555 in timeout thread w.r.t. Demux()/Control() */
217 /* */
218 bool b_force_mcast;
219 bool b_multicast; /* if one of the tracks is multicasted */
220 bool b_no_data; /* if we never received any data */
221 int i_no_data_ti; /* consecutive number of TaskInterrupt */
223 char event_rtsp;
224 char event_data;
226 bool b_get_param; /* Does the server support GET_PARAMETER */
227 bool b_paused; /* Are we paused? */
228 bool b_error;
229 int i_live555_ret; /* live555 callback return code */
231 float f_seek_request;/* In case we receive a seek request while paused*/
235 class RTSPClientVlc : public RTSPClient
237 public:
238 RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
239 char const* applicationName, portNumBits tunnelOverHTTPPortNum,
240 demux_sys_t *p_sys) :
241 RTSPClient( env, rtspURL, verbosityLevel, applicationName,
242 tunnelOverHTTPPortNum
243 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1373932800
244 , -1
245 #endif
248 this->p_sys = p_sys;
250 demux_sys_t *p_sys;
253 static int Demux ( demux_t * );
254 static int Control( demux_t *, int, va_list );
256 static int Connect ( demux_t * );
257 static int SessionsSetup( demux_t * );
258 static int Play ( demux_t *);
259 static int ParseASF ( demux_t * );
260 static int RollOverTcp ( demux_t * );
262 static void StreamRead ( void *, unsigned int, unsigned int,
263 struct timeval, unsigned int );
264 static void StreamClose ( void * );
265 static void TaskInterruptData( void * );
266 static void TaskInterruptRTSP( void * );
268 static void TimeoutPrevention( void * );
270 static unsigned char* parseH264ConfigStr( char const* configStr,
271 unsigned int& configSize );
272 static unsigned char* parseVorbisConfigStr( char const* configStr,
273 unsigned int& configSize );
275 static char *passwordLessURL( vlc_url_t *url );
277 /*****************************************************************************
278 * DemuxOpen:
279 *****************************************************************************/
280 static int Open ( vlc_object_t *p_this )
282 demux_t *p_demux = (demux_t*)p_this;
283 demux_sys_t *p_sys = NULL;
285 char *psz_url;
286 int i_return;
287 int i_error = VLC_EGENERIC;
289 /* if the rtsp URL may contain a sat.ip fake DNS, bail-out early and
290 * let the SAT>IP module handle that */
291 if( !strncmp(p_demux->psz_location, "sat.ip", 6) )
293 msg_Err( p_demux, "SAT>IP server, bailing out");
294 return VLC_EGENERIC;
296 /* If satip-host is set on the item, we shall assume it is a rtsp for the
297 * SAT>IP module and bail-out early. */
298 char *psz_host = var_InheritString(p_demux, "satip-host");
299 if (psz_host != NULL) {
300 msg_Err( p_demux, "URL is for SAT>IP, bailing out");
301 free(psz_host);
302 return VLC_EGENERIC;
305 if( p_demux->s )
307 /* See if it looks like a SDP
308 v, o, s fields are mandatory and in this order */
309 const uint8_t *p_peek;
310 if( vlc_stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
312 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
313 memcmp( p_peek, "v=0\n", 4 ) &&
314 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
316 return VLC_EGENERIC;
320 p_demux->pf_demux = Demux;
321 p_demux->pf_control= Control;
322 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
323 if( !p_sys ) return VLC_ENOMEM;
325 if( vlc_timer_create(&p_sys->timer, TimeoutPrevention, p_demux) )
327 free( p_sys );
328 return VLC_ENOMEM;
331 msg_Dbg( p_demux, "version " LIVEMEDIA_LIBRARY_VERSION_STRING );
333 TAB_INIT( p_sys->i_track, p_sys->track );
334 p_sys->b_no_data = true;
335 p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
336 p_sys->f_seek_request = -1;
337 vlc_mutex_init(&p_sys->timeout_mutex);
339 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
340 if( asprintf( &psz_url, "%s://%s", p_demux->psz_access, p_demux->psz_location ) == -1 )
342 i_error = VLC_ENOMEM;
343 goto error;
345 vlc_UrlParse( &p_sys->url, psz_url );
346 free( psz_url );
348 if( ( p_sys->psz_pl_url = passwordLessURL( &p_sys->url ) ) == NULL )
350 i_error = VLC_ENOMEM;
351 goto error;
354 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
356 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
357 goto error;
359 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
361 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
362 goto error;
365 if( strcasecmp( p_demux->psz_access, "sdp" ) )
367 char *p = p_sys->psz_pl_url;
368 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
371 if( p_demux->s != NULL )
373 /* Gather the complete sdp file */
374 int i_sdp = 0;
375 int i_sdp_max = 1000;
376 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
378 if( !p_sdp )
380 i_error = VLC_ENOMEM;
381 goto error;
384 for( ;; )
386 int i_read = vlc_stream_Read( p_demux->s, &p_sdp[i_sdp],
387 i_sdp_max - i_sdp - 1 );
388 if( i_read < 0 )
390 msg_Err( p_demux, "failed to read SDP" );
391 free( p_sdp );
392 goto error;
395 i_sdp += i_read;
397 if( i_read < i_sdp_max - i_sdp - 1 )
399 p_sdp[i_sdp] = '\0';
400 break;
403 i_sdp_max += 1000;
404 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
406 p_sys->p_sdp = (char*)p_sdp;
408 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
410 msg_Err( p_demux, "Failed to connect with %s", p_sys->psz_pl_url );
411 goto error;
414 if( p_sys->p_sdp == NULL )
416 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
417 i_error = VLC_ENOMEM;
418 goto error;
421 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
423 msg_Err( p_demux, "Nothing to play for %s", p_sys->psz_pl_url );
424 goto error;
427 if( p_sys->b_real ) goto error;
429 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
430 goto error;
432 if( p_sys->p_out_asf && ParseASF( p_demux ) )
434 msg_Err( p_demux, "cannot find a usable asf header" );
435 /* TODO Clean tracks */
436 goto error;
439 if( p_sys->i_track <= 0 )
440 goto error;
442 return VLC_SUCCESS;
444 error:
445 Close( p_this );
446 return i_error;
449 /*****************************************************************************
450 * DemuxClose:
451 *****************************************************************************/
452 static void Close( vlc_object_t *p_this )
454 demux_t *p_demux = (demux_t*)p_this;
455 demux_sys_t *p_sys = p_demux->p_sys;
457 vlc_timer_destroy(p_sys->timer);
459 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
460 if( p_sys->ms ) Medium::close( p_sys->ms );
461 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
462 if( p_sys->env ) p_sys->env->reclaim();
464 for( int i = 0; i < p_sys->i_track; i++ )
466 live_track_t *tk = p_sys->track[i];
468 if( tk->p_out_muxed )
469 vlc_demux_chained_Delete( tk->p_out_muxed );
470 es_format_Clean( &tk->fmt );
471 free( tk->p_buffer );
472 free( tk );
474 TAB_CLEAN( p_sys->i_track, p_sys->track );
475 if( p_sys->p_out_asf )
476 vlc_demux_chained_Delete( p_sys->p_out_asf );
477 delete p_sys->scheduler;
478 free( p_sys->p_sdp );
479 free( p_sys->psz_pl_url );
481 vlc_UrlClean( &p_sys->url );
482 vlc_mutex_destroy(&p_sys->timeout_mutex);
484 free( p_sys );
487 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
489 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
491 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
492 demux_sys_t *p_sys = client_vlc->p_sys;
493 delete []result_string;
494 p_sys->i_live555_ret = result_code;
495 p_sys->b_error = p_sys->i_live555_ret != 0;
496 p_sys->event_rtsp = 1;
499 /* return true if the RTSP command succeeded */
500 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
502 TaskToken task;
503 demux_sys_t * p_sys = p_demux->p_sys;
504 p_sys->event_rtsp = 0;
505 if( i_timeout > 0 )
507 /* Create a task that will be called if we wait more than timeout ms */
508 task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000,
509 TaskInterruptRTSP,
510 p_demux );
512 p_sys->event_rtsp = 0;
513 p_sys->b_error = true;
514 p_sys->i_live555_ret = 0;
515 p_sys->scheduler->doEventLoop( &p_sys->event_rtsp );
516 //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
517 if( i_timeout > 0 )
519 /* remove the task */
520 p_sys->scheduler->unscheduleDelayedTask( task );
522 return !p_sys->b_error;
525 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
526 char* result_string )
528 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
529 demux_sys_t *p_sys = client_vlc->p_sys;
530 p_sys->i_live555_ret = result_code;
531 if ( result_code == 0 )
533 char* sdpDescription = result_string;
534 free( p_sys->p_sdp );
535 p_sys->p_sdp = NULL;
536 if( sdpDescription )
538 p_sys->p_sdp = strdup( sdpDescription );
539 p_sys->b_error = false;
542 else
543 p_sys->b_error = true;
544 delete[] result_string;
545 p_sys->event_rtsp = 1;
548 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
549 char* result_string )
551 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
552 demux_sys_t *p_sys = client_vlc->p_sys;
553 p_sys->b_get_param =
554 // If OPTIONS fails, assume GET_PARAMETER is not supported but
555 // still continue on with the stream. Some servers (foscam)
556 // return 501/not implemented for OPTIONS.
557 result_code == 0
558 && result_string != NULL
559 && strstr( result_string, "GET_PARAMETER" ) != NULL;
560 client->sendDescribeCommand( continueAfterDESCRIBE );
561 delete[] result_string;
564 /*****************************************************************************
565 * Connect: connects to the RTSP server to setup the session DESCRIBE
566 *****************************************************************************/
567 static int Connect( demux_t *p_demux )
569 demux_sys_t *p_sys = p_demux->p_sys;
570 Authenticator authenticator;
571 vlc_credential credential;
572 const char *psz_user = NULL;
573 const char *psz_pwd = NULL;
574 int i_http_port = 0;
575 int i_ret = VLC_SUCCESS;
576 const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
578 vlc_credential_init( &credential, &p_sys->url );
580 /* Credentials can be NULL since they may not be needed */
581 if( vlc_credential_get( &credential, p_demux, "rtsp-user", "rtsp-pwd",
582 NULL, NULL) )
584 psz_user = credential.psz_username;
585 psz_pwd = credential.psz_password;
588 createnew:
589 /* FIXME: This is naive and incorrect; it does not prevent the thread
590 * getting stuck in blocking socket operations. */
591 if( vlc_killed() )
593 i_ret = VLC_EGENERIC;
594 goto bailout;
597 if( var_CreateGetBool( p_demux, "rtsp-http" ) )
598 i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
600 p_sys->rtsp = new (std::nothrow) RTSPClientVlc( *p_sys->env, p_sys->psz_pl_url,
601 var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
602 "LibVLC/" VERSION, i_http_port, p_sys );
603 if( !p_sys->rtsp )
605 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
606 p_sys->env->getResultMsg() );
607 i_ret = VLC_EGENERIC;
608 goto bailout;
611 /* Kasenna enables KeepAlive by analysing the User-Agent string.
612 * Appending _KA to the string should be enough to enable this feature,
613 * however, there is a bug where the _KA doesn't get parsed from the
614 * default User-Agent as created by VLC/Live555 code. This is probably due
615 * to spaces in the string or the string being too long. Here we override
616 * the default string with a more compact version.
618 if( var_InheritBool( p_demux, "rtsp-kasenna" ))
620 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
623 describe:
624 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
626 p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
628 if( !wait_Live555_response( p_demux, i_timeout ) )
630 int i_code = p_sys->i_live555_ret;
631 if( i_code == 401 )
633 msg_Dbg( p_demux, "authentication failed" );
635 if( vlc_credential_get( &credential, p_demux, "rtsp-user", "rtsp-pwd",
636 _("RTSP authentication"),
637 _("Please enter a valid login name and a password.") ) )
639 psz_user = credential.psz_username;
640 psz_pwd = credential.psz_password;
641 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
642 goto describe;
645 else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
647 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
648 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
649 var_SetBool( p_demux, "rtsp-http", true );
650 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
651 p_sys->rtsp = NULL;
652 goto createnew;
654 else
656 if( i_code == 0 )
657 msg_Dbg( p_demux, "connection timeout" );
658 else
660 msg_Dbg( p_demux, "connection error %d", i_code );
661 if( i_code == 403 )
662 vlc_dialog_display_error( p_demux, _("RTSP connection failed"),
663 _("Access to the stream is denied by the server configuration.") );
665 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
666 p_sys->rtsp = NULL;
668 i_ret = VLC_EGENERIC;
670 else
671 vlc_credential_store( &credential, p_demux );
673 bailout:
674 vlc_credential_clean( &credential );
676 return i_ret;
679 /*****************************************************************************
680 * SessionsSetup: prepares the subsessions and does the SETUP
681 *****************************************************************************/
682 static int SessionsSetup( demux_t *p_demux )
684 demux_sys_t *p_sys = p_demux->p_sys;
685 MediaSubsessionIterator *iter = NULL;
686 MediaSubsession *sub = NULL;
688 bool b_rtsp_tcp;
689 int i_client_port;
690 int i_return = VLC_SUCCESS;
691 unsigned int i_receive_buffer = 0;
692 int i_frame_buffer = DEFAULT_FRAME_BUFFER_SIZE;
693 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
694 const char *p_sess_lang = NULL;
695 const char *p_lang;
697 b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
698 var_GetBool( p_demux, "rtsp-http" );
699 i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
702 /* Create the session from the SDP */
703 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
705 msg_Err( p_demux, "Could not create the RTSP Session: %s",
706 p_sys->env->getResultMsg() );
707 return VLC_EGENERIC;
710 if( strcmp( p_sys->p_sdp, "m=" ) != 0 )
712 const char *p_sess_attr_end;
714 p_sess_attr_end = strstr( p_sys->p_sdp, "\nm=" );
715 if( !p_sess_attr_end )
716 p_sess_attr_end = strstr( p_sys->p_sdp, "\rm=" );
718 p_sess_lang = p_sess_attr_end ? strstr( p_sys->p_sdp, "a=lang:" ) : NULL;
719 if( p_sess_lang &&
720 p_sess_lang - p_sys->p_sdp > p_sess_attr_end - p_sys->p_sdp )
721 p_sess_lang = NULL;
724 /* Initialise each media subsession */
725 iter = new MediaSubsessionIterator( *p_sys->ms );
726 while( ( sub = iter->next() ) != NULL )
728 Boolean bInit;
729 live_track_t *tk;
731 /* Value taken from mplayer */
732 if( !strcmp( sub->mediumName(), "audio" ) )
733 i_receive_buffer = 100000;
734 else if( !strcmp( sub->mediumName(), "video" ) )
736 int i_var_buf_size = var_InheritInteger( p_demux, "rtsp-frame-buffer-size" );
737 if( i_var_buf_size > 0 )
738 i_frame_buffer = i_var_buf_size;
739 i_receive_buffer = 2000000;
741 else if( !strcmp( sub->mediumName(), "text" ) )
743 else continue;
745 if( strcasestr( sub->codecName(), "REAL" ) )
747 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
748 p_sys->b_real = true; /* This is a problem, we'll handle it later */
749 continue;
752 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
753 bInit = sub->initiate( 0 );
754 else
755 bInit = sub->initiate();
757 if( !bInit )
759 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
760 sub->mediumName(), sub->codecName(),
761 p_sys->env->getResultMsg() );
763 else
765 if( sub->rtpSource() != NULL )
767 int fd = sub->rtpSource()->RTPgs()->socketNum();
769 /* Increase the buffer size */
770 if( i_receive_buffer > 0 )
771 increaseReceiveBufferTo( *p_sys->env, fd, i_receive_buffer );
773 /* Increase the RTP reorder timebuffer just a bit */
774 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
776 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
777 sub->codecName() );
779 /* Issue the SETUP */
780 if( p_sys->rtsp )
783 if( i_client_port != -1 )
785 sub->setClientPortNum( i_client_port );
786 i_client_port += 2;
789 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
790 toBool( b_rtsp_tcp ),
791 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
792 if( !wait_Live555_response( p_demux ) )
794 /* if we get an unsupported transport error, toggle TCP
795 * use and try again */
796 if( p_sys->i_live555_ret == 461 )
797 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
798 !toBool( b_rtsp_tcp ), False );
799 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
801 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
802 sub->mediumName(), sub->codecName(),
803 p_sys->env->getResultMsg() );
804 continue;
806 else
808 var_SetBool( p_demux, "rtsp-tcp", true );
809 b_rtsp_tcp = true;
814 /* Check if we will receive data from this subsession for
815 * this track */
816 if( sub->readSource() == NULL ) continue;
817 if( !p_sys->b_multicast )
819 /* We need different rollover behaviour for multicast */
820 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
823 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
824 if( !tk )
826 delete iter;
827 return VLC_ENOMEM;
829 tk->p_demux = p_demux;
830 tk->sub = sub;
831 tk->p_es = NULL;
832 tk->format = live_track_t::SINGLE_STREAM;
833 tk->p_asf_block = NULL;
834 tk->b_discard_trunc = false;
835 tk->p_out_muxed = NULL;
836 tk->waiting = 0;
837 tk->b_rtcp_sync = false;
838 tk->b_flushing_discontinuity = false;
839 tk->i_next_block_flags = 0;
840 tk->i_lastpts = VLC_TS_INVALID;
841 tk->i_pcr = VLC_TS_INVALID;
842 tk->f_npt = 0.;
843 tk->b_selected = true;
844 tk->i_buffer = i_frame_buffer;
845 tk->p_buffer = (uint8_t *)malloc( i_frame_buffer );
847 if( !tk->p_buffer )
849 free( tk );
850 delete iter;
851 return VLC_ENOMEM;
854 /* Value taken from mplayer */
855 if( !strcmp( sub->mediumName(), "audio" ) )
857 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
858 tk->fmt.audio.i_channels = sub->numChannels();
859 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
861 if( !strcmp( sub->codecName(), "MPA" ) ||
862 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
863 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
865 tk->fmt.i_codec = VLC_CODEC_MPGA;
866 tk->fmt.audio.i_rate = 0;
868 else if( !strcmp( sub->codecName(), "AC3" ) )
870 tk->fmt.i_codec = VLC_CODEC_A52;
871 tk->fmt.audio.i_rate = 0;
873 else if( !strcmp( sub->codecName(), "L16" ) )
875 tk->fmt.i_codec = VLC_CODEC_S16B;
876 tk->fmt.audio.i_bitspersample = 16;
878 else if( !strcmp( sub->codecName(), "L20" ) )
880 tk->fmt.i_codec = VLC_CODEC_S20B;
881 tk->fmt.audio.i_bitspersample = 20;
883 else if( !strcmp( sub->codecName(), "L24" ) )
885 tk->fmt.i_codec = VLC_CODEC_S24B;
886 tk->fmt.audio.i_bitspersample = 24;
888 else if( !strcmp( sub->codecName(), "L8" ) )
890 tk->fmt.i_codec = VLC_CODEC_U8;
891 tk->fmt.audio.i_bitspersample = 8;
893 else if( !strcmp( sub->codecName(), "DAT12" ) )
895 tk->fmt.i_codec = VLC_CODEC_DAT12;
896 tk->fmt.audio.i_bitspersample = 12;
898 else if( !strcmp( sub->codecName(), "PCMU" ) )
900 tk->fmt.i_codec = VLC_CODEC_MULAW;
901 tk->fmt.audio.i_bitspersample = 8;
903 else if( !strcmp( sub->codecName(), "PCMA" ) )
905 tk->fmt.i_codec = VLC_CODEC_ALAW;
906 tk->fmt.audio.i_bitspersample = 8;
908 else if( !strncmp( sub->codecName(), "G726", 4 ) )
910 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
911 tk->fmt.audio.i_rate = 8000;
912 tk->fmt.audio.i_channels = 1;
913 if( !strcmp( sub->codecName()+5, "40" ) )
914 tk->fmt.i_bitrate = 40000;
915 else if( !strcmp( sub->codecName()+5, "32" ) )
916 tk->fmt.i_bitrate = 32000;
917 else if( !strcmp( sub->codecName()+5, "24" ) )
918 tk->fmt.i_bitrate = 24000;
919 else if( !strcmp( sub->codecName()+5, "16" ) )
920 tk->fmt.i_bitrate = 16000;
922 else if( !strcmp( sub->codecName(), "AMR" ) )
924 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
926 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
928 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
930 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
932 unsigned int i_extra;
933 uint8_t *p_extra;
935 tk->fmt.i_codec = VLC_CODEC_MP4A;
937 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
938 i_extra ) ) )
940 tk->fmt.i_extra = i_extra;
941 tk->fmt.p_extra = xmalloc( i_extra );
942 memcpy( tk->fmt.p_extra, p_extra, i_extra );
943 delete[] p_extra;
945 /* Because the "faad" decoder does not handle the LATM
946 * data length field at the start of each returned LATM
947 * frame, tell the RTP source to omit. */
948 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
950 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
952 unsigned int i_extra;
953 uint8_t *p_extra;
955 tk->fmt.i_codec = VLC_CODEC_MP4A;
957 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
958 i_extra ) ) )
960 tk->fmt.i_extra = i_extra;
961 tk->fmt.p_extra = xmalloc( i_extra );
962 memcpy( tk->fmt.p_extra, p_extra, i_extra );
963 delete[] p_extra;
966 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
968 tk->format = live_track_t::ASF_STREAM;
969 if( p_sys->p_out_asf == NULL )
970 p_sys->p_out_asf =
971 vlc_demux_chained_New( VLC_OBJECT(p_demux), "asf",
972 p_demux->out );
974 else if( !strcmp( sub->codecName(), "X-QT" ) ||
975 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
977 tk->format = live_track_t::QUICKTIME_STREAM;
979 else if( !strcmp( sub->codecName(), "SPEEX" ) )
981 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
983 else if( !strcmp( sub->codecName(), "VORBIS" ) )
985 tk->fmt.i_codec = VLC_CODEC_VORBIS;
986 unsigned int i_extra;
987 unsigned char *p_extra;
988 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
989 i_extra ) ) )
991 tk->fmt.i_extra = i_extra;
992 tk->fmt.p_extra = p_extra;
994 else
995 msg_Warn( p_demux,"Missing or unsupported vorbis header." );
997 else if( !strcmp( sub->codecName(), "OPUS" ) )
999 tk->fmt.i_codec = VLC_CODEC_OPUS;
1002 else if( !strcmp( sub->mediumName(), "video" ) )
1004 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
1005 if( !strcmp( sub->codecName(), "MPV" ) )
1007 tk->fmt.i_codec = VLC_CODEC_MPGV;
1008 tk->fmt.b_packetized = false;
1010 else if( !strcmp( sub->codecName(), "H263" ) ||
1011 !strcmp( sub->codecName(), "H263-1998" ) ||
1012 !strcmp( sub->codecName(), "H263-2000" ) )
1014 tk->fmt.i_codec = VLC_CODEC_H263;
1016 else if( !strcmp( sub->codecName(), "H261" ) )
1018 tk->fmt.i_codec = VLC_CODEC_H261;
1020 else if( !strcmp( sub->codecName(), "H264" ) )
1022 unsigned int i_extra = 0;
1023 uint8_t *p_extra = NULL;
1025 tk->fmt.i_codec = VLC_CODEC_H264;
1026 tk->fmt.b_packetized = false;
1028 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
1029 i_extra ) ) )
1031 tk->fmt.i_extra = i_extra;
1032 tk->fmt.p_extra = xmalloc( i_extra );
1033 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1035 delete[] p_extra;
1038 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1393372800 // 2014.02.26
1039 else if( !strcmp( sub->codecName(), "H265" ) )
1041 unsigned int i_extra1 = 0, i_extra2 = 0, i_extra3 = 0, i_extraTot;
1042 uint8_t *p_extra1 = NULL, *p_extra2 = NULL, *p_extra3 = NULL;
1044 tk->fmt.i_codec = VLC_CODEC_HEVC;
1045 tk->fmt.b_packetized = false;
1047 p_extra1 = parseH264ConfigStr( sub->fmtp_spropvps(), i_extra1 );
1048 p_extra2 = parseH264ConfigStr( sub->fmtp_spropsps(), i_extra2 );
1049 p_extra3 = parseH264ConfigStr( sub->fmtp_sproppps(), i_extra3 );
1050 i_extraTot = i_extra1 + i_extra2 + i_extra3;
1051 if( i_extraTot > 0 )
1053 tk->fmt.i_extra = i_extraTot;
1054 tk->fmt.p_extra = xmalloc( i_extraTot );
1055 if( p_extra1 )
1057 memcpy( tk->fmt.p_extra, p_extra1, i_extra1 );
1059 if( p_extra2 )
1061 memcpy( ((char*)tk->fmt.p_extra)+i_extra1, p_extra2, i_extra2 );
1063 if( p_extra3 )
1065 memcpy( ((char*)tk->fmt.p_extra)+i_extra1+i_extra2, p_extra3, i_extra3 );
1068 delete[] p_extra1; delete[] p_extra2; delete[] p_extra3;
1071 #endif
1072 else if( !strcmp( sub->codecName(), "JPEG" ) )
1074 tk->fmt.i_codec = VLC_CODEC_MJPG;
1076 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1078 unsigned int i_extra;
1079 uint8_t *p_extra;
1081 tk->fmt.i_codec = VLC_CODEC_MP4V;
1083 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1084 i_extra ) ) )
1086 tk->fmt.i_extra = i_extra;
1087 tk->fmt.p_extra = xmalloc( i_extra );
1088 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1089 delete[] p_extra;
1092 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1093 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1094 !strcmp( sub->codecName(), "X-QDM" ) ||
1095 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1096 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1098 tk->format = live_track_t::QUICKTIME_STREAM;
1100 else if( !strcmp( sub->codecName(), "MP2T" ) )
1102 tk->format = live_track_t::MULTIPLEXED_STREAM;
1103 tk->p_out_muxed =
1104 vlc_demux_chained_New( VLC_OBJECT(p_demux), "ts",
1105 p_demux->out );
1107 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1108 !strcmp( sub->codecName(), "MP1S" ) )
1110 tk->format = live_track_t::MULTIPLEXED_STREAM;
1111 tk->p_out_muxed =
1112 vlc_demux_chained_New( VLC_OBJECT(p_demux), "ps",
1113 p_demux->out );
1115 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1117 tk->format = live_track_t::ASF_STREAM;
1118 if( p_sys->p_out_asf == NULL )
1119 p_sys->p_out_asf =
1120 vlc_demux_chained_New( VLC_OBJECT(p_demux),
1121 "asf", p_demux->out );
1123 else if( !strcmp( sub->codecName(), "DV" ) )
1125 tk->format = live_track_t::MULTIPLEXED_STREAM;
1126 tk->b_discard_trunc = true;
1127 tk->p_out_muxed =
1128 vlc_demux_chained_New( VLC_OBJECT(p_demux), "rawdv",
1129 p_demux->out );
1131 else if( !strcmp( sub->codecName(), "VP8" ) )
1133 tk->fmt.i_codec = VLC_CODEC_VP8;
1135 else if( !strcmp( sub->codecName(), "THEORA" ) )
1137 tk->fmt.i_codec = VLC_CODEC_THEORA;
1138 unsigned int i_extra;
1139 unsigned char *p_extra;
1140 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
1141 i_extra ) ) )
1143 tk->fmt.i_extra = i_extra;
1144 tk->fmt.p_extra = p_extra;
1146 else
1147 msg_Warn( p_demux,"Missing or unsupported theora header." );
1150 else if( !strcmp( sub->mediumName(), "text" ) )
1152 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1154 if( !strcmp( sub->codecName(), "T140" ) )
1156 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1160 /* Try and parse a=lang: attribute */
1161 p_lang = strstr( sub->savedSDPLines(), "a=lang:" );
1162 if( !p_lang )
1163 p_lang = p_sess_lang;
1165 if( p_lang )
1167 unsigned i_lang_len;
1168 p_lang += 7;
1169 i_lang_len = strcspn( p_lang, " \r\n" );
1170 tk->fmt.psz_language = strndup( p_lang, i_lang_len );
1173 if( tk->format == live_track_t::SINGLE_STREAM )
1175 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1178 if( sub->rtcpInstance() != NULL )
1180 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1183 if( tk->p_es ||
1184 tk->format == live_track_t::QUICKTIME_STREAM ||
1185 (tk->format == live_track_t::MULTIPLEXED_STREAM && tk->p_out_muxed ) ||
1186 (tk->format == live_track_t::ASF_STREAM && p_sys->p_out_asf ) )
1188 TAB_APPEND_CAST( (live_track_t **), p_sys->i_track, p_sys->track, tk );
1190 else
1192 /* BUG ??? */
1193 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1194 es_format_Clean( &tk->fmt );
1195 free( tk );
1199 delete iter;
1200 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1202 /* Retrieve the starttime if possible */
1203 p_sys->f_npt_start = p_sys->ms->playStartTime();
1205 /* Retrieve the duration if possible */
1206 p_sys->f_npt_length = p_sys->ms->playEndTime();
1208 /* */
1209 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1211 /* */
1212 p_sys->b_no_data = true;
1213 p_sys->i_no_data_ti = 0;
1214 p_sys->b_rtcp_sync = false;
1215 p_sys->i_pcr = VLC_TS_INVALID;
1217 return i_return;
1220 /*****************************************************************************
1221 * Play: starts the actual playback of the stream
1222 *****************************************************************************/
1223 static int Play( demux_t *p_demux )
1225 demux_sys_t *p_sys = p_demux->p_sys;
1227 if( p_sys->rtsp )
1229 /* The PLAY */
1230 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_npt_start, -1, 1 );
1232 if( !wait_Live555_response(p_demux) )
1234 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1235 return VLC_EGENERIC;
1238 /* Retrieve the timeout value and set up a timeout prevention thread */
1239 int timeout = p_sys->rtsp->sessionTimeoutParameter();
1240 if( timeout <= 2 )
1241 timeout = 60; /* default value from RFC2326 */
1242 msg_Dbg( p_demux, "We have a timeout of %d seconds", timeout );
1244 mtime_t interval = (timeout - 2) * CLOCK_FREQ;
1245 vlc_timer_schedule( p_sys->timer, false, interval, interval);
1247 p_sys->i_pcr = VLC_TS_INVALID;
1249 /* Retrieve the starttime if possible */
1250 p_sys->f_npt_start = p_sys->ms->playStartTime();
1251 if( p_sys->ms->playEndTime() > 0 )
1252 p_sys->f_npt_length = p_sys->ms->playEndTime();
1254 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1255 return VLC_SUCCESS;
1259 /*****************************************************************************
1260 * Demux:
1261 *****************************************************************************/
1262 static int Demux( demux_t *p_demux )
1264 demux_sys_t *p_sys = p_demux->p_sys;
1265 TaskToken task;
1267 bool b_send_pcr = true;
1268 int i;
1270 /* Protect Live555 from simultaneous calls in TimeoutPrevention()
1271 during pause */
1272 vlc_mutex_locker locker(&p_sys->timeout_mutex);
1274 for( i = 0; i < p_sys->i_track; i++ )
1276 live_track_t *tk = p_sys->track[i];
1278 if( tk->p_es )
1280 bool b;
1281 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1282 if( !b && tk->b_selected && p_sys->rtsp )
1284 tk->b_selected = false;
1285 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1287 else if( b && !tk->b_selected)
1289 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1290 var_GetBool( p_demux, "rtsp-http" );
1291 p_sys->rtsp->sendSetupCommand( *tk->sub, default_live555_callback, False,
1292 toBool( b_rtsp_tcp ),
1293 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
1294 if( !wait_Live555_response( p_demux ) )
1296 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
1297 tk->sub->mediumName(), tk->sub->codecName(),
1298 p_sys->env->getResultMsg() );
1300 else
1302 p_sys->rtsp->sendPlayCommand( *tk->sub, default_live555_callback, -1, -1, p_sys->ms->scale() );
1303 if( !wait_Live555_response(p_demux) )
1305 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1306 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1308 else
1309 tk->b_selected = true;
1311 if( !tk->b_selected )
1312 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1316 if( tk->format == live_track_t::ASF_STREAM ||
1317 tk->format == live_track_t::MULTIPLEXED_STREAM )
1319 b_send_pcr = false;
1323 /* First warn we want to read data */
1324 p_sys->event_data = 0;
1325 for( i = 0; i < p_sys->i_track; i++ )
1327 live_track_t *tk = p_sys->track[i];
1329 if( tk->waiting == 0 )
1331 tk->waiting = 1;
1332 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1333 StreamRead, tk, StreamClose, tk );
1336 /* Create a task that will be called if we wait more than 300ms */
1337 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1339 /* Do the read */
1340 p_sys->scheduler->doEventLoop( &p_sys->event_data );
1342 /* remove the task */
1343 p_sys->scheduler->unscheduleDelayedTask( task );
1345 if( b_send_pcr )
1347 mtime_t i_minpcr = VLC_TS_INVALID;
1348 bool b_need_flush = false;
1350 /* Check for gap in pts value */
1351 for( i = 0; i < p_sys->i_track; i++ )
1353 live_track_t *tk = p_sys->track[i];
1355 if( !tk->b_selected ||
1356 (p_sys->b_rtcp_sync && !tk->b_rtcp_sync) )
1357 continue;
1359 /* Check for gap in pts value */
1360 b_need_flush |= (tk->b_flushing_discontinuity);
1362 if( i_minpcr == VLC_TS_INVALID || i_minpcr > tk->i_pcr )
1363 i_minpcr = tk->i_pcr;
1366 if( p_sys->i_pcr > VLC_TS_INVALID && b_need_flush )
1368 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1369 p_sys->i_pcr = i_minpcr;
1370 p_sys->f_npt = 0.;
1372 for( i = 0; i < p_sys->i_track; i++ )
1374 live_track_t *tk = p_sys->track[i];
1375 tk->i_lastpts = VLC_TS_INVALID;
1376 tk->i_pcr = VLC_TS_INVALID;
1377 tk->f_npt = 0.;
1378 tk->b_flushing_discontinuity = false;
1379 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1381 if( p_sys->i_pcr != VLC_TS_INVALID )
1382 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
1384 else if( p_sys->i_pcr == VLC_TS_INVALID ||
1385 i_minpcr > p_sys->i_pcr + CLOCK_FREQ / 4 )
1387 p_sys->i_pcr = i_minpcr;
1388 if( p_sys->i_pcr != VLC_TS_INVALID )
1389 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
1393 if( p_sys->b_multicast && p_sys->b_no_data &&
1394 ( p_sys->i_no_data_ti > 120 ) )
1396 /* FIXME Make this configurable
1397 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1398 return 0;
1401 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1402 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1404 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1405 var_GetBool( p_demux, "rtsp-http" );
1407 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1409 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1410 if( RollOverTcp( p_demux ) )
1412 msg_Err( p_demux, "TCP rollover failed, aborting" );
1413 return 0;
1415 return 1;
1417 msg_Err( p_demux, "no data received in 10s, aborting" );
1418 return 0;
1420 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1421 ( p_sys->i_no_data_ti > 34 ) )
1423 /* EOF ? */
1424 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1425 return 0;
1427 return p_sys->b_error ? 0 : 1;
1430 /*****************************************************************************
1431 * Control:
1432 *****************************************************************************/
1433 static int Control( demux_t *p_demux, int i_query, va_list args )
1435 demux_sys_t *p_sys = p_demux->p_sys;
1436 int64_t *pi64, i64;
1437 double *pf, f;
1438 bool *pb;
1440 vlc_mutex_locker locker(&p_sys->timeout_mutex); /* (see same in Demux) */
1442 switch( i_query )
1444 case DEMUX_GET_TIME:
1445 pi64 = va_arg( args, int64_t * );
1446 if( p_sys->f_npt > 0 )
1448 *pi64 = (int64_t)(p_sys->f_npt * 1000000.);
1449 return VLC_SUCCESS;
1451 return VLC_EGENERIC;
1453 case DEMUX_GET_LENGTH:
1454 pi64 = va_arg( args, int64_t * );
1455 if( p_sys->f_npt_length > 0 )
1457 double d_length = p_sys->f_npt_length * 1000000.0;
1458 if( d_length >= INT64_MAX )
1459 *pi64 = INT64_MAX;
1460 else
1461 *pi64 = (int64_t)d_length;
1462 return VLC_SUCCESS;
1464 return VLC_EGENERIC;
1466 case DEMUX_GET_POSITION:
1467 pf = va_arg( args, double * );
1468 if( (p_sys->f_npt_length > 0) && (p_sys->f_npt > 0) )
1470 *pf = p_sys->f_npt / p_sys->f_npt_length;
1471 return VLC_SUCCESS;
1473 return VLC_EGENERIC;
1475 case DEMUX_SET_POSITION:
1476 case DEMUX_SET_TIME:
1477 if( p_sys->rtsp && (p_sys->f_npt_length > 0) )
1479 float time;
1481 if( (i_query == DEMUX_SET_TIME) && (p_sys->f_npt > 0) )
1483 i64 = va_arg( args, int64_t );
1484 time = (float)(i64 / 1000000.0); /* in second */
1486 else if( i_query == DEMUX_SET_TIME )
1487 return VLC_EGENERIC;
1488 else
1490 f = va_arg( args, double );
1491 time = f * p_sys->f_npt_length; /* in second */
1494 if( p_sys->b_paused )
1496 p_sys->f_seek_request = time;
1497 return VLC_SUCCESS;
1500 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1502 if( !wait_Live555_response( p_demux ) )
1504 msg_Err( p_demux, "PAUSE before seek failed %s",
1505 p_sys->env->getResultMsg() );
1506 return VLC_EGENERIC;
1509 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1511 if( !wait_Live555_response( p_demux ) )
1513 msg_Err( p_demux, "seek PLAY failed %s",
1514 p_sys->env->getResultMsg() );
1515 return VLC_EGENERIC;
1517 p_sys->i_pcr = VLC_TS_INVALID;
1519 for( int i = 0; i < p_sys->i_track; i++ )
1521 p_sys->track[i]->b_rtcp_sync = false;
1522 p_sys->track[i]->i_lastpts = VLC_TS_INVALID;
1523 p_sys->track[i]->i_pcr = VLC_TS_INVALID;
1526 /* Retrieve the starttime if possible */
1527 p_sys->f_npt = p_sys->f_npt_start = p_sys->ms->playStartTime();
1529 /* Retrieve the duration if possible */
1530 if( p_sys->ms->playEndTime() > 0 )
1531 p_sys->f_npt_length = p_sys->ms->playEndTime();
1533 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1534 return VLC_SUCCESS;
1536 return VLC_EGENERIC;
1538 /* Special for access_demux */
1539 case DEMUX_CAN_PAUSE:
1540 case DEMUX_CAN_SEEK:
1541 pb = va_arg( args, bool * );
1542 if( p_sys->rtsp && p_sys->f_npt_length > 0 )
1543 /* Not always true, but will be handled in SET_PAUSE_STATE */
1544 *pb = true;
1545 else
1546 *pb = false;
1547 return VLC_SUCCESS;
1549 case DEMUX_CAN_CONTROL_PACE:
1550 pb = va_arg( args, bool * );
1552 #if 1 /* Disable for now until we have a clock synchro algo
1553 * which works with something else than MPEG over UDP */
1554 *pb = false;
1555 #else
1556 *pb = true;
1557 #endif
1558 return VLC_SUCCESS;
1560 case DEMUX_CAN_CONTROL_RATE:
1561 pb = va_arg( args, bool * );
1563 *pb = (p_sys->rtsp != NULL) &&
1564 (p_sys->f_npt_length > 0) &&
1565 ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1566 !var_GetBool( p_demux, "rtsp-wmserver" ) );
1567 return VLC_SUCCESS;
1569 case DEMUX_SET_RATE:
1571 int *pi_int;
1572 double f_scale, f_old_scale;
1574 if( !p_sys->rtsp || (p_sys->f_npt_length <= 0) ||
1575 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1576 var_GetBool( p_demux, "rtsp-wmserver" ) )
1577 return VLC_EGENERIC;
1579 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1580 * supports Scale:
1582 * "[...] should try to approximate the viewing rate, but
1583 * may restrict the range of scale values that it supports.
1584 * The response MUST contain the actual scale value chosen
1585 * by the server."
1587 * Scale = 1 indicates normal play
1588 * Scale > 1 indicates fast forward
1589 * Scale < 1 && Scale > 0 indicates slow motion
1590 * Scale < 0 value indicates rewind
1593 pi_int = va_arg( args, int * );
1594 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1595 f_old_scale = p_sys->ms->scale();
1597 /* Passing -1 for the start and end time will mean liveMedia won't
1598 * create a Range: section for the RTSP message. The server should
1599 * pick up from the current position */
1600 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1602 if( !wait_Live555_response( p_demux ) )
1604 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1605 p_sys->env->getResultMsg() );
1606 return VLC_EGENERIC;
1609 if( p_sys->ms->scale() == f_old_scale )
1611 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1612 p_sys->ms->scale() );
1613 return VLC_EGENERIC;
1616 /* ReSync the stream */
1617 p_sys->f_npt_start = 0;
1618 p_sys->i_pcr = VLC_TS_INVALID;
1619 p_sys->f_npt = 0.0;
1621 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1622 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1623 return VLC_SUCCESS;
1626 case DEMUX_SET_PAUSE_STATE:
1628 bool b_pause = (bool)va_arg( args, int );
1629 if( p_sys->rtsp == NULL )
1630 return VLC_EGENERIC;
1632 if( b_pause == p_sys->b_paused )
1633 return VLC_SUCCESS;
1634 if( b_pause )
1635 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1636 else
1637 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1638 -1.0f, p_sys->ms->scale() );
1640 if( !wait_Live555_response( p_demux ) )
1642 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1643 return VLC_EGENERIC;
1645 p_sys->f_seek_request = -1;
1646 p_sys->b_paused = b_pause;
1648 if( !p_sys->b_paused )
1650 for( int i = 0; i < p_sys->i_track; i++ )
1652 live_track_t *tk = p_sys->track[i];
1653 tk->b_rtcp_sync = false;
1654 tk->b_flushing_discontinuity = false;
1655 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1656 tk->i_lastpts = VLC_TS_INVALID;
1657 tk->i_pcr = VLC_TS_INVALID;
1659 p_sys->i_pcr = VLC_TS_INVALID;
1660 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1663 /* Reset data received counter */
1664 p_sys->i_no_data_ti = 0;
1666 /* Retrieve the starttime if possible */
1667 p_sys->f_npt_start = p_sys->ms->playStartTime();
1669 /* Retrieve the duration if possible */
1670 if( p_sys->ms->playEndTime() )
1671 p_sys->f_npt_length = p_sys->ms->playEndTime();
1673 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1675 return VLC_SUCCESS;
1677 case DEMUX_GET_TITLE_INFO:
1678 case DEMUX_SET_TITLE:
1679 case DEMUX_SET_SEEKPOINT:
1680 return VLC_EGENERIC;
1682 case DEMUX_GET_PTS_DELAY:
1683 pi64 = va_arg( args, int64_t * );
1684 *pi64 = INT64_C(1000)
1685 * var_InheritInteger( p_demux, "network-caching" );
1686 return VLC_SUCCESS;
1688 default:
1689 return VLC_EGENERIC;
1693 /*****************************************************************************
1694 * RollOverTcp: reopen the rtsp into TCP mode
1695 * XXX: ugly, a lot of code are duplicated from Open()
1696 * This should REALLY be fixed
1697 *****************************************************************************/
1698 static int RollOverTcp( demux_t *p_demux )
1700 demux_sys_t *p_sys = p_demux->p_sys;
1701 int i, i_return;
1703 var_SetBool( p_demux, "rtsp-tcp", true );
1705 /* We close the old RTSP session */
1706 vlc_timer_schedule(p_sys->timer, false, 0, 0);
1707 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1708 Medium::close( p_sys->ms );
1709 RTSPClient::close( p_sys->rtsp );
1711 for( i = 0; i < p_sys->i_track; i++ )
1713 live_track_t *tk = p_sys->track[i];
1715 if( tk->p_out_muxed ) vlc_demux_chained_Delete( tk->p_out_muxed );
1716 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1717 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1718 es_format_Clean( &tk->fmt );
1719 free( tk->p_buffer );
1720 free( tk );
1722 TAB_CLEAN( p_sys->i_track, p_sys->track );
1723 if( p_sys->p_out_asf ) vlc_demux_chained_Delete( p_sys->p_out_asf );
1725 p_sys->ms = NULL;
1726 p_sys->rtsp = NULL;
1727 p_sys->b_no_data = true;
1728 p_sys->i_no_data_ti = 0;
1729 p_sys->p_out_asf = NULL;
1731 /* Reopen rtsp client */
1732 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1734 msg_Err( p_demux, "Failed to connect with %s", p_sys->psz_pl_url );
1735 goto error;
1738 if( p_sys->p_sdp == NULL )
1740 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1741 goto error;
1744 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1746 msg_Err( p_demux, "Nothing to play for %s", p_sys->psz_pl_url );
1747 goto error;
1750 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1751 goto error;
1753 return VLC_SUCCESS;
1755 error:
1756 return VLC_EGENERIC;
1760 /*****************************************************************************
1762 *****************************************************************************/
1763 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1764 bool b_marker,
1765 const uint8_t *p_data, unsigned i_size )
1767 const unsigned i_packet_size = p_demux->p_sys->asfh.i_min_data_packet_size;
1768 block_t *p_list = NULL;
1770 while( i_size >= 4 )
1772 unsigned i_flags = p_data[0];
1773 unsigned i_length_offset = (p_data[1] << 16) |
1774 (p_data[2] << 8) |
1775 (p_data[3] );
1776 bool b_length = i_flags & 0x40;
1777 bool b_relative_ts = i_flags & 0x20;
1778 bool b_duration = i_flags & 0x10;
1779 bool b_location_id = i_flags & 0x08;
1781 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1782 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1783 unsigned i_header_size = 4;
1784 if( b_relative_ts )
1785 i_header_size += 4;
1786 if( b_duration )
1787 i_header_size += 4;
1788 if( b_location_id )
1789 i_header_size += 4;
1791 if( i_header_size > i_size )
1793 msg_Warn( p_demux, "Invalid header size" );
1794 break;
1797 /* XXX
1798 * When b_length is true, the streams I found do not seems to respect
1799 * the documentation.
1800 * From them, I have failed to find which choice between '__MIN()' or
1801 * 'i_length_offset - i_header_size' is the right one.
1803 unsigned i_payload;
1804 if( b_length )
1805 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1806 else
1807 i_payload = i_size - i_header_size;
1809 if( !tk->p_asf_block )
1811 tk->p_asf_block = block_Alloc( i_packet_size );
1812 if( !tk->p_asf_block )
1813 break;
1814 tk->p_asf_block->i_buffer = 0;
1816 unsigned i_offset = b_length ? 0 : i_length_offset;
1817 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1819 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1820 tk->p_asf_block->i_buffer += i_payload;
1821 if( b_marker )
1823 /* We have a complete packet */
1824 tk->p_asf_block->i_buffer = i_packet_size;
1825 block_ChainAppend( &p_list, tk->p_asf_block );
1826 tk->p_asf_block = NULL;
1829 else
1831 /* Reset on broken stream */
1832 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1833 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1834 tk->p_asf_block->i_buffer = 0;
1837 /* */
1838 p_data += i_header_size + i_payload;
1839 i_size -= i_header_size + i_payload;
1841 return p_list;
1844 /*****************************************************************************
1846 *****************************************************************************/
1847 static void StreamRead( void *p_private, unsigned int i_size,
1848 unsigned int i_truncated_bytes, struct timeval pts,
1849 unsigned int duration )
1851 VLC_UNUSED( duration );
1853 live_track_t *tk = (live_track_t*)p_private;
1854 demux_t *p_demux = tk->p_demux;
1855 demux_sys_t *p_sys = p_demux->p_sys;
1856 block_t *p_block;
1858 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1860 int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1861 (int64_t)pts.tv_usec;
1863 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1864 i_pts &= INT64_C(0x00ffffffffffffff);
1866 /* Retrieve NPT for this pts */
1867 tk->f_npt = tk->sub->getNormalPlayTime(pts);
1869 if( tk->format == live_track_t::QUICKTIME_STREAM && tk->p_es == NULL )
1871 QuickTimeGenericRTPSource *qtRTPSource =
1872 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1873 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1874 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1876 /* Get codec information from the quicktime atoms :
1877 * http://developer.apple.com/quicktime/icefloe/dispatch026.html */
1878 if( tk->fmt.i_cat == VIDEO_ES ) {
1879 if( qtState.sdAtomSize < 16 + 32 )
1881 /* invalid */
1882 p_sys->event_data = 0xff;
1883 tk->waiting = 0;
1884 return;
1886 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1887 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1888 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1890 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1892 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1893 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1894 + qtRTPSource->qtState.sdAtomSize;
1895 while (pos+8 < endpos) {
1896 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1897 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1898 if( memcmp(pos+4, "avcC", 4) == 0 &&
1899 atomLength > 8 &&
1900 atomLength <= INT_MAX )
1902 tk->fmt.i_extra = atomLength-8;
1903 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1904 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1905 break;
1907 pos += atomLength;
1910 else
1912 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1913 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1914 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1917 else {
1918 if( qtState.sdAtomSize < 24 )
1920 /* invalid */
1921 p_sys->event_data = 0xff;
1922 tk->waiting = 0;
1923 return;
1925 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1926 tk->fmt.audio.i_bitspersample = (sdAtom[22] << 8) | sdAtom[23];
1928 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1931 #if 0
1932 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1933 i_size,
1934 pts.tv_sec * 1000000LL + pts.tv_usec );
1935 #endif
1937 /* grow buffer if it looks like buffer is too small, but don't eat
1938 * up all the memory on strange streams */
1939 if( i_truncated_bytes > 0 )
1941 if( tk->i_buffer < 2000000 )
1943 void *p_tmp;
1944 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1945 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1946 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1947 if( p_tmp == NULL )
1949 msg_Warn( p_demux, "realloc failed" );
1951 else
1953 tk->p_buffer = (uint8_t*)p_tmp;
1954 tk->i_buffer *= 2;
1958 if( tk->b_discard_trunc )
1960 p_sys->event_data = 0xff;
1961 tk->waiting = 0;
1962 return;
1966 assert( i_size <= tk->i_buffer );
1968 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1969 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1971 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1973 if( (p_block = block_Alloc( i_size + 1 )) )
1975 p_block->p_buffer[0] = amrSource->lastFrameHeader();
1976 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1979 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1981 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1982 uint32_t header = h261Source->lastSpecialHeader();
1983 if( (p_block = block_Alloc( i_size + 4 )) )
1985 memcpy( p_block->p_buffer, &header, 4 );
1986 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1989 else if( tk->fmt.i_codec == VLC_CODEC_H264 || tk->fmt.i_codec == VLC_CODEC_HEVC )
1991 if( tk->fmt.i_codec == VLC_CODEC_H264 && (tk->p_buffer[0] & 0x1f) >= 24 )
1992 msg_Warn( p_demux, "unsupported NAL type for H264" );
1993 else if( tk->fmt.i_codec == VLC_CODEC_HEVC && ((tk->p_buffer[0] & 0x7e)>>1) >= 48 )
1994 msg_Warn( p_demux, "unsupported NAL type for H265" );
1996 /* Normal NAL type */
1997 if( (p_block = block_Alloc( i_size + 4 )) )
1999 p_block->p_buffer[0] = 0x00;
2000 p_block->p_buffer[1] = 0x00;
2001 p_block->p_buffer[2] = 0x00;
2002 p_block->p_buffer[3] = 0x01;
2003 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
2006 else if( tk->format == live_track_t::ASF_STREAM )
2008 p_block = StreamParseAsf( p_demux, tk,
2009 tk->sub->rtpSource()->curPacketMarkerBit(),
2010 tk->p_buffer, i_size );
2012 else
2014 if( (p_block = block_Alloc( i_size )) )
2015 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
2018 /* No data sent. Always in sync then */
2019 if( !tk->b_rtcp_sync && tk->sub->rtpSource() &&
2020 tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
2022 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
2023 p_sys->b_rtcp_sync = tk->b_rtcp_sync = true;
2024 if( tk->i_pcr != VLC_TS_INVALID )
2026 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
2027 const int64_t i_max_diff = CLOCK_FREQ * (( tk->fmt.i_cat == SPU_ES ) ? 60 : 1);
2028 tk->b_flushing_discontinuity = (llabs(i_pts - tk->i_pcr) > i_max_diff);
2029 tk->i_pcr = i_pts;
2033 /* Update our global npt value */
2034 if( tk->f_npt > 0 &&
2035 ( tk->f_npt < p_sys->f_npt_length || p_sys->f_npt_length <= 0 ) )
2036 p_sys->f_npt = tk->f_npt;
2038 if( p_block )
2040 switch( tk->format )
2042 case live_track_t::ASF_STREAM:
2043 vlc_demux_chained_Send( p_sys->p_out_asf, p_block );
2044 break;
2045 case live_track_t::MULTIPLEXED_STREAM:
2046 vlc_demux_chained_Send( tk->p_out_muxed, p_block );
2047 break;
2048 default:
2049 if( i_pts != tk->i_lastpts )
2050 p_block->i_pts = VLC_TS_0 + i_pts;
2051 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
2052 switch( tk->fmt.i_codec )
2054 case VLC_CODEC_MPGV:
2055 case VLC_CODEC_H264:
2056 case VLC_CODEC_HEVC:
2057 case VLC_CODEC_VP8:
2058 p_block->i_dts = VLC_TS_INVALID;
2059 break;
2060 default:
2061 p_block->i_dts = VLC_TS_0 + i_pts;
2062 break;
2065 if( i_truncated_bytes )
2066 p_block->i_flags |= BLOCK_FLAG_CORRUPTED;
2068 if( unlikely(tk->i_next_block_flags) )
2070 p_block->i_flags |= tk->i_next_block_flags;
2071 tk->i_next_block_flags = 0;
2073 es_out_Send( p_demux->out, tk->p_es, p_block );
2074 if( i_pts > 0 )
2076 if( tk->i_pcr < i_pts )
2077 tk->i_pcr = i_pts;
2078 tk->i_lastpts = i_pts;
2080 break;
2084 /* warn that's ok */
2085 p_sys->event_data = 0xff;
2087 /* we have read data */
2088 tk->waiting = 0;
2089 p_demux->p_sys->b_no_data = false;
2090 p_demux->p_sys->i_no_data_ti = 0;
2093 /*****************************************************************************
2095 *****************************************************************************/
2096 static void StreamClose( void *p_private )
2098 live_track_t *tk = (live_track_t*)p_private;
2099 demux_t *p_demux = tk->p_demux;
2100 demux_sys_t *p_sys = p_demux->p_sys;
2101 tk->b_selected = false;
2102 p_sys->event_rtsp = 0xff;
2103 p_sys->event_data = 0xff;
2105 if( tk->p_es )
2106 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
2108 int nb_tracks = 0;
2109 for( int i = 0; i < p_sys->i_track; i++ )
2111 if( p_sys->track[i]->b_selected )
2112 nb_tracks++;
2114 msg_Dbg( p_demux, "RTSP track Close, %d track remaining", nb_tracks );
2115 if( !nb_tracks )
2116 p_sys->b_error = true;
2120 /*****************************************************************************
2122 *****************************************************************************/
2123 static void TaskInterruptRTSP( void *p_private )
2125 demux_t *p_demux = (demux_t*)p_private;
2127 /* Avoid lock */
2128 p_demux->p_sys->event_rtsp = 0xff;
2131 static void TaskInterruptData( void *p_private )
2133 demux_t *p_demux = (demux_t*)p_private;
2135 p_demux->p_sys->i_no_data_ti++;
2137 /* Avoid lock */
2138 p_demux->p_sys->event_data = 0xff;
2141 /*****************************************************************************
2143 *****************************************************************************/
2144 static void TimeoutPrevention( void *p_data )
2146 demux_t *p_demux = (demux_t *) p_data;
2147 demux_sys_t *p_sys = p_demux->p_sys;
2148 char *bye = NULL;
2150 /* Protect Live555 from us calling their functions simultaneously
2151 with Demux() or Control() */
2152 vlc_mutex_locker locker(&p_sys->timeout_mutex);
2154 /* If the timer fires while the demuxer owns the lock, and the demuxer
2155 * then torns the session down, the pointers will become NULL. By the time
2156 * this timer callback obtains the callback, either a new session was
2157 * created and the timer is rescheduled, or the pointers are still NULL
2158 * and the timer is descheduled. In the second case, bail out (then wait
2159 * for the timer to be rescheduled or destroyed). In the first case, this
2160 * might send an early refresh - that´s harmless but suboptimal (FIXME). */
2161 if( p_sys->rtsp == NULL || p_sys->ms == NULL )
2162 return;
2164 bool use_get_param = p_sys->b_get_param;
2166 /* Use GET_PARAMETERS if supported. wmserver dialect supports
2167 * it, but does not report this properly. */
2168 if( var_GetBool( p_demux, "rtsp-wmserver" ) )
2169 use_get_param = true;
2171 if( use_get_param )
2172 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms,
2173 default_live555_callback, bye );
2174 else
2175 p_sys->rtsp->sendOptionsCommand( default_live555_callback, NULL );
2177 if( !wait_Live555_response( p_demux ) )
2179 msg_Err( p_demux, "keep-alive failed: %s",
2180 p_sys->env->getResultMsg() );
2181 /* Just continue, worst case is we get timed out later */
2185 /*****************************************************************************
2187 *****************************************************************************/
2188 static int ParseASF( demux_t *p_demux )
2190 demux_sys_t *p_sys = p_demux->p_sys;
2192 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
2193 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2194 char *psz_end;
2195 block_t *p_header;
2197 /* Parse the asf header */
2198 if( psz_asf == NULL )
2199 return VLC_EGENERIC;
2201 psz_asf += strlen( psz_marker );
2202 psz_asf = strdup( psz_asf ); /* Duplicate it */
2203 psz_end = strchr( psz_asf, '\n' );
2205 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2206 *psz_end-- = '\0';
2208 if( psz_asf >= psz_end )
2210 free( psz_asf );
2211 return VLC_EGENERIC;
2214 /* Always smaller */
2215 p_header = block_Alloc( psz_end - psz_asf );
2216 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2217 p_header->i_buffer, psz_asf );
2218 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2219 if( p_header->i_buffer <= 0 )
2221 free( psz_asf );
2222 return VLC_EGENERIC;
2225 /* Parse it to get packet size */
2226 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2228 /* Send it to demuxer */
2229 vlc_demux_chained_Send( p_sys->p_out_asf, p_header );
2231 free( psz_asf );
2232 return VLC_SUCCESS;
2236 static unsigned char* parseH264ConfigStr( char const* configStr,
2237 unsigned int& configSize )
2239 char *dup, *psz;
2240 size_t i_records = 1;
2242 configSize = 0;
2244 if( configStr == NULL || *configStr == '\0' )
2245 return NULL;
2247 psz = dup = strdup( configStr );
2249 /* Count the number of commas */
2250 for( psz = dup; *psz != '\0'; ++psz )
2252 if( *psz == ',')
2254 ++i_records;
2255 *psz = '\0';
2259 size_t configMax = 5*strlen(dup);
2260 unsigned char *cfg = new unsigned char[configMax];
2261 psz = dup;
2262 for( size_t i = 0; i < i_records; ++i )
2264 cfg[configSize++] = 0x00;
2265 cfg[configSize++] = 0x00;
2266 cfg[configSize++] = 0x00;
2267 cfg[configSize++] = 0x01;
2269 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2270 configMax-configSize, psz );
2271 psz += strlen(psz)+1;
2274 free( dup );
2275 return cfg;
2278 static uint8_t *parseVorbisConfigStr( char const* configStr,
2279 unsigned int& configSize )
2281 configSize = 0;
2282 if( configStr == NULL || *configStr == '\0' )
2283 return NULL;
2284 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1332115200 // 2012.03.20
2285 unsigned char *p_cfg = base64Decode( configStr, configSize );
2286 #else
2287 char* configStr_dup = strdup( configStr );
2288 unsigned char *p_cfg = base64Decode( configStr_dup, configSize );
2289 free( configStr_dup );
2290 #endif
2291 uint8_t *p_extra = NULL;
2292 /* skip header count, ident number and length (cf. RFC 5215) */
2293 const unsigned int headerSkip = 9;
2294 if( configSize > headerSkip && ((uint8_t*)p_cfg)[3] == 1 )
2296 configSize -= headerSkip;
2297 p_extra = (uint8_t*)xmalloc( configSize );
2298 memcpy( p_extra, p_cfg+headerSkip, configSize );
2300 delete[] p_cfg;
2301 return p_extra;
2304 static char *passwordLessURL( vlc_url_t *p_url )
2306 vlc_url_t url;
2308 memcpy( &url, p_url, sizeof( vlc_url_t ) );
2310 url.psz_username = NULL;
2311 url.psz_password = NULL;
2312 if( url.i_port == 0 )
2313 url.i_port = 554;
2314 return vlc_uri_compose( &url );