live555: remove trailing whitespace
[vlc.git] / modules / access / live555.cpp
blob6f8c896292bfab2fddccf52c299797ade70fede7
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", 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, PASS_LONGTEXT)
138 add_integer( "rtsp-frame-buffer-size", DEFAULT_FRAME_BUFFER_SIZE,
139 FRAME_BUFFER_SIZE_TEXT, FRAME_BUFFER_SIZE_LONGTEXT,
140 true )
141 vlc_module_end ()
144 /*****************************************************************************
145 * Local prototypes
146 *****************************************************************************/
148 typedef struct
150 demux_t *p_demux;
151 MediaSubsession *sub;
153 es_format_t fmt;
154 es_out_id_t *p_es;
156 enum
158 SINGLE_STREAM,
159 MULTIPLEXED_STREAM,
160 QUICKTIME_STREAM,
161 ASF_STREAM
162 } format;
164 block_t *p_asf_block;
165 bool b_discard_trunc;
166 vlc_demux_chained_t *p_out_muxed; /* for muxed stream */
168 uint8_t *p_buffer;
169 unsigned int i_buffer;
171 bool b_rtcp_sync;
172 bool b_flushing_discontinuity;
173 int i_next_block_flags;
174 char waiting;
175 int64_t i_lastpts;
176 int64_t i_pcr;
177 double f_npt;
179 enum
181 STATE_NONE,
182 STATE_SELECTED,
183 STATE_IGNORED,
184 STATE_TEARDOWN,
185 } state;
187 } live_track_t;
189 class RTSPClientVlc;
191 #define CAP_RATE_CONTROL (1 << 1)
192 #define CAP_SUBSESSION_TEARDOWN (1 << 2)
193 #define CAP_SUBSESSION_PAUSE (1 << 3)
194 #define CAPS_DEFAULT CAP_RATE_CONTROL
196 struct demux_sys_t
198 char *p_sdp; /* XXX mallocated */
199 char *psz_pl_url; /* password-less URL */
200 vlc_url_t url;
202 MediaSession *ms;
203 TaskScheduler *scheduler;
204 UsageEnvironment *env ;
205 RTSPClientVlc *rtsp;
206 int capabilities; /* Server capabilities workaround */
208 /* */
209 int i_track;
210 live_track_t **track;
212 /* Weird formats */
213 asf_header_t asfh;
214 vlc_demux_chained_t *p_out_asf;
215 bool b_real;
217 /* */
218 mtime_t i_pcr; /* The clock */
219 bool b_rtcp_sync; /* At least one track received sync */
220 double f_npt;
221 double f_npt_length;
222 double f_npt_start;
224 /* timeout thread information */
225 vlc_timer_t timer;
226 vlc_mutex_t timeout_mutex; /* Serialise calls to live555 in timeout thread w.r.t. Demux()/Control() */
228 /* */
229 bool b_force_mcast;
230 bool b_multicast; /* if one of the tracks is multicasted */
231 bool b_no_data; /* if we never received any data */
232 int i_no_data_ti; /* consecutive number of TaskInterrupt */
234 char event_rtsp;
235 char event_data;
237 bool b_get_param; /* Does the server support GET_PARAMETER */
238 bool b_paused; /* Are we paused? */
239 bool b_error;
240 int i_live555_ret; /* live555 callback return code */
242 float f_seek_request;/* In case we receive a seek request while paused*/
246 class RTSPClientVlc : public RTSPClient
248 public:
249 RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
250 char const* applicationName, portNumBits tunnelOverHTTPPortNum,
251 demux_sys_t *p_sys) :
252 RTSPClient( env, rtspURL, verbosityLevel, applicationName,
253 tunnelOverHTTPPortNum
254 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1373932800
255 , -1
256 #endif
259 this->p_sys = p_sys;
261 demux_sys_t *p_sys;
264 static int Demux ( demux_t * );
265 static int Control( demux_t *, int, va_list );
267 static int Connect ( demux_t * );
268 static int SessionsSetup( demux_t * );
269 static int Play ( demux_t *);
270 static int ParseASF ( demux_t * );
271 static int RollOverTcp ( demux_t * );
273 static void StreamRead ( void *, unsigned int, unsigned int,
274 struct timeval, unsigned int );
275 static void StreamClose ( void * );
276 static void TaskInterruptData( void * );
277 static void TaskInterruptRTSP( void * );
279 static void TimeoutPrevention( void * );
281 static unsigned char* parseH264ConfigStr( char const* configStr,
282 unsigned int& configSize );
283 static unsigned char* parseVorbisConfigStr( char const* configStr,
284 unsigned int& configSize );
286 static char *passwordLessURL( vlc_url_t *url );
288 #define PCR_OBS (CLOCK_FREQ / 4)
289 #define PCR_OFF PCR_OBS
291 /*****************************************************************************
292 * DemuxOpen:
293 *****************************************************************************/
294 static int Open ( vlc_object_t *p_this )
296 demux_t *p_demux = (demux_t*)p_this;
297 demux_sys_t *p_sys = NULL;
299 int i_return;
300 int i_error = VLC_EGENERIC;
302 if (p_demux->out == NULL)
303 return VLC_EGENERIC;
305 /* if the rtsp URL may contain a sat.ip fake DNS, bail-out early and
306 * let the SAT>IP module handle that */
307 if( !strncmp(p_demux->psz_location, "sat.ip", 6) )
309 msg_Err( p_demux, "SAT>IP server, bailing out");
310 return VLC_EGENERIC;
312 /* If satip-host is set on the item, we shall assume it is a rtsp for the
313 * SAT>IP module and bail-out early. */
314 char *psz_host = var_InheritString(p_demux, "satip-host");
315 if (psz_host != NULL) {
316 msg_Err( p_demux, "URL is for SAT>IP, bailing out");
317 free(psz_host);
318 return VLC_EGENERIC;
321 if( p_demux->s )
323 /* See if it looks like a SDP
324 v, o, s fields are mandatory and in this order */
325 const uint8_t *p_peek;
326 if( vlc_stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
328 if( memcmp( p_peek, "v=0\r\n", 5 ) &&
329 memcmp( p_peek, "v=0\n", 4 ) &&
330 ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
332 return VLC_EGENERIC;
336 p_demux->pf_demux = Demux;
337 p_demux->pf_control= Control;
338 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
339 if( !p_sys ) return VLC_ENOMEM;
341 if( vlc_timer_create(&p_sys->timer, TimeoutPrevention, p_demux) )
343 free( p_sys );
344 return VLC_ENOMEM;
347 msg_Dbg( p_demux, "version " LIVEMEDIA_LIBRARY_VERSION_STRING );
349 p_sys->capabilities = CAPS_DEFAULT;
350 if( var_GetBool( p_demux, "rtsp-kasenna" ) ||
351 var_GetBool( p_demux, "rtsp-wmserver" ) )
353 p_sys->capabilities &= ~CAP_RATE_CONTROL;
356 TAB_INIT( p_sys->i_track, p_sys->track );
357 p_sys->b_no_data = true;
358 p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
359 p_sys->f_seek_request = -1;
360 vlc_mutex_init(&p_sys->timeout_mutex);
362 /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
363 vlc_UrlParse( &p_sys->url, p_demux->psz_url );
365 if( ( p_sys->psz_pl_url = passwordLessURL( &p_sys->url ) ) == NULL )
367 i_error = VLC_ENOMEM;
368 goto error;
371 if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
373 msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
374 goto error;
376 if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
378 msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
379 goto error;
382 if( p_demux->s != NULL )
384 char *p = p_sys->psz_pl_url;
385 while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
388 if( p_demux->s != NULL )
390 /* Gather the complete sdp file */
391 int i_sdp = 0;
392 int i_sdp_max = 1000;
393 uint8_t *p_sdp = (uint8_t*) malloc( i_sdp_max );
395 if( !p_sdp )
397 i_error = VLC_ENOMEM;
398 goto error;
401 for( ;; )
403 int i_read = vlc_stream_Read( p_demux->s, &p_sdp[i_sdp],
404 i_sdp_max - i_sdp - 1 );
405 if( i_read < 0 )
407 msg_Err( p_demux, "failed to read SDP" );
408 free( p_sdp );
409 goto error;
412 i_sdp += i_read;
414 if( i_read < i_sdp_max - i_sdp - 1 )
416 p_sdp[i_sdp] = '\0';
417 break;
420 i_sdp_max += 1000;
421 p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
423 p_sys->p_sdp = (char*)p_sdp;
425 else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
427 msg_Err( p_demux, "Failed to connect with %s", p_sys->psz_pl_url );
428 goto error;
431 if( p_sys->p_sdp == NULL )
433 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
434 i_error = VLC_ENOMEM;
435 goto error;
438 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
440 msg_Err( p_demux, "Nothing to play for %s", p_sys->psz_pl_url );
441 goto error;
444 if( p_sys->b_real ) goto error;
446 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
447 goto error;
449 if( p_sys->p_out_asf && ParseASF( p_demux ) )
451 msg_Err( p_demux, "cannot find a usable asf header" );
452 /* TODO Clean tracks */
453 goto error;
456 if( p_sys->i_track <= 0 )
457 goto error;
459 return VLC_SUCCESS;
461 error:
462 Close( p_this );
463 return i_error;
466 /*****************************************************************************
467 * DemuxClose:
468 *****************************************************************************/
469 static void Close( vlc_object_t *p_this )
471 demux_t *p_demux = (demux_t*)p_this;
472 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
474 vlc_timer_destroy(p_sys->timer);
476 if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
477 if( p_sys->ms ) Medium::close( p_sys->ms );
478 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
479 if( p_sys->env ) p_sys->env->reclaim();
481 for( int i = 0; i < p_sys->i_track; i++ )
483 live_track_t *tk = p_sys->track[i];
485 if( tk->p_out_muxed )
486 vlc_demux_chained_Delete( tk->p_out_muxed );
487 es_format_Clean( &tk->fmt );
488 free( tk->p_buffer );
489 free( tk );
491 TAB_CLEAN( p_sys->i_track, p_sys->track );
492 if( p_sys->p_out_asf )
493 vlc_demux_chained_Delete( p_sys->p_out_asf );
494 delete p_sys->scheduler;
495 free( p_sys->p_sdp );
496 free( p_sys->psz_pl_url );
498 vlc_UrlClean( &p_sys->url );
499 vlc_mutex_destroy(&p_sys->timeout_mutex);
501 free( p_sys );
504 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
506 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
508 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
509 demux_sys_t *p_sys = client_vlc->p_sys;
510 delete []result_string;
511 p_sys->i_live555_ret = result_code;
512 p_sys->b_error = p_sys->i_live555_ret != 0;
513 p_sys->event_rtsp = 1;
516 /* return true if the RTSP command succeeded */
517 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
519 TaskToken task;
520 demux_sys_t * p_sys = (demux_sys_t *)p_demux->p_sys;
521 p_sys->event_rtsp = 0;
522 if( i_timeout > 0 )
524 /* Create a task that will be called if we wait more than timeout ms */
525 task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000,
526 TaskInterruptRTSP,
527 p_demux );
529 p_sys->event_rtsp = 0;
530 p_sys->b_error = true;
531 p_sys->i_live555_ret = 0;
532 p_sys->scheduler->doEventLoop( &p_sys->event_rtsp );
533 //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
534 if( i_timeout > 0 )
536 /* remove the task */
537 p_sys->scheduler->unscheduleDelayedTask( task );
539 return !p_sys->b_error;
542 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
543 char* result_string )
545 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
546 demux_sys_t *p_sys = client_vlc->p_sys;
547 p_sys->i_live555_ret = result_code;
548 if ( result_code == 0 )
550 char* sdpDescription = result_string;
551 free( p_sys->p_sdp );
552 p_sys->p_sdp = NULL;
553 if( sdpDescription )
555 p_sys->p_sdp = strdup( sdpDescription );
556 p_sys->b_error = false;
559 else
560 p_sys->b_error = true;
561 delete[] result_string;
562 p_sys->event_rtsp = 1;
563 #ifdef VLC_PATCH_RTSPCLIENT_SERVERSTRING
564 if( client_vlc->serverString() )
566 if( !strncmp(client_vlc->serverString(), "Kasenna", 7) ||
567 !strncmp(client_vlc->serverString(), "WMServer", 8) )
568 p_sys->capabilities &= ~CAP_RATE_CONTROL;
569 if( !strncmp(client_vlc->serverString(), "VLC/", 4) )
570 p_sys->capabilities |= (CAP_SUBSESSION_TEARDOWN|CAP_SUBSESSION_PAUSE);
572 #endif
575 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
576 char* result_string )
578 RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
579 demux_sys_t *p_sys = client_vlc->p_sys;
580 p_sys->b_get_param =
581 // If OPTIONS fails, assume GET_PARAMETER is not supported but
582 // still continue on with the stream. Some servers (foscam)
583 // return 501/not implemented for OPTIONS.
584 result_code == 0
585 && result_string != NULL
586 && strstr( result_string, "GET_PARAMETER" ) != NULL;
587 client->sendDescribeCommand( continueAfterDESCRIBE );
588 delete[] result_string;
591 /*****************************************************************************
592 * Connect: connects to the RTSP server to setup the session DESCRIBE
593 *****************************************************************************/
594 static int Connect( demux_t *p_demux )
596 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
597 Authenticator authenticator;
598 vlc_credential credential;
599 const char *psz_user = NULL;
600 const char *psz_pwd = NULL;
601 int i_http_port = 0;
602 int i_ret = VLC_SUCCESS;
603 const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
605 vlc_credential_init( &credential, &p_sys->url );
607 /* Credentials can be NULL since they may not be needed */
608 if( vlc_credential_get( &credential, p_demux, "rtsp-user", "rtsp-pwd",
609 NULL, NULL) )
611 psz_user = credential.psz_username;
612 psz_pwd = credential.psz_password;
615 createnew:
616 /* FIXME: This is naive and incorrect; it does not prevent the thread
617 * getting stuck in blocking socket operations. */
618 if( vlc_killed() )
620 i_ret = VLC_EGENERIC;
621 goto bailout;
624 if( var_CreateGetBool( p_demux, "rtsp-http" ) )
625 i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
627 p_sys->rtsp = new (std::nothrow) RTSPClientVlc( *p_sys->env, p_sys->psz_pl_url,
628 var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
629 "LibVLC/" VERSION, i_http_port, p_sys );
630 if( !p_sys->rtsp )
632 msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
633 p_sys->env->getResultMsg() );
634 i_ret = VLC_EGENERIC;
635 goto bailout;
638 /* Kasenna enables KeepAlive by analysing the User-Agent string.
639 * Appending _KA to the string should be enough to enable this feature,
640 * however, there is a bug where the _KA doesn't get parsed from the
641 * default User-Agent as created by VLC/Live555 code. This is probably due
642 * to spaces in the string or the string being too long. Here we override
643 * the default string with a more compact version.
645 if( var_InheritBool( p_demux, "rtsp-kasenna" ))
647 p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
650 describe:
651 authenticator.setUsernameAndPassword( psz_user, psz_pwd );
653 p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
655 if( !wait_Live555_response( p_demux, i_timeout ) )
657 int i_code = p_sys->i_live555_ret;
658 if( i_code == 401 )
660 msg_Dbg( p_demux, "authentication failed" );
662 if( vlc_credential_get( &credential, p_demux, "rtsp-user", "rtsp-pwd",
663 _("RTSP authentication"),
664 _("Please enter a valid login name and a password.") ) )
666 psz_user = credential.psz_username;
667 psz_pwd = credential.psz_password;
668 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
669 goto describe;
672 else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
674 /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
675 msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
676 var_SetBool( p_demux, "rtsp-http", true );
677 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
678 p_sys->rtsp = NULL;
679 goto createnew;
681 else
683 if( i_code == 0 )
684 msg_Dbg( p_demux, "connection timeout" );
685 else
687 msg_Dbg( p_demux, "connection error %d", i_code );
688 if( i_code == 403 )
689 vlc_dialog_display_error( p_demux, _("RTSP connection failed"),
690 _("Access to the stream is denied by the server configuration.") );
692 if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
693 p_sys->rtsp = NULL;
695 i_ret = VLC_EGENERIC;
697 else
698 vlc_credential_store( &credential, p_demux );
700 bailout:
701 vlc_credential_clean( &credential );
703 return i_ret;
706 /*****************************************************************************
707 * SessionsSetup: prepares the subsessions and does the SETUP
708 *****************************************************************************/
709 static int SessionsSetup( demux_t *p_demux )
711 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
712 MediaSubsessionIterator *iter = NULL;
713 MediaSubsession *sub = NULL;
715 bool b_rtsp_tcp;
716 int i_client_port;
717 int i_return = VLC_SUCCESS;
718 unsigned int i_receive_buffer = 0;
719 int i_frame_buffer = DEFAULT_FRAME_BUFFER_SIZE;
720 unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
721 const char *p_sess_lang = NULL;
722 const char *p_lang;
724 b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
725 var_GetBool( p_demux, "rtsp-http" );
726 i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
729 /* Create the session from the SDP */
730 if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
732 msg_Err( p_demux, "Could not create the RTSP Session: %s",
733 p_sys->env->getResultMsg() );
734 return VLC_EGENERIC;
737 if( strcmp( p_sys->p_sdp, "m=" ) != 0 )
739 const char *p_sess_attr_end;
741 p_sess_attr_end = strstr( p_sys->p_sdp, "\nm=" );
742 if( !p_sess_attr_end )
743 p_sess_attr_end = strstr( p_sys->p_sdp, "\rm=" );
745 p_sess_lang = p_sess_attr_end ? strstr( p_sys->p_sdp, "a=lang:" ) : NULL;
746 if( p_sess_lang &&
747 p_sess_lang - p_sys->p_sdp > p_sess_attr_end - p_sys->p_sdp )
748 p_sess_lang = NULL;
751 /* Initialise each media subsession */
752 iter = new MediaSubsessionIterator( *p_sys->ms );
753 while( ( sub = iter->next() ) != NULL )
755 Boolean bInit;
756 live_track_t *tk;
758 /* Value taken from mplayer */
759 if( !strcmp( sub->mediumName(), "audio" ) )
760 i_receive_buffer = 100000;
761 else if( !strcmp( sub->mediumName(), "video" ) )
763 int i_var_buf_size = var_InheritInteger( p_demux, "rtsp-frame-buffer-size" );
764 if( i_var_buf_size > 0 )
765 i_frame_buffer = i_var_buf_size;
766 i_receive_buffer = 2000000;
768 else if( !strcmp( sub->mediumName(), "text" ) )
770 else continue;
772 if( strcasestr( sub->codecName(), "REAL" ) )
774 msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
775 p_sys->b_real = true; /* This is a problem, we'll handle it later */
776 continue;
779 if( p_sys->rtsp && i_client_port != -1 )
781 sub->setClientPortNum( i_client_port );
782 i_client_port += 2;
785 if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
786 bInit = sub->initiate( 0 );
787 else
788 bInit = sub->initiate();
790 if( !bInit )
792 msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
793 sub->mediumName(), sub->codecName(),
794 p_sys->env->getResultMsg() );
796 else
798 if( sub->rtpSource() != NULL )
800 int fd = sub->rtpSource()->RTPgs()->socketNum();
802 /* Increase the buffer size */
803 if( i_receive_buffer > 0 )
804 increaseReceiveBufferTo( *p_sys->env, fd, i_receive_buffer );
806 /* Increase the RTP reorder timebuffer just a bit */
807 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
809 msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
810 sub->codecName() );
812 /* Issue the SETUP */
813 if( p_sys->rtsp )
815 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
816 toBool( b_rtsp_tcp ),
817 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
818 if( !wait_Live555_response( p_demux ) )
820 /* if we get an unsupported transport error, toggle TCP
821 * use and try again */
822 if( p_sys->i_live555_ret == 461 )
823 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
824 !toBool( b_rtsp_tcp ), False );
825 if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
827 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
828 sub->mediumName(), sub->codecName(),
829 p_sys->env->getResultMsg() );
830 continue;
832 else
834 var_SetBool( p_demux, "rtsp-tcp", true );
835 b_rtsp_tcp = true;
840 /* Check if we will receive data from this subsession for
841 * this track */
842 if( sub->readSource() == NULL ) continue;
843 if( !p_sys->b_multicast )
845 /* We need different rollover behaviour for multicast */
846 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
849 tk = (live_track_t*)malloc( sizeof( live_track_t ) );
850 if( !tk )
852 delete iter;
853 return VLC_ENOMEM;
855 tk->p_demux = p_demux;
856 tk->sub = sub;
857 tk->p_es = NULL;
858 tk->format = live_track_t::SINGLE_STREAM;
859 tk->p_asf_block = NULL;
860 tk->b_discard_trunc = false;
861 tk->p_out_muxed = NULL;
862 tk->waiting = 0;
863 tk->b_rtcp_sync = false;
864 tk->b_flushing_discontinuity = false;
865 tk->i_next_block_flags = 0;
866 tk->i_lastpts = VLC_TS_INVALID;
867 tk->i_pcr = VLC_TS_INVALID;
868 tk->f_npt = 0.;
869 tk->state = live_track_t::STATE_SELECTED;
870 tk->i_buffer = i_frame_buffer;
871 tk->p_buffer = (uint8_t *)malloc( i_frame_buffer );
873 if( !tk->p_buffer )
875 free( tk );
876 delete iter;
877 return VLC_ENOMEM;
880 /* Value taken from mplayer */
881 if( !strcmp( sub->mediumName(), "audio" ) )
883 es_format_Init( &tk->fmt, AUDIO_ES, VLC_CODEC_UNKNOWN );
884 tk->fmt.audio.i_channels = sub->numChannels();
885 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
887 if( !strcmp( sub->codecName(), "MPA" ) ||
888 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
889 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
891 tk->fmt.i_codec = VLC_CODEC_MPGA;
892 tk->fmt.audio.i_rate = 0;
894 else if( !strcmp( sub->codecName(), "AC3" ) )
896 tk->fmt.i_codec = VLC_CODEC_A52;
897 tk->fmt.audio.i_rate = 0;
899 else if( !strcmp( sub->codecName(), "L16" ) )
901 tk->fmt.i_codec = VLC_CODEC_S16B;
902 tk->fmt.audio.i_bitspersample = 16;
904 else if( !strcmp( sub->codecName(), "L20" ) )
906 tk->fmt.i_codec = VLC_CODEC_S20B;
907 tk->fmt.audio.i_bitspersample = 20;
909 else if( !strcmp( sub->codecName(), "L24" ) )
911 tk->fmt.i_codec = VLC_CODEC_S24B;
912 tk->fmt.audio.i_bitspersample = 24;
914 else if( !strcmp( sub->codecName(), "L8" ) )
916 tk->fmt.i_codec = VLC_CODEC_U8;
917 tk->fmt.audio.i_bitspersample = 8;
919 else if( !strcmp( sub->codecName(), "DAT12" ) )
921 tk->fmt.i_codec = VLC_CODEC_DAT12;
922 tk->fmt.audio.i_bitspersample = 12;
924 else if( !strcmp( sub->codecName(), "PCMU" ) )
926 tk->fmt.i_codec = VLC_CODEC_MULAW;
927 tk->fmt.audio.i_bitspersample = 8;
929 else if( !strcmp( sub->codecName(), "PCMA" ) )
931 tk->fmt.i_codec = VLC_CODEC_ALAW;
932 tk->fmt.audio.i_bitspersample = 8;
934 else if( !strncmp( sub->codecName(), "G726", 4 ) )
936 tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
937 tk->fmt.audio.i_rate = 8000;
938 tk->fmt.audio.i_channels = 1;
939 if( !strcmp( sub->codecName()+5, "40" ) )
940 tk->fmt.i_bitrate = 40000;
941 else if( !strcmp( sub->codecName()+5, "32" ) )
942 tk->fmt.i_bitrate = 32000;
943 else if( !strcmp( sub->codecName()+5, "24" ) )
944 tk->fmt.i_bitrate = 24000;
945 else if( !strcmp( sub->codecName()+5, "16" ) )
946 tk->fmt.i_bitrate = 16000;
948 else if( !strcmp( sub->codecName(), "AMR" ) )
950 tk->fmt.i_codec = VLC_CODEC_AMR_NB;
952 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
954 tk->fmt.i_codec = VLC_CODEC_AMR_WB;
956 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
958 unsigned int i_extra;
959 uint8_t *p_extra;
961 tk->fmt.i_codec = VLC_CODEC_MP4A;
963 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
964 i_extra ) ) )
966 tk->fmt.i_extra = i_extra;
967 tk->fmt.p_extra = xmalloc( i_extra );
968 memcpy( tk->fmt.p_extra, p_extra, i_extra );
969 delete[] p_extra;
971 /* Because the "faad" decoder does not handle the LATM
972 * data length field at the start of each returned LATM
973 * frame, tell the RTP source to omit. */
974 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
976 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
978 unsigned int i_extra;
979 uint8_t *p_extra;
981 tk->fmt.i_codec = VLC_CODEC_MP4A;
983 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
984 i_extra ) ) )
986 tk->fmt.i_extra = i_extra;
987 tk->fmt.p_extra = xmalloc( i_extra );
988 memcpy( tk->fmt.p_extra, p_extra, i_extra );
989 delete[] p_extra;
992 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
994 tk->format = live_track_t::ASF_STREAM;
995 if( p_sys->p_out_asf == NULL )
996 p_sys->p_out_asf =
997 vlc_demux_chained_New( VLC_OBJECT(p_demux), "asf",
998 p_demux->out );
1000 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1001 !strcmp( sub->codecName(), "X-QUICKTIME" ) )
1003 tk->format = live_track_t::QUICKTIME_STREAM;
1005 else if( !strcmp( sub->codecName(), "SPEEX" ) )
1007 tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
1009 else if( !strcmp( sub->codecName(), "VORBIS" ) )
1011 tk->fmt.i_codec = VLC_CODEC_VORBIS;
1012 unsigned int i_extra;
1013 unsigned char *p_extra;
1014 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
1015 i_extra ) ) )
1017 tk->fmt.i_extra = i_extra;
1018 tk->fmt.p_extra = p_extra;
1020 else
1021 msg_Warn( p_demux,"Missing or unsupported vorbis header." );
1023 else if( !strcmp( sub->codecName(), "OPUS" ) )
1025 tk->fmt.i_codec = VLC_CODEC_OPUS;
1028 else if( !strcmp( sub->mediumName(), "video" ) )
1030 es_format_Init( &tk->fmt, VIDEO_ES, VLC_CODEC_UNKNOWN );
1031 if( !strcmp( sub->codecName(), "MPV" ) )
1033 tk->fmt.i_codec = VLC_CODEC_MPGV;
1034 tk->fmt.b_packetized = false;
1036 else if( !strcmp( sub->codecName(), "H263" ) ||
1037 !strcmp( sub->codecName(), "H263-1998" ) ||
1038 !strcmp( sub->codecName(), "H263-2000" ) )
1040 tk->fmt.i_codec = VLC_CODEC_H263;
1042 else if( !strcmp( sub->codecName(), "H261" ) )
1044 tk->fmt.i_codec = VLC_CODEC_H261;
1046 else if( !strcmp( sub->codecName(), "H264" ) )
1048 unsigned int i_extra = 0;
1049 uint8_t *p_extra = NULL;
1051 tk->fmt.i_codec = VLC_CODEC_H264;
1052 tk->fmt.b_packetized = false;
1054 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
1055 i_extra ) ) )
1057 tk->fmt.i_extra = i_extra;
1058 tk->fmt.p_extra = xmalloc( i_extra );
1059 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1061 delete[] p_extra;
1064 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1393372800 // 2014.02.26
1065 else if( !strcmp( sub->codecName(), "H265" ) )
1067 unsigned int i_extra1 = 0, i_extra2 = 0, i_extra3 = 0, i_extraTot;
1068 uint8_t *p_extra1 = NULL, *p_extra2 = NULL, *p_extra3 = NULL;
1070 tk->fmt.i_codec = VLC_CODEC_HEVC;
1071 tk->fmt.b_packetized = false;
1073 p_extra1 = parseH264ConfigStr( sub->fmtp_spropvps(), i_extra1 );
1074 p_extra2 = parseH264ConfigStr( sub->fmtp_spropsps(), i_extra2 );
1075 p_extra3 = parseH264ConfigStr( sub->fmtp_sproppps(), i_extra3 );
1076 i_extraTot = i_extra1 + i_extra2 + i_extra3;
1077 if( i_extraTot > 0 )
1079 tk->fmt.i_extra = i_extraTot;
1080 tk->fmt.p_extra = xmalloc( i_extraTot );
1081 if( p_extra1 )
1083 memcpy( tk->fmt.p_extra, p_extra1, i_extra1 );
1085 if( p_extra2 )
1087 memcpy( ((char*)tk->fmt.p_extra)+i_extra1, p_extra2, i_extra2 );
1089 if( p_extra3 )
1091 memcpy( ((char*)tk->fmt.p_extra)+i_extra1+i_extra2, p_extra3, i_extra3 );
1094 delete[] p_extra1; delete[] p_extra2; delete[] p_extra3;
1097 #endif
1098 else if( !strcmp( sub->codecName(), "JPEG" ) )
1100 tk->fmt.i_codec = VLC_CODEC_MJPG;
1102 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1104 unsigned int i_extra;
1105 uint8_t *p_extra;
1107 tk->fmt.i_codec = VLC_CODEC_MP4V;
1109 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1110 i_extra ) ) )
1112 tk->fmt.i_extra = i_extra;
1113 tk->fmt.p_extra = xmalloc( i_extra );
1114 memcpy( tk->fmt.p_extra, p_extra, i_extra );
1115 delete[] p_extra;
1118 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1119 !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1120 !strcmp( sub->codecName(), "X-QDM" ) ||
1121 !strcmp( sub->codecName(), "X-SV3V-ES" ) ||
1122 !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1124 tk->format = live_track_t::QUICKTIME_STREAM;
1126 else if( !strcmp( sub->codecName(), "MP2T" ) )
1128 tk->format = live_track_t::MULTIPLEXED_STREAM;
1129 tk->p_out_muxed =
1130 vlc_demux_chained_New( VLC_OBJECT(p_demux), "ts",
1131 p_demux->out );
1133 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1134 !strcmp( sub->codecName(), "MP1S" ) )
1136 tk->format = live_track_t::MULTIPLEXED_STREAM;
1137 tk->p_out_muxed =
1138 vlc_demux_chained_New( VLC_OBJECT(p_demux), "ps",
1139 p_demux->out );
1141 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1143 tk->format = live_track_t::ASF_STREAM;
1144 if( p_sys->p_out_asf == NULL )
1145 p_sys->p_out_asf =
1146 vlc_demux_chained_New( VLC_OBJECT(p_demux),
1147 "asf", p_demux->out );
1149 else if( !strcmp( sub->codecName(), "DV" ) )
1151 tk->format = live_track_t::MULTIPLEXED_STREAM;
1152 tk->b_discard_trunc = true;
1153 tk->p_out_muxed =
1154 vlc_demux_chained_New( VLC_OBJECT(p_demux), "rawdv",
1155 p_demux->out );
1157 else if( !strcmp( sub->codecName(), "VP8" ) )
1159 tk->fmt.i_codec = VLC_CODEC_VP8;
1161 else if( !strcmp( sub->codecName(), "THEORA" ) )
1163 tk->fmt.i_codec = VLC_CODEC_THEORA;
1164 unsigned int i_extra;
1165 unsigned char *p_extra;
1166 if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
1167 i_extra ) ) )
1169 tk->fmt.i_extra = i_extra;
1170 tk->fmt.p_extra = p_extra;
1172 else
1173 msg_Warn( p_demux,"Missing or unsupported theora header." );
1176 else if( !strcmp( sub->mediumName(), "text" ) )
1178 es_format_Init( &tk->fmt, SPU_ES, VLC_CODEC_UNKNOWN );
1180 if( !strcmp( sub->codecName(), "T140" ) )
1182 tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1186 /* Try and parse a=lang: attribute */
1187 p_lang = strstr( sub->savedSDPLines(), "a=lang:" );
1188 if( !p_lang )
1189 p_lang = p_sess_lang;
1191 if( p_lang )
1193 unsigned i_lang_len;
1194 p_lang += 7;
1195 i_lang_len = strcspn( p_lang, " \r\n" );
1196 tk->fmt.psz_language = strndup( p_lang, i_lang_len );
1199 if( tk->format == live_track_t::SINGLE_STREAM )
1201 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1204 if( sub->rtcpInstance() != NULL )
1206 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1209 if( tk->p_es ||
1210 tk->format == live_track_t::QUICKTIME_STREAM ||
1211 (tk->format == live_track_t::MULTIPLEXED_STREAM && tk->p_out_muxed ) ||
1212 (tk->format == live_track_t::ASF_STREAM && p_sys->p_out_asf ) )
1214 TAB_APPEND_CAST( (live_track_t **), p_sys->i_track, p_sys->track, tk );
1216 else
1218 /* BUG ??? */
1219 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1220 es_format_Clean( &tk->fmt );
1221 free( tk );
1225 delete iter;
1226 if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1228 /* Retrieve the starttime if possible */
1229 p_sys->f_npt_start = p_sys->ms->playStartTime();
1231 /* Retrieve the duration if possible */
1232 p_sys->f_npt_length = p_sys->ms->playEndTime();
1234 /* */
1235 msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1237 /* */
1238 p_sys->b_no_data = true;
1239 p_sys->i_no_data_ti = 0;
1240 p_sys->b_rtcp_sync = false;
1241 p_sys->i_pcr = VLC_TS_INVALID;
1243 return i_return;
1246 /*****************************************************************************
1247 * Play: starts the actual playback of the stream
1248 *****************************************************************************/
1249 static int Play( demux_t *p_demux )
1251 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1253 if( p_sys->rtsp )
1255 /* The PLAY */
1256 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_npt_start, -1, 1 );
1258 if( !wait_Live555_response(p_demux) )
1260 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1261 return VLC_EGENERIC;
1264 /* Retrieve the timeout value and set up a timeout prevention thread */
1265 int timeout = p_sys->rtsp->sessionTimeoutParameter();
1266 if( timeout <= 2 )
1267 timeout = 60; /* default value from RFC2326 */
1268 msg_Dbg( p_demux, "We have a timeout of %d seconds", timeout );
1270 mtime_t interval = (timeout - 2) * CLOCK_FREQ;
1271 vlc_timer_schedule( p_sys->timer, false, interval, interval);
1273 p_sys->i_pcr = VLC_TS_INVALID;
1275 /* Retrieve the starttime if possible */
1276 p_sys->f_npt_start = p_sys->ms->playStartTime();
1277 if( p_sys->ms->playEndTime() > 0 )
1278 p_sys->f_npt_length = p_sys->ms->playEndTime();
1280 msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1281 return VLC_SUCCESS;
1284 /*****************************************************************************
1285 * HasSharedSession: returns if the session is shared with another stream
1286 *****************************************************************************/
1287 static bool HasSharedSession( MediaSubsession *session )
1289 if( session->sessionId() == NULL )
1290 return false;
1291 MediaSubsessionIterator *it =
1292 new MediaSubsessionIterator( session->parentSession() );
1293 MediaSubsession *subsession;
1294 bool b_shared = false;
1295 while( (subsession = it->next()) != NULL )
1297 if( session == subsession )
1298 continue;
1299 if( subsession->sessionId() != NULL &&
1300 !strcmp( session->sessionId(), subsession->sessionId() ) )
1302 b_shared = true;
1303 break;
1306 delete it;
1307 return b_shared;
1310 /*****************************************************************************
1311 * ResumeTrack: setup or resume a silenced track
1312 *****************************************************************************/
1313 static void ResumeTrack( demux_t *p_demux, live_track_t *tk )
1315 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1317 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1318 var_GetBool( p_demux, "rtsp-http" );
1319 p_sys->rtsp->sendSetupCommand( *tk->sub, default_live555_callback, False,
1320 toBool( b_rtsp_tcp ),
1321 toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
1322 if( !wait_Live555_response( p_demux ) )
1324 msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
1325 tk->sub->mediumName(), tk->sub->codecName(),
1326 p_sys->env->getResultMsg() );
1328 else
1330 p_sys->rtsp->sendPlayCommand( *tk->sub, default_live555_callback, -1, -1, p_sys->ms->scale() );
1331 if( !wait_Live555_response(p_demux) )
1333 msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1334 if( (p_sys->capabilities & CAP_SUBSESSION_TEARDOWN) ||
1335 !HasSharedSession( tk->sub ) )
1337 tk->state = live_track_t::STATE_TEARDOWN;
1338 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1341 else
1342 tk->state = live_track_t::STATE_SELECTED;
1346 /*****************************************************************************
1347 * Demux:
1348 *****************************************************************************/
1349 static int Demux( demux_t *p_demux )
1351 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1352 TaskToken task;
1354 bool b_send_pcr = true;
1355 int i;
1357 /* Protect Live555 from simultaneous calls in TimeoutPrevention()
1358 during pause */
1359 vlc_mutex_locker locker(&p_sys->timeout_mutex);
1361 for( i = 0; i < p_sys->i_track; i++ )
1363 live_track_t *tk = p_sys->track[i];
1365 if( tk->p_es )
1367 bool b;
1368 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1369 if( !b && (tk->state == live_track_t::STATE_SELECTED) && p_sys->rtsp )
1371 if( (p_sys->capabilities & CAP_SUBSESSION_TEARDOWN) ||
1372 !HasSharedSession( tk->sub ) )
1374 tk->state = live_track_t::STATE_TEARDOWN;
1375 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1377 else tk->state = live_track_t::STATE_IGNORED;
1379 else if( b && tk->state != live_track_t::STATE_SELECTED )
1381 if( tk->state != live_track_t::STATE_IGNORED )
1382 ResumeTrack( p_demux, tk );
1383 else
1384 tk->state = live_track_t::STATE_SELECTED;
1386 if( tk->state != live_track_t::STATE_SELECTED )
1387 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1391 if( tk->format == live_track_t::ASF_STREAM ||
1392 tk->format == live_track_t::MULTIPLEXED_STREAM )
1394 b_send_pcr = false;
1398 /* First warn we want to read data */
1399 p_sys->event_data = 0;
1400 for( i = 0; i < p_sys->i_track; i++ )
1402 live_track_t *tk = p_sys->track[i];
1404 if( tk->waiting == 0 )
1406 tk->waiting = 1;
1407 tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1408 StreamRead, tk, StreamClose, tk );
1411 /* Create a task that will be called if we wait more than 300ms */
1412 task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1414 /* Do the read */
1415 p_sys->scheduler->doEventLoop( &p_sys->event_data );
1417 /* remove the task */
1418 p_sys->scheduler->unscheduleDelayedTask( task );
1420 if( b_send_pcr )
1422 mtime_t i_minpcr = VLC_TS_INVALID;
1423 bool b_need_flush = false;
1425 /* Check for gap in pts value */
1426 for( i = 0; i < p_sys->i_track; i++ )
1428 live_track_t *tk = p_sys->track[i];
1430 if( tk->state != live_track_t::STATE_SELECTED ||
1431 (p_sys->b_rtcp_sync && !tk->b_rtcp_sync) )
1432 continue;
1434 /* Check for gap in pts value */
1435 b_need_flush |= (tk->b_flushing_discontinuity);
1437 if( i_minpcr == VLC_TS_INVALID || ( tk->i_pcr != VLC_TS_INVALID && i_minpcr > tk->i_pcr ) )
1438 i_minpcr = tk->i_pcr;
1441 if( p_sys->i_pcr != VLC_TS_INVALID && b_need_flush )
1443 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1444 p_sys->i_pcr = i_minpcr;
1445 p_sys->f_npt = 0.;
1447 for( i = 0; i < p_sys->i_track; i++ )
1449 live_track_t *tk = p_sys->track[i];
1450 tk->i_lastpts = VLC_TS_INVALID;
1451 tk->i_pcr = VLC_TS_INVALID;
1452 tk->f_npt = 0.;
1453 tk->b_flushing_discontinuity = false;
1454 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1456 if( p_sys->i_pcr != VLC_TS_INVALID )
1457 es_out_SetPCR( p_demux->out, VLC_TS_0 +
1458 __MAX(0, p_sys->i_pcr - PCR_OFF) );
1460 else if( p_sys->i_pcr == VLC_TS_INVALID ||
1461 i_minpcr > p_sys->i_pcr + PCR_OBS )
1463 p_sys->i_pcr = __MAX(0, i_minpcr - PCR_OFF);
1464 if( p_sys->i_pcr != VLC_TS_INVALID )
1465 es_out_SetPCR( p_demux->out, VLC_TS_0 + p_sys->i_pcr );
1469 if( p_sys->b_multicast && p_sys->b_no_data &&
1470 ( p_sys->i_no_data_ti > 120 ) )
1472 /* FIXME Make this configurable
1473 msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1474 return 0;
1477 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1478 p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1480 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1481 var_GetBool( p_demux, "rtsp-http" );
1483 if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1485 msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1486 if( RollOverTcp( p_demux ) )
1488 msg_Err( p_demux, "TCP rollover failed, aborting" );
1489 return 0;
1491 return 1;
1493 msg_Err( p_demux, "no data received in 10s, aborting" );
1494 return 0;
1496 else if( !p_sys->b_multicast && !p_sys->b_paused &&
1497 ( p_sys->i_no_data_ti > 34 ) )
1499 /* EOF ? */
1500 msg_Warn( p_demux, "no data received in 10s, eof ?" );
1501 return 0;
1503 return p_sys->b_error ? 0 : 1;
1506 /*****************************************************************************
1507 * Control:
1508 *****************************************************************************/
1509 static int Control( demux_t *p_demux, int i_query, va_list args )
1511 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1512 int64_t *pi64, i64;
1513 double *pf, f;
1514 bool *pb;
1516 vlc_mutex_locker locker(&p_sys->timeout_mutex); /* (see same in Demux) */
1518 switch( i_query )
1520 case DEMUX_GET_TIME:
1521 pi64 = va_arg( args, int64_t * );
1522 if( p_sys->f_npt > 0 )
1524 *pi64 = (int64_t)(p_sys->f_npt * (double)CLOCK_FREQ);
1525 return VLC_SUCCESS;
1527 return VLC_EGENERIC;
1529 case DEMUX_GET_LENGTH:
1530 pi64 = va_arg( args, int64_t * );
1531 if( p_sys->f_npt_length > 0 )
1533 double d_length = p_sys->f_npt_length * (double)CLOCK_FREQ;
1534 if( d_length >= INT64_MAX )
1535 *pi64 = INT64_MAX;
1536 else
1537 *pi64 = (int64_t)d_length;
1538 return VLC_SUCCESS;
1540 return VLC_EGENERIC;
1542 case DEMUX_GET_POSITION:
1543 pf = va_arg( args, double * );
1544 if( (p_sys->f_npt_length > 0) && (p_sys->f_npt > 0) )
1546 *pf = p_sys->f_npt / p_sys->f_npt_length;
1547 return VLC_SUCCESS;
1549 return VLC_EGENERIC;
1551 case DEMUX_SET_POSITION:
1552 case DEMUX_SET_TIME:
1553 if( p_sys->rtsp && (p_sys->f_npt_length > 0) )
1555 float time;
1557 if( (i_query == DEMUX_SET_TIME) && (p_sys->f_npt > 0) )
1559 i64 = va_arg( args, int64_t );
1560 time = (float)(i64 / 1000000.0); /* in second */
1562 else if( i_query == DEMUX_SET_TIME )
1563 return VLC_EGENERIC;
1564 else
1566 f = va_arg( args, double );
1567 time = f * p_sys->f_npt_length; /* in second */
1570 if( p_sys->b_paused )
1572 p_sys->f_seek_request = time;
1573 return VLC_SUCCESS;
1576 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1578 if( !wait_Live555_response( p_demux ) )
1580 msg_Err( p_demux, "PAUSE before seek failed %s",
1581 p_sys->env->getResultMsg() );
1582 return VLC_EGENERIC;
1585 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1587 if( !wait_Live555_response( p_demux ) )
1589 msg_Err( p_demux, "seek PLAY failed %s",
1590 p_sys->env->getResultMsg() );
1591 return VLC_EGENERIC;
1593 p_sys->i_pcr = VLC_TS_INVALID;
1595 for( int i = 0; i < p_sys->i_track; i++ )
1597 p_sys->track[i]->b_rtcp_sync = false;
1598 p_sys->track[i]->i_lastpts = VLC_TS_INVALID;
1599 p_sys->track[i]->i_pcr = VLC_TS_INVALID;
1602 /* Retrieve the starttime if possible */
1603 p_sys->f_npt = p_sys->f_npt_start = p_sys->ms->playStartTime();
1605 /* Retrieve the duration if possible */
1606 if( p_sys->ms->playEndTime() > 0 )
1607 p_sys->f_npt_length = p_sys->ms->playEndTime();
1609 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1610 return VLC_SUCCESS;
1612 return VLC_EGENERIC;
1614 /* Special for access_demux */
1615 case DEMUX_CAN_PAUSE:
1616 case DEMUX_CAN_SEEK:
1617 pb = va_arg( args, bool * );
1618 if( p_sys->rtsp && p_sys->f_npt_length > 0 )
1619 /* Not always true, but will be handled in SET_PAUSE_STATE */
1620 *pb = true;
1621 else
1622 *pb = false;
1623 return VLC_SUCCESS;
1625 case DEMUX_CAN_CONTROL_PACE:
1626 pb = va_arg( args, bool * );
1628 #if 1 /* Disable for now until we have a clock synchro algo
1629 * which works with something else than MPEG over UDP */
1630 *pb = false;
1631 #else
1632 *pb = true;
1633 #endif
1634 return VLC_SUCCESS;
1636 case DEMUX_CAN_CONTROL_RATE:
1637 pb = va_arg( args, bool * );
1639 *pb = (p_sys->rtsp != NULL) &&
1640 (p_sys->f_npt_length > 0) &&
1641 (p_sys->capabilities & CAP_RATE_CONTROL);
1642 return VLC_SUCCESS;
1644 case DEMUX_SET_RATE:
1646 int *pi_int;
1647 double f_scale, f_old_scale;
1649 if( !p_sys->rtsp || (p_sys->f_npt_length <= 0) ||
1650 !(p_sys->capabilities & CAP_RATE_CONTROL) )
1651 return VLC_EGENERIC;
1653 /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1654 * supports Scale:
1656 * "[...] should try to approximate the viewing rate, but
1657 * may restrict the range of scale values that it supports.
1658 * The response MUST contain the actual scale value chosen
1659 * by the server."
1661 * Scale = 1 indicates normal play
1662 * Scale > 1 indicates fast forward
1663 * Scale < 1 && Scale > 0 indicates slow motion
1664 * Scale < 0 value indicates rewind
1667 pi_int = va_arg( args, int * );
1668 f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1669 f_old_scale = p_sys->ms->scale();
1671 /* Passing -1 for the start and end time will mean liveMedia won't
1672 * create a Range: section for the RTSP message. The server should
1673 * pick up from the current position */
1674 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1676 if( !wait_Live555_response( p_demux ) )
1678 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1679 p_sys->env->getResultMsg() );
1680 return VLC_EGENERIC;
1683 if( p_sys->ms->scale() == f_old_scale )
1685 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1686 p_sys->ms->scale() );
1687 return VLC_EGENERIC;
1690 /* ReSync the stream */
1691 p_sys->f_npt_start = 0;
1692 p_sys->i_pcr = VLC_TS_INVALID;
1693 p_sys->f_npt = 0.0;
1695 *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1696 msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1697 return VLC_SUCCESS;
1700 case DEMUX_SET_PAUSE_STATE:
1702 bool b_pause = (bool)va_arg( args, int );
1703 if( p_sys->rtsp == NULL )
1704 return VLC_EGENERIC;
1706 if( b_pause == p_sys->b_paused )
1707 return VLC_SUCCESS;
1708 if( b_pause )
1709 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1710 else
1711 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1712 -1.0f, p_sys->ms->scale() );
1714 if( !wait_Live555_response( p_demux ) )
1716 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1717 return VLC_EGENERIC;
1719 p_sys->f_seek_request = -1;
1720 p_sys->b_paused = b_pause;
1722 if( !p_sys->b_paused )
1724 for( int i = 0; i < p_sys->i_track; i++ )
1726 live_track_t *tk = p_sys->track[i];
1727 tk->b_rtcp_sync = false;
1728 tk->b_flushing_discontinuity = false;
1729 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1730 tk->i_lastpts = VLC_TS_INVALID;
1731 tk->i_pcr = VLC_TS_INVALID;
1733 p_sys->i_pcr = VLC_TS_INVALID;
1734 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1737 /* Reset data received counter */
1738 p_sys->i_no_data_ti = 0;
1740 /* Retrieve the starttime if possible */
1741 p_sys->f_npt_start = p_sys->ms->playStartTime();
1743 /* Retrieve the duration if possible */
1744 if( p_sys->ms->playEndTime() )
1745 p_sys->f_npt_length = p_sys->ms->playEndTime();
1747 msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1749 return VLC_SUCCESS;
1751 case DEMUX_GET_TITLE_INFO:
1752 case DEMUX_SET_TITLE:
1753 case DEMUX_SET_SEEKPOINT:
1754 return VLC_EGENERIC;
1756 case DEMUX_GET_PTS_DELAY:
1757 pi64 = va_arg( args, int64_t * );
1758 *pi64 = INT64_C(1000)
1759 * var_InheritInteger( p_demux, "network-caching" );
1760 return VLC_SUCCESS;
1762 default:
1763 return VLC_EGENERIC;
1767 /*****************************************************************************
1768 * RollOverTcp: reopen the rtsp into TCP mode
1769 * XXX: ugly, a lot of code are duplicated from Open()
1770 * This should REALLY be fixed
1771 *****************************************************************************/
1772 static int RollOverTcp( demux_t *p_demux )
1774 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1775 int i, i_return;
1777 var_SetBool( p_demux, "rtsp-tcp", true );
1779 /* We close the old RTSP session */
1780 vlc_timer_schedule(p_sys->timer, false, 0, 0);
1781 p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1782 Medium::close( p_sys->ms );
1783 RTSPClient::close( p_sys->rtsp );
1785 for( i = 0; i < p_sys->i_track; i++ )
1787 live_track_t *tk = p_sys->track[i];
1789 if( tk->p_out_muxed ) vlc_demux_chained_Delete( tk->p_out_muxed );
1790 if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1791 if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1792 es_format_Clean( &tk->fmt );
1793 free( tk->p_buffer );
1794 free( tk );
1796 TAB_CLEAN( p_sys->i_track, p_sys->track );
1797 if( p_sys->p_out_asf ) vlc_demux_chained_Delete( p_sys->p_out_asf );
1799 p_sys->ms = NULL;
1800 p_sys->rtsp = NULL;
1801 p_sys->b_no_data = true;
1802 p_sys->i_no_data_ti = 0;
1803 p_sys->p_out_asf = NULL;
1805 /* Reopen rtsp client */
1806 if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1808 msg_Err( p_demux, "Failed to connect with %s", p_sys->psz_pl_url );
1809 goto error;
1812 if( p_sys->p_sdp == NULL )
1814 msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1815 goto error;
1818 if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1820 msg_Err( p_demux, "Nothing to play for %s", p_sys->psz_pl_url );
1821 goto error;
1824 if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1825 goto error;
1827 return VLC_SUCCESS;
1829 error:
1830 return VLC_EGENERIC;
1834 /*****************************************************************************
1836 *****************************************************************************/
1837 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1838 bool b_marker,
1839 const uint8_t *p_data, unsigned i_size )
1841 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1842 const unsigned i_packet_size = p_sys->asfh.i_min_data_packet_size;
1843 block_t *p_list = NULL;
1845 while( i_size >= 4 )
1847 unsigned i_flags = p_data[0];
1848 unsigned i_length_offset = (p_data[1] << 16) |
1849 (p_data[2] << 8) |
1850 (p_data[3] );
1851 bool b_length = i_flags & 0x40;
1852 bool b_relative_ts = i_flags & 0x20;
1853 bool b_duration = i_flags & 0x10;
1854 bool b_location_id = i_flags & 0x08;
1856 //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1857 // b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1858 unsigned i_header_size = 4;
1859 if( b_relative_ts )
1860 i_header_size += 4;
1861 if( b_duration )
1862 i_header_size += 4;
1863 if( b_location_id )
1864 i_header_size += 4;
1866 if( i_header_size > i_size )
1868 msg_Warn( p_demux, "Invalid header size" );
1869 break;
1872 /* XXX
1873 * When b_length is true, the streams I found do not seems to respect
1874 * the documentation.
1875 * From them, I have failed to find which choice between '__MIN()' or
1876 * 'i_length_offset - i_header_size' is the right one.
1878 unsigned i_payload;
1879 if( b_length )
1880 i_payload = __MIN( i_length_offset, i_size - i_header_size);
1881 else
1882 i_payload = i_size - i_header_size;
1884 if( !tk->p_asf_block )
1886 tk->p_asf_block = block_Alloc( i_packet_size );
1887 if( !tk->p_asf_block )
1888 break;
1889 tk->p_asf_block->i_buffer = 0;
1891 unsigned i_offset = b_length ? 0 : i_length_offset;
1892 if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1894 memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1895 tk->p_asf_block->i_buffer += i_payload;
1896 if( b_marker )
1898 /* We have a complete packet */
1899 tk->p_asf_block->i_buffer = i_packet_size;
1900 block_ChainAppend( &p_list, tk->p_asf_block );
1901 tk->p_asf_block = NULL;
1904 else
1906 /* Reset on broken stream */
1907 msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1908 i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1909 tk->p_asf_block->i_buffer = 0;
1912 /* */
1913 p_data += i_header_size + i_payload;
1914 i_size -= i_header_size + i_payload;
1916 return p_list;
1919 /*****************************************************************************
1921 *****************************************************************************/
1922 static void StreamRead( void *p_private, unsigned int i_size,
1923 unsigned int i_truncated_bytes, struct timeval pts,
1924 unsigned int duration )
1926 VLC_UNUSED( duration );
1928 live_track_t *tk = (live_track_t*)p_private;
1929 demux_t *p_demux = tk->p_demux;
1930 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1931 block_t *p_block;
1933 //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1935 int64_t i_pts = (int64_t)pts.tv_sec * CLOCK_FREQ +
1936 (int64_t)pts.tv_usec;
1938 /* XXX Beurk beurk beurk Avoid having negative value XXX */
1939 i_pts &= INT64_C(0x00ffffffffffffff);
1941 /* Retrieve NPT for this pts */
1942 tk->f_npt = tk->sub->getNormalPlayTime(pts);
1944 if( tk->format == live_track_t::QUICKTIME_STREAM && tk->p_es == NULL )
1946 QuickTimeGenericRTPSource *qtRTPSource =
1947 (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1948 QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1949 uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1951 /* Get codec information from the quicktime atoms :
1952 * http://developer.apple.com/quicktime/icefloe/dispatch026.html */
1953 if( tk->fmt.i_cat == VIDEO_ES ) {
1954 if( qtState.sdAtomSize < 16 + 32 )
1956 /* invalid */
1957 p_sys->event_data = 0xff;
1958 tk->waiting = 0;
1959 return;
1961 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1962 tk->fmt.video.i_width = (sdAtom[28] << 8) | sdAtom[29];
1963 tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1965 if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1967 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1968 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1969 + qtRTPSource->qtState.sdAtomSize;
1970 while (pos+8 < endpos) {
1971 unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1972 if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1973 if( memcmp(pos+4, "avcC", 4) == 0 &&
1974 atomLength > 8 &&
1975 atomLength <= INT_MAX )
1977 tk->fmt.i_extra = atomLength-8;
1978 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1979 memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1980 break;
1982 pos += atomLength;
1985 else
1987 tk->fmt.i_extra = qtState.sdAtomSize - 16;
1988 tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1989 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1992 else {
1993 if( qtState.sdAtomSize < 24 )
1995 /* invalid */
1996 p_sys->event_data = 0xff;
1997 tk->waiting = 0;
1998 return;
2000 tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
2001 tk->fmt.audio.i_bitspersample = (sdAtom[22] << 8) | sdAtom[23];
2003 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
2006 #if 0
2007 fprintf( stderr, "StreamRead size=%d pts=%lld\n",
2008 i_size,
2009 pts.tv_sec * 1000000LL + pts.tv_usec );
2010 #endif
2012 /* grow buffer if it looks like buffer is too small, but don't eat
2013 * up all the memory on strange streams */
2014 if( i_truncated_bytes > 0 )
2016 if( tk->i_buffer < 2000000 )
2018 void *p_tmp;
2019 msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
2020 msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
2021 p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
2022 if( p_tmp == NULL )
2024 msg_Warn( p_demux, "realloc failed" );
2026 else
2028 tk->p_buffer = (uint8_t*)p_tmp;
2029 tk->i_buffer *= 2;
2033 if( tk->b_discard_trunc )
2035 p_sys->event_data = 0xff;
2036 tk->waiting = 0;
2037 return;
2041 assert( i_size <= tk->i_buffer );
2043 if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
2044 tk->fmt.i_codec == VLC_CODEC_AMR_WB )
2046 AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
2048 if( (p_block = block_Alloc( i_size + 1 )) )
2050 p_block->p_buffer[0] = amrSource->lastFrameHeader();
2051 memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
2054 else if( tk->fmt.i_codec == VLC_CODEC_H261 )
2056 H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
2057 uint32_t header = h261Source->lastSpecialHeader();
2058 if( (p_block = block_Alloc( i_size + 4 )) )
2060 memcpy( p_block->p_buffer, &header, 4 );
2061 memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
2064 else if( tk->fmt.i_codec == VLC_CODEC_H264 || tk->fmt.i_codec == VLC_CODEC_HEVC )
2066 if( tk->fmt.i_codec == VLC_CODEC_H264 && (tk->p_buffer[0] & 0x1f) >= 24 )
2067 msg_Warn( p_demux, "unsupported NAL type for H264" );
2068 else if( tk->fmt.i_codec == VLC_CODEC_HEVC && ((tk->p_buffer[0] & 0x7e)>>1) >= 48 )
2069 msg_Warn( p_demux, "unsupported NAL type for H265" );
2071 /* Normal NAL type */
2072 if( (p_block = block_Alloc( i_size + 4 )) )
2074 p_block->p_buffer[0] = 0x00;
2075 p_block->p_buffer[1] = 0x00;
2076 p_block->p_buffer[2] = 0x00;
2077 p_block->p_buffer[3] = 0x01;
2078 memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
2081 else if( tk->format == live_track_t::ASF_STREAM )
2083 p_block = StreamParseAsf( p_demux, tk,
2084 tk->sub->rtpSource()->curPacketMarkerBit(),
2085 tk->p_buffer, i_size );
2087 else
2089 if( (p_block = block_Alloc( i_size )) )
2090 memcpy( p_block->p_buffer, tk->p_buffer, i_size );
2093 /* No data sent. Always in sync then */
2094 if( !tk->b_rtcp_sync && tk->sub->rtpSource() &&
2095 tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
2097 msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
2098 p_sys->b_rtcp_sync = tk->b_rtcp_sync = true;
2099 if( tk->i_pcr != VLC_TS_INVALID )
2101 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
2102 const int64_t i_max_diff = CLOCK_FREQ * (( tk->fmt.i_cat == SPU_ES ) ? 60 : 1);
2103 tk->b_flushing_discontinuity = (llabs(i_pts - tk->i_pcr) > i_max_diff);
2104 tk->i_pcr = i_pts;
2108 /* Update our global npt value */
2109 if( tk->f_npt > 0 &&
2110 ( tk->f_npt < p_sys->f_npt_length || p_sys->f_npt_length <= 0 ) )
2111 p_sys->f_npt = tk->f_npt;
2113 if( p_block )
2115 switch( tk->format )
2117 case live_track_t::ASF_STREAM:
2118 vlc_demux_chained_Send( p_sys->p_out_asf, p_block );
2119 break;
2120 case live_track_t::MULTIPLEXED_STREAM:
2121 vlc_demux_chained_Send( tk->p_out_muxed, p_block );
2122 break;
2123 default:
2124 if( i_pts != tk->i_lastpts )
2125 p_block->i_pts = VLC_TS_0 + i_pts;
2126 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
2127 switch( tk->fmt.i_codec )
2129 case VLC_CODEC_MPGV:
2130 case VLC_CODEC_H264:
2131 case VLC_CODEC_HEVC:
2132 case VLC_CODEC_VP8:
2133 p_block->i_dts = VLC_TS_INVALID;
2134 break;
2135 default:
2136 p_block->i_dts = VLC_TS_0 + i_pts;
2137 break;
2140 if( i_truncated_bytes )
2141 p_block->i_flags |= BLOCK_FLAG_CORRUPTED;
2143 if( unlikely(tk->i_next_block_flags) )
2145 p_block->i_flags |= tk->i_next_block_flags;
2146 tk->i_next_block_flags = 0;
2148 es_out_Send( p_demux->out, tk->p_es, p_block );
2149 if( i_pts > 0 )
2151 if( tk->i_pcr < i_pts )
2152 tk->i_pcr = i_pts;
2153 tk->i_lastpts = i_pts;
2155 break;
2159 /* warn that's ok */
2160 p_sys->event_data = 0xff;
2162 /* we have read data */
2163 tk->waiting = 0;
2164 p_sys->b_no_data = false;
2165 p_sys->i_no_data_ti = 0;
2168 /*****************************************************************************
2170 *****************************************************************************/
2171 static void StreamClose( void *p_private )
2173 live_track_t *tk = (live_track_t*)p_private;
2174 demux_t *p_demux = tk->p_demux;
2175 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2176 tk->state = live_track_t::STATE_IGNORED;
2177 p_sys->event_rtsp = 0xff;
2178 p_sys->event_data = 0xff;
2180 if( tk->p_es )
2181 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
2183 int nb_tracks = 0;
2184 for( int i = 0; i < p_sys->i_track; i++ )
2186 if( p_sys->track[i]->state == live_track_t::STATE_SELECTED )
2187 nb_tracks++;
2189 msg_Dbg( p_demux, "RTSP track Close, %d track remaining", nb_tracks );
2190 if( !nb_tracks )
2191 p_sys->b_error = true;
2195 /*****************************************************************************
2197 *****************************************************************************/
2198 static void TaskInterruptRTSP( void *p_private )
2200 demux_t *p_demux = (demux_t*)p_private;
2201 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2203 /* Avoid lock */
2204 p_sys->event_rtsp = 0xff;
2207 static void TaskInterruptData( void *p_private )
2209 demux_t *p_demux = (demux_t*)p_private;
2210 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2212 p_sys->i_no_data_ti++;
2214 /* Avoid lock */
2215 p_sys->event_data = 0xff;
2218 /*****************************************************************************
2220 *****************************************************************************/
2221 static void TimeoutPrevention( void *p_data )
2223 demux_t *p_demux = (demux_t *) p_data;
2224 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2225 char *bye = NULL;
2227 /* Protect Live555 from us calling their functions simultaneously
2228 with Demux() or Control() */
2229 vlc_mutex_locker locker(&p_sys->timeout_mutex);
2231 /* If the timer fires while the demuxer owns the lock, and the demuxer
2232 * then torns the session down, the pointers will become NULL. By the time
2233 * this timer callback obtains the callback, either a new session was
2234 * created and the timer is rescheduled, or the pointers are still NULL
2235 * and the timer is descheduled. In the second case, bail out (then wait
2236 * for the timer to be rescheduled or destroyed). In the first case, this
2237 * might send an early refresh - that´s harmless but suboptimal (FIXME). */
2238 if( p_sys->rtsp == NULL || p_sys->ms == NULL )
2239 return;
2241 bool use_get_param = p_sys->b_get_param;
2243 /* Use GET_PARAMETERS if supported. wmserver dialect supports
2244 * it, but does not report this properly. */
2245 if( var_GetBool( p_demux, "rtsp-wmserver" ) )
2246 use_get_param = true;
2248 if( use_get_param )
2249 p_sys->rtsp->sendGetParameterCommand( *p_sys->ms,
2250 default_live555_callback, bye );
2251 else
2252 p_sys->rtsp->sendOptionsCommand( default_live555_callback, NULL );
2254 if( !wait_Live555_response( p_demux ) )
2256 msg_Err( p_demux, "keep-alive failed: %s",
2257 p_sys->env->getResultMsg() );
2258 /* Just continue, worst case is we get timed out later */
2262 /*****************************************************************************
2264 *****************************************************************************/
2265 static int ParseASF( demux_t *p_demux )
2267 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2269 const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
2270 char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2271 char *psz_end;
2272 block_t *p_header;
2274 /* Parse the asf header */
2275 if( psz_asf == NULL )
2276 return VLC_EGENERIC;
2278 psz_asf += strlen( psz_marker );
2279 psz_asf = strdup( psz_asf ); /* Duplicate it */
2280 psz_end = strchr( psz_asf, '\n' );
2282 while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2283 *psz_end-- = '\0';
2285 if( psz_asf >= psz_end )
2287 free( psz_asf );
2288 return VLC_EGENERIC;
2291 /* Always smaller */
2292 p_header = block_Alloc( psz_end - psz_asf );
2293 p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2294 p_header->i_buffer, psz_asf );
2295 //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2296 if( p_header->i_buffer <= 0 )
2298 free( psz_asf );
2299 return VLC_EGENERIC;
2302 /* Parse it to get packet size */
2303 asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2305 /* Send it to demuxer */
2306 vlc_demux_chained_Send( p_sys->p_out_asf, p_header );
2308 free( psz_asf );
2309 return VLC_SUCCESS;
2313 static unsigned char* parseH264ConfigStr( char const* configStr,
2314 unsigned int& configSize )
2316 char *dup, *psz;
2317 size_t i_records = 1;
2319 configSize = 0;
2321 if( configStr == NULL || *configStr == '\0' )
2322 return NULL;
2324 psz = dup = strdup( configStr );
2326 /* Count the number of commas */
2327 for( psz = dup; *psz != '\0'; ++psz )
2329 if( *psz == ',')
2331 ++i_records;
2332 *psz = '\0';
2336 size_t configMax = 5*strlen(dup);
2337 unsigned char *cfg = new unsigned char[configMax];
2338 psz = dup;
2339 for( size_t i = 0; i < i_records; ++i )
2341 cfg[configSize++] = 0x00;
2342 cfg[configSize++] = 0x00;
2343 cfg[configSize++] = 0x00;
2344 cfg[configSize++] = 0x01;
2346 configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2347 configMax-configSize, psz );
2348 psz += strlen(psz)+1;
2351 free( dup );
2352 return cfg;
2355 static uint8_t *parseVorbisConfigStr( char const* configStr,
2356 unsigned int& configSize )
2358 configSize = 0;
2359 if( configStr == NULL || *configStr == '\0' )
2360 return NULL;
2361 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1332115200 // 2012.03.20
2362 unsigned char *p_cfg = base64Decode( configStr, configSize );
2363 #else
2364 char* configStr_dup = strdup( configStr );
2365 unsigned char *p_cfg = base64Decode( configStr_dup, configSize );
2366 free( configStr_dup );
2367 #endif
2368 uint8_t *p_extra = NULL;
2369 /* skip header count, ident number and length (cf. RFC 5215) */
2370 const unsigned int headerSkip = 9;
2371 if( configSize > headerSkip && ((uint8_t*)p_cfg)[3] == 1 )
2373 configSize -= headerSkip;
2374 p_extra = (uint8_t*)xmalloc( configSize );
2375 memcpy( p_extra, p_cfg+headerSkip, configSize );
2377 delete[] p_cfg;
2378 return p_extra;
2381 static char *passwordLessURL( vlc_url_t *p_url )
2383 vlc_url_t url;
2385 memcpy( &url, p_url, sizeof( vlc_url_t ) );
2387 url.psz_username = NULL;
2388 url.psz_password = NULL;
2389 if( url.i_port == 0 )
2390 url.i_port = 554;
2391 return vlc_uri_compose( &url );