cdc3741f35f08580ada9ed5fd182d500e82848fc
[vlc.git] / modules / access / live555.cpp
1 /*****************************************************************************
2  * live555.cpp : LIVE555 Streaming Media support.
3  *****************************************************************************
4  * Copyright (C) 2003-2007 VLC authors and VideoLAN
5  * $Id$
6  *
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>
11  *
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.
16  *
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.
21  *
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  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <inttypes.h>
36
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>
46
47 #include <limits.h>
48 #include <assert.h>
49
50 #include <new>
51
52 #if defined( _WIN32 )
53 #   include <winsock2.h>
54 #endif
55
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>
62
63 extern "C" {
64 #include "../access/mms/asf.h"  /* Who said ugly ? */
65 }
66
67 /*****************************************************************************
68  * Module descriptor
69  *****************************************************************************/
70 static int  Open ( vlc_object_t * );
71 static void Close( vlc_object_t * );
72
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." )
77
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.")
82
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
94
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 )
103
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,
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 ()
143
144
145 /*****************************************************************************
146  * Local prototypes
147  *****************************************************************************/
148
149 typedef struct
150 {
151     demux_t         *p_demux;
152     MediaSubsession *sub;
153
154     es_format_t     fmt;
155     es_out_id_t     *p_es;
156
157     enum
158     {
159         SINGLE_STREAM,
160         MULTIPLEXED_STREAM,
161         QUICKTIME_STREAM,
162         ASF_STREAM
163     } format;
164
165     block_t         *p_asf_block;
166     bool            b_discard_trunc;
167     vlc_demux_chained_t *p_out_muxed;    /* for muxed stream */
168
169     uint8_t         *p_buffer;
170     unsigned int    i_buffer;
171
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;
179
180     enum
181     {
182         STATE_NONE,
183         STATE_SELECTED,
184         STATE_IGNORED,
185         STATE_TEARDOWN,
186     } state;
187
188 } live_track_t;
189
190 class RTSPClientVlc;
191
192 #define CAP_RATE_CONTROL        (1 << 1)
193 #define CAP_SUBSESSION_TEARDOWN (1 << 2)
194 #define CAP_SUBSESSION_PAUSE    (1 << 3)
195 #define CAPS_DEFAULT            CAP_RATE_CONTROL
196
197 struct demux_sys_t
198 {
199     char            *p_sdp;    /* XXX mallocated */
200     char            *psz_pl_url; /* password-less URL */
201     vlc_url_t       url;
202
203     MediaSession     *ms;
204     TaskScheduler    *scheduler;
205     UsageEnvironment *env ;
206     RTSPClientVlc    *rtsp;
207     int              capabilities; /* Server capabilities workaround */
208
209     /* */
210     int              i_track;
211     live_track_t     **track;
212
213     /* Weird formats */
214     asf_header_t     asfh;
215     vlc_demux_chained_t *p_out_asf;
216     bool             b_real;
217
218     /* */
219     int64_t          i_pcr; /* The clock */
220     bool             b_rtcp_sync; /* At least one track received sync */
221     double           f_npt;
222     double           f_npt_length;
223     double           f_npt_start;
224
225     /* timeout thread information */
226     vlc_timer_t      timer;
227     vlc_mutex_t      timeout_mutex; /* Serialise calls to live555 in timeout thread w.r.t. Demux()/Control() */
228
229     /* */
230     bool             b_force_mcast;
231     bool             b_multicast;   /* if one of the tracks is multicasted */
232     bool             b_no_data;     /* if we never received any data */
233     int              i_no_data_ti;  /* consecutive number of TaskInterrupt */
234
235     char             event_rtsp;
236     char             event_data;
237
238     bool             b_get_param;   /* Does the server support GET_PARAMETER */
239     bool             b_paused;      /* Are we paused? */
240     bool             b_error;
241     int              i_live555_ret; /* live555 callback return code */
242
243     float            f_seek_request;/* In case we receive a seek request while paused*/
244 };
245
246
247 class RTSPClientVlc : public RTSPClient
248 {
249 public:
250     RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
251                    char const* applicationName, portNumBits tunnelOverHTTPPortNum,
252                    demux_sys_t *p_sys) :
253                    RTSPClient( env, rtspURL, verbosityLevel, applicationName,
254                    tunnelOverHTTPPortNum
255 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1373932800
256                    , -1
257 #endif
258                    )
259     {
260         this->p_sys = p_sys;
261     }
262     demux_sys_t *p_sys;
263 };
264
265 static int Demux  ( demux_t * );
266 static int Control( demux_t *, int, va_list );
267
268 static int Connect      ( demux_t * );
269 static int SessionsSetup( demux_t * );
270 static int Play         ( demux_t *);
271 static int ParseASF     ( demux_t * );
272 static int RollOverTcp  ( demux_t * );
273
274 static void StreamRead  ( void *, unsigned int, unsigned int,
275                           struct timeval, unsigned int );
276 static void StreamClose ( void * );
277 static void TaskInterruptData( void * );
278 static void TaskInterruptRTSP( void * );
279
280 static void TimeoutPrevention( void * );
281
282 static unsigned char* parseH264ConfigStr( char const* configStr,
283                                           unsigned int& configSize );
284 static unsigned char* parseVorbisConfigStr( char const* configStr,
285                                             unsigned int& configSize );
286
287 static char *passwordLessURL( vlc_url_t *url );
288
289 #define PCR_OBS (CLOCK_FREQ / 4)
290 #define PCR_OFF PCR_OBS
291
292 /*****************************************************************************
293  * DemuxOpen:
294  *****************************************************************************/
295 static int  Open ( vlc_object_t *p_this )
296 {
297     demux_t     *p_demux = (demux_t*)p_this;
298     demux_sys_t *p_sys = NULL;
299
300     int i_return;
301     int i_error = VLC_EGENERIC;
302
303     if (p_demux->out == NULL)
304         return VLC_EGENERIC;
305
306     /* if the rtsp URL may contain a sat.ip fake DNS, bail-out early and 
307      * let the SAT>IP module handle that */
308     if( !strncmp(p_demux->psz_location, "sat.ip", 6) )
309     {
310         msg_Err( p_demux, "SAT>IP server, bailing out");
311         return VLC_EGENERIC;
312     }
313     /* If satip-host is set on the item, we shall assume it is a rtsp for the
314      * SAT>IP module and bail-out early. */
315     char *psz_host = var_InheritString(p_demux, "satip-host");
316     if (psz_host != NULL) {
317         msg_Err( p_demux, "URL is for SAT>IP, bailing out");
318         free(psz_host);
319         return VLC_EGENERIC;
320     }
321
322     if( p_demux->s )
323     {
324         /* See if it looks like a SDP
325            v, o, s fields are mandatory and in this order */
326         const uint8_t *p_peek;
327         if( vlc_stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
328
329         if( memcmp( p_peek, "v=0\r\n", 5 ) &&
330             memcmp( p_peek, "v=0\n", 4 ) &&
331             ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
332         {
333             return VLC_EGENERIC;
334         }
335     }
336
337     p_demux->pf_demux  = Demux;
338     p_demux->pf_control= Control;
339     p_demux->p_sys     = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
340     if( !p_sys ) return VLC_ENOMEM;
341
342     if( vlc_timer_create(&p_sys->timer, TimeoutPrevention, p_demux) )
343     {
344         free( p_sys );
345         return VLC_ENOMEM;
346     }
347
348     msg_Dbg( p_demux, "version " LIVEMEDIA_LIBRARY_VERSION_STRING );
349
350     p_sys->capabilities = CAPS_DEFAULT;
351     if( var_GetBool( p_demux, "rtsp-kasenna" ) ||
352         var_GetBool( p_demux, "rtsp-wmserver" ) )
353     {
354         p_sys->capabilities &= ~CAP_RATE_CONTROL;
355     }
356
357     TAB_INIT( p_sys->i_track, p_sys->track );
358     p_sys->b_no_data = true;
359     p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
360     p_sys->f_seek_request = -1;
361     vlc_mutex_init(&p_sys->timeout_mutex);
362
363     /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
364     vlc_UrlParse( &p_sys->url, p_demux->psz_url );
365
366     if( ( p_sys->psz_pl_url = passwordLessURL( &p_sys->url ) ) == NULL )
367     {
368         i_error = VLC_ENOMEM;
369         goto error;
370     }
371
372     if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
373     {
374         msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
375         goto error;
376     }
377     if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
378     {
379         msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
380         goto error;
381     }
382
383     if( p_demux->s != NULL )
384     {
385         char *p = p_sys->psz_pl_url;
386         while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
387     }
388
389     if( p_demux->s != NULL )
390     {
391         /* Gather the complete sdp file */
392         int     i_sdp       = 0;
393         int     i_sdp_max   = 1000;
394         uint8_t *p_sdp      = (uint8_t*) malloc( i_sdp_max );
395
396         if( !p_sdp )
397         {
398             i_error = VLC_ENOMEM;
399             goto error;
400         }
401
402         for( ;; )
403         {
404             int i_read = vlc_stream_Read( p_demux->s, &p_sdp[i_sdp],
405                                       i_sdp_max - i_sdp - 1 );
406             if( i_read < 0 )
407             {
408                 msg_Err( p_demux, "failed to read SDP" );
409                 free( p_sdp );
410                 goto error;
411             }
412
413             i_sdp += i_read;
414
415             if( i_read < i_sdp_max - i_sdp - 1 )
416             {
417                 p_sdp[i_sdp] = '\0';
418                 break;
419             }
420
421             i_sdp_max += 1000;
422             p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
423         }
424         p_sys->p_sdp = (char*)p_sdp;
425     }
426     else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
427     {
428         msg_Err( p_demux, "Failed to connect with %s", p_sys->psz_pl_url );
429         goto error;
430     }
431
432     if( p_sys->p_sdp == NULL )
433     {
434         msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
435         i_error = VLC_ENOMEM;
436         goto error;
437     }
438
439     if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
440     {
441         msg_Err( p_demux, "Nothing to play for %s", p_sys->psz_pl_url );
442         goto error;
443     }
444
445     if( p_sys->b_real ) goto error;
446
447     if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
448         goto error;
449
450     if( p_sys->p_out_asf && ParseASF( p_demux ) )
451     {
452         msg_Err( p_demux, "cannot find a usable asf header" );
453         /* TODO Clean tracks */
454         goto error;
455     }
456
457     if( p_sys->i_track <= 0 )
458         goto error;
459
460     return VLC_SUCCESS;
461
462 error:
463     Close( p_this );
464     return i_error;
465 }
466
467 /*****************************************************************************
468  * DemuxClose:
469  *****************************************************************************/
470 static void Close( vlc_object_t *p_this )
471 {
472     demux_t *p_demux = (demux_t*)p_this;
473     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
474
475     vlc_timer_destroy(p_sys->timer);
476
477     if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
478     if( p_sys->ms ) Medium::close( p_sys->ms );
479     if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
480     if( p_sys->env ) p_sys->env->reclaim();
481
482     for( int i = 0; i < p_sys->i_track; i++ )
483     {
484         live_track_t *tk = p_sys->track[i];
485
486         if( tk->p_out_muxed )
487             vlc_demux_chained_Delete( tk->p_out_muxed );
488         es_format_Clean( &tk->fmt );
489         free( tk->p_buffer );
490         free( tk );
491     }
492     TAB_CLEAN( p_sys->i_track, p_sys->track );
493     if( p_sys->p_out_asf )
494         vlc_demux_chained_Delete( p_sys->p_out_asf );
495     delete p_sys->scheduler;
496     free( p_sys->p_sdp );
497     free( p_sys->psz_pl_url );
498
499     vlc_UrlClean( &p_sys->url );
500     vlc_mutex_destroy(&p_sys->timeout_mutex);
501
502     free( p_sys );
503 }
504
505 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
506
507 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
508 {
509     RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
510     demux_sys_t *p_sys = client_vlc->p_sys;
511     delete []result_string;
512     p_sys->i_live555_ret = result_code;
513     p_sys->b_error = p_sys->i_live555_ret != 0;
514     p_sys->event_rtsp = 1;
515 }
516
517 /* return true if the RTSP command succeeded */
518 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
519 {
520     TaskToken task;
521     demux_sys_t * p_sys = (demux_sys_t *)p_demux->p_sys;
522     p_sys->event_rtsp = 0;
523     if( i_timeout > 0 )
524     {
525         /* Create a task that will be called if we wait more than timeout ms */
526         task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000,
527                                                       TaskInterruptRTSP,
528                                                       p_demux );
529     }
530     p_sys->event_rtsp = 0;
531     p_sys->b_error = true;
532     p_sys->i_live555_ret = 0;
533     p_sys->scheduler->doEventLoop( &p_sys->event_rtsp );
534     //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
535     if( i_timeout > 0 )
536     {
537         /* remove the task */
538         p_sys->scheduler->unscheduleDelayedTask( task );
539     }
540     return !p_sys->b_error;
541 }
542
543 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
544                                    char* result_string )
545 {
546     RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
547     demux_sys_t *p_sys = client_vlc->p_sys;
548     p_sys->i_live555_ret = result_code;
549     if ( result_code == 0 )
550     {
551         char* sdpDescription = result_string;
552         free( p_sys->p_sdp );
553         p_sys->p_sdp = NULL;
554         if( sdpDescription )
555         {
556             p_sys->p_sdp = strdup( sdpDescription );
557             p_sys->b_error = false;
558         }
559     }
560     else
561         p_sys->b_error = true;
562     delete[] result_string;
563     p_sys->event_rtsp = 1;
564 #ifdef VLC_PATCH_RTSPCLIENT_SERVERSTRING
565     if( client_vlc->serverString() )
566     {
567         if( !strncmp(client_vlc->serverString(), "Kasenna", 7) ||
568             !strncmp(client_vlc->serverString(), "WMServer", 8) )
569             p_sys->capabilities &= ~CAP_RATE_CONTROL;
570         if( !strncmp(client_vlc->serverString(), "VLC/", 4) )
571             p_sys->capabilities |= (CAP_SUBSESSION_TEARDOWN|CAP_SUBSESSION_PAUSE);
572     }
573 #endif
574 }
575
576 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
577                                   char* result_string )
578 {
579     RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
580     demux_sys_t *p_sys = client_vlc->p_sys;
581     p_sys->b_get_param =
582       // If OPTIONS fails, assume GET_PARAMETER is not supported but
583       // still continue on with the stream.  Some servers (foscam)
584       // return 501/not implemented for OPTIONS.
585       result_code == 0
586       && result_string != NULL
587       && strstr( result_string, "GET_PARAMETER" ) != NULL;
588     client->sendDescribeCommand( continueAfterDESCRIBE );
589     delete[] result_string;
590 }
591
592 /*****************************************************************************
593  * Connect: connects to the RTSP server to setup the session DESCRIBE
594  *****************************************************************************/
595 static int Connect( demux_t *p_demux )
596 {
597     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
598     Authenticator authenticator;
599     vlc_credential credential;
600     const char *psz_user = NULL;
601     const char *psz_pwd  = NULL;
602     int  i_http_port  = 0;
603     int  i_ret        = VLC_SUCCESS;
604     const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
605
606     vlc_credential_init( &credential, &p_sys->url );
607
608     /* Credentials can be NULL since they may not be needed */
609     if( vlc_credential_get( &credential, p_demux, "rtsp-user", "rtsp-pwd",
610                             NULL, NULL) )
611     {
612         psz_user = credential.psz_username;
613         psz_pwd = credential.psz_password;
614     }
615
616 createnew:
617     /* FIXME: This is naive and incorrect; it does not prevent the thread
618      * getting stuck in blocking socket operations. */
619     if( vlc_killed() )
620     {
621         i_ret = VLC_EGENERIC;
622         goto bailout;
623     }
624
625     if( var_CreateGetBool( p_demux, "rtsp-http" ) )
626         i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
627
628     p_sys->rtsp = new (std::nothrow) RTSPClientVlc( *p_sys->env, p_sys->psz_pl_url,
629                                      var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
630                                      "LibVLC/" VERSION, i_http_port, p_sys );
631     if( !p_sys->rtsp )
632     {
633         msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
634                  p_sys->env->getResultMsg() );
635         i_ret = VLC_EGENERIC;
636         goto bailout;
637     }
638
639     /* Kasenna enables KeepAlive by analysing the User-Agent string.
640      * Appending _KA to the string should be enough to enable this feature,
641      * however, there is a bug where the _KA doesn't get parsed from the
642      * default User-Agent as created by VLC/Live555 code. This is probably due
643      * to spaces in the string or the string being too long. Here we override
644      * the default string with a more compact version.
645      */
646     if( var_InheritBool( p_demux, "rtsp-kasenna" ))
647     {
648         p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
649     }
650
651 describe:
652     authenticator.setUsernameAndPassword( psz_user, psz_pwd );
653
654     p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
655
656     if( !wait_Live555_response( p_demux, i_timeout ) )
657     {
658         int i_code = p_sys->i_live555_ret;
659         if( i_code == 401 )
660         {
661             msg_Dbg( p_demux, "authentication failed" );
662
663             if( vlc_credential_get( &credential, p_demux, "rtsp-user", "rtsp-pwd",
664                                     _("RTSP authentication"),
665                                     _("Please enter a valid login name and a password.") ) )
666             {
667                 psz_user = credential.psz_username;
668                 psz_pwd = credential.psz_password;
669                 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
670                 goto describe;
671             }
672         }
673         else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
674         {
675             /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
676             msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
677             var_SetBool( p_demux, "rtsp-http", true );
678             if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
679             p_sys->rtsp = NULL;
680             goto createnew;
681         }
682         else
683         {
684             if( i_code == 0 )
685                 msg_Dbg( p_demux, "connection timeout" );
686             else
687             {
688                 msg_Dbg( p_demux, "connection error %d", i_code );
689                 if( i_code == 403 )
690                     vlc_dialog_display_error( p_demux, _("RTSP connection failed"),
691                         _("Access to the stream is denied by the server configuration.") );
692             }
693             if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
694             p_sys->rtsp = NULL;
695         }
696         i_ret = VLC_EGENERIC;
697     }
698     else
699         vlc_credential_store( &credential, p_demux );
700
701 bailout:
702     vlc_credential_clean( &credential );
703
704     return i_ret;
705 }
706
707 /*****************************************************************************
708  * SessionsSetup: prepares the subsessions and does the SETUP
709  *****************************************************************************/
710 static int SessionsSetup( demux_t *p_demux )
711 {
712     demux_sys_t *p_sys  = (demux_sys_t *)p_demux->p_sys;
713     MediaSubsessionIterator *iter   = NULL;
714     MediaSubsession         *sub    = NULL;
715
716     bool           b_rtsp_tcp;
717     int            i_client_port;
718     int            i_return = VLC_SUCCESS;
719     unsigned int   i_receive_buffer = 0;
720     int            i_frame_buffer = DEFAULT_FRAME_BUFFER_SIZE;
721     unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
722     const char     *p_sess_lang = NULL;
723     const char     *p_lang;
724
725     b_rtsp_tcp    = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
726                     var_GetBool( p_demux, "rtsp-http" );
727     i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
728
729
730     /* Create the session from the SDP */
731     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
732     {
733         msg_Err( p_demux, "Could not create the RTSP Session: %s",
734             p_sys->env->getResultMsg() );
735         return VLC_EGENERIC;
736     }
737
738     if( strcmp( p_sys->p_sdp, "m=" ) != 0 )
739     {
740         const char *p_sess_attr_end;
741
742         p_sess_attr_end = strstr( p_sys->p_sdp, "\nm=" );
743         if( !p_sess_attr_end )
744             p_sess_attr_end = strstr( p_sys->p_sdp, "\rm=" );
745
746         p_sess_lang = p_sess_attr_end ? strstr( p_sys->p_sdp, "a=lang:" ) : NULL;
747         if( p_sess_lang &&
748             p_sess_lang - p_sys->p_sdp > p_sess_attr_end - p_sys->p_sdp )
749             p_sess_lang = NULL;
750     }
751
752     /* Initialise each media subsession */
753     iter = new MediaSubsessionIterator( *p_sys->ms );
754     while( ( sub = iter->next() ) != NULL )
755     {
756         Boolean bInit;
757         live_track_t *tk;
758
759         /* Value taken from mplayer */
760         if( !strcmp( sub->mediumName(), "audio" ) )
761             i_receive_buffer = 100000;
762         else if( !strcmp( sub->mediumName(), "video" ) )
763         {
764             int i_var_buf_size = var_InheritInteger( p_demux, "rtsp-frame-buffer-size" );
765             if( i_var_buf_size > 0 )
766                 i_frame_buffer = i_var_buf_size;
767             i_receive_buffer = 2000000;
768         }
769         else if( !strcmp( sub->mediumName(), "text" ) )
770             ;
771         else continue;
772
773         if( strcasestr( sub->codecName(), "REAL" ) )
774         {
775             msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
776             p_sys->b_real = true; /* This is a problem, we'll handle it later */
777             continue;
778         }
779
780         if( p_sys->rtsp && i_client_port != -1 )
781         {
782             sub->setClientPortNum( i_client_port );
783             i_client_port += 2;
784         }
785
786         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
787             bInit = sub->initiate( 0 );
788         else
789             bInit = sub->initiate();
790
791         if( !bInit )
792         {
793             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
794                       sub->mediumName(), sub->codecName(),
795                       p_sys->env->getResultMsg() );
796         }
797         else
798         {
799             if( sub->rtpSource() != NULL )
800             {
801                 int fd = sub->rtpSource()->RTPgs()->socketNum();
802
803                 /* Increase the buffer size */
804                 if( i_receive_buffer > 0 )
805                     increaseReceiveBufferTo( *p_sys->env, fd, i_receive_buffer );
806
807                 /* Increase the RTP reorder timebuffer just a bit */
808                 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
809             }
810             msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
811                      sub->codecName() );
812
813             /* Issue the SETUP */
814             if( p_sys->rtsp )
815             {
816                 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
817                                                toBool( b_rtsp_tcp ),
818                                                toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
819                 if( !wait_Live555_response( p_demux ) )
820                 {
821                     /* if we get an unsupported transport error, toggle TCP
822                      * use and try again */
823                     if( p_sys->i_live555_ret == 461 )
824                         p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
825                                                        !toBool( b_rtsp_tcp ), False );
826                     if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
827                     {
828                         msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
829                                  sub->mediumName(), sub->codecName(),
830                                  p_sys->env->getResultMsg() );
831                         continue;
832                     }
833                     else
834                     {
835                         var_SetBool( p_demux, "rtsp-tcp", true );
836                         b_rtsp_tcp = true;
837                     }
838                 }
839             }
840
841             /* Check if we will receive data from this subsession for
842              * this track */
843             if( sub->readSource() == NULL ) continue;
844             if( !p_sys->b_multicast )
845             {
846                 /* We need different rollover behaviour for multicast */
847                 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
848             }
849
850             tk = (live_track_t*)malloc( sizeof( live_track_t ) );
851             if( !tk )
852             {
853                 delete iter;
854                 return VLC_ENOMEM;
855             }
856             tk->p_demux     = p_demux;
857             tk->sub         = sub;
858             tk->p_es        = NULL;
859             tk->format      = live_track_t::SINGLE_STREAM;
860             tk->p_asf_block = NULL;
861             tk->b_discard_trunc = false;
862             tk->p_out_muxed = NULL;
863             tk->waiting     = 0;
864             tk->b_rtcp_sync = false;
865             tk->b_flushing_discontinuity = false;
866             tk->i_next_block_flags = 0;
867             tk->i_lastpts   = VLC_TS_INVALID;
868             tk->i_pcr       = VLC_TS_INVALID;
869             tk->f_npt       = 0.;
870             tk->state       = live_track_t::STATE_SELECTED;
871             tk->i_buffer    = i_frame_buffer;
872             tk->p_buffer    = (uint8_t *)malloc( i_frame_buffer );
873
874             if( !tk->p_buffer )
875             {
876                 free( tk );
877                 delete iter;
878                 return VLC_ENOMEM;
879             }
880
881             /* Value taken from mplayer */
882             if( !strcmp( sub->mediumName(), "audio" ) )
883             {
884                 es_format_Init( &tk->fmt, AUDIO_ES, VLC_CODEC_UNKNOWN );
885                 tk->fmt.audio.i_channels = sub->numChannels();
886                 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
887
888                 if( !strcmp( sub->codecName(), "MPA" ) ||
889                     !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
890                     !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
891                 {
892                     tk->fmt.i_codec = VLC_CODEC_MPGA;
893                     tk->fmt.audio.i_rate = 0;
894                 }
895                 else if( !strcmp( sub->codecName(), "AC3" ) )
896                 {
897                     tk->fmt.i_codec = VLC_CODEC_A52;
898                     tk->fmt.audio.i_rate = 0;
899                 }
900                 else if( !strcmp( sub->codecName(), "L16" ) )
901                 {
902                     tk->fmt.i_codec = VLC_CODEC_S16B;
903                     tk->fmt.audio.i_bitspersample = 16;
904                 }
905                 else if( !strcmp( sub->codecName(), "L20" ) )
906                 {
907                     tk->fmt.i_codec = VLC_CODEC_S20B;
908                     tk->fmt.audio.i_bitspersample = 20;
909                 }
910                 else if( !strcmp( sub->codecName(), "L24" ) )
911                 {
912                     tk->fmt.i_codec = VLC_CODEC_S24B;
913                     tk->fmt.audio.i_bitspersample = 24;
914                 }
915                 else if( !strcmp( sub->codecName(), "L8" ) )
916                 {
917                     tk->fmt.i_codec = VLC_CODEC_U8;
918                     tk->fmt.audio.i_bitspersample = 8;
919                 }
920                 else if( !strcmp( sub->codecName(), "DAT12" ) )
921                 {
922                     tk->fmt.i_codec = VLC_CODEC_DAT12;
923                     tk->fmt.audio.i_bitspersample = 12;
924                 }
925                 else if( !strcmp( sub->codecName(), "PCMU" ) )
926                 {
927                     tk->fmt.i_codec = VLC_CODEC_MULAW;
928                     tk->fmt.audio.i_bitspersample = 8;
929                 }
930                 else if( !strcmp( sub->codecName(), "PCMA" ) )
931                 {
932                     tk->fmt.i_codec = VLC_CODEC_ALAW;
933                     tk->fmt.audio.i_bitspersample = 8;
934                 }
935                 else if( !strncmp( sub->codecName(), "G726", 4 ) )
936                 {
937                     tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
938                     tk->fmt.audio.i_rate = 8000;
939                     tk->fmt.audio.i_channels = 1;
940                     if( !strcmp( sub->codecName()+5, "40" ) )
941                         tk->fmt.i_bitrate = 40000;
942                     else if( !strcmp( sub->codecName()+5, "32" ) )
943                         tk->fmt.i_bitrate = 32000;
944                     else if( !strcmp( sub->codecName()+5, "24" ) )
945                         tk->fmt.i_bitrate = 24000;
946                     else if( !strcmp( sub->codecName()+5, "16" ) )
947                         tk->fmt.i_bitrate = 16000;
948                 }
949                 else if( !strcmp( sub->codecName(), "AMR" ) )
950                 {
951                     tk->fmt.i_codec = VLC_CODEC_AMR_NB;
952                 }
953                 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
954                 {
955                     tk->fmt.i_codec = VLC_CODEC_AMR_WB;
956                 }
957                 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
958                 {
959                     unsigned int i_extra;
960                     uint8_t      *p_extra;
961
962                     tk->fmt.i_codec = VLC_CODEC_MP4A;
963
964                     if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
965                                                              i_extra ) ) )
966                     {
967                         tk->fmt.i_extra = i_extra;
968                         tk->fmt.p_extra = xmalloc( i_extra );
969                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
970                         delete[] p_extra;
971                     }
972                     /* Because the "faad" decoder does not handle the LATM
973                      * data length field at the start of each returned LATM
974                      * frame, tell the RTP source to omit. */
975                     ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
976                 }
977                 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
978                 {
979                     unsigned int i_extra;
980                     uint8_t      *p_extra;
981
982                     tk->fmt.i_codec = VLC_CODEC_MP4A;
983
984                     if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
985                                                            i_extra ) ) )
986                     {
987                         tk->fmt.i_extra = i_extra;
988                         tk->fmt.p_extra = xmalloc( i_extra );
989                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
990                         delete[] p_extra;
991                     }
992                 }
993                 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
994                 {
995                     tk->format = live_track_t::ASF_STREAM;
996                     if( p_sys->p_out_asf == NULL )
997                         p_sys->p_out_asf =
998                             vlc_demux_chained_New( VLC_OBJECT(p_demux), "asf",
999                                                    p_demux->out );
1000                 }
1001                 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1002                          !strcmp( sub->codecName(), "X-QUICKTIME" ) )
1003                 {
1004                     tk->format = live_track_t::QUICKTIME_STREAM;
1005                 }
1006                 else if( !strcmp( sub->codecName(), "SPEEX" ) )
1007                 {
1008                     tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
1009                 }
1010                 else if( !strcmp( sub->codecName(), "VORBIS" ) )
1011                 {
1012                     tk->fmt.i_codec = VLC_CODEC_VORBIS;
1013                     unsigned int i_extra;
1014                     unsigned char *p_extra;
1015                     if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
1016                                                         i_extra ) ) )
1017                     {
1018                         tk->fmt.i_extra = i_extra;
1019                         tk->fmt.p_extra = p_extra;
1020                     }
1021                     else
1022                         msg_Warn( p_demux,"Missing or unsupported vorbis header." );
1023                 }
1024                 else if( !strcmp( sub->codecName(), "OPUS" ) )
1025                 {
1026                     tk->fmt.i_codec = VLC_CODEC_OPUS;
1027                 }
1028             }
1029             else if( !strcmp( sub->mediumName(), "video" ) )
1030             {
1031                 es_format_Init( &tk->fmt, VIDEO_ES, VLC_CODEC_UNKNOWN );
1032                 if( !strcmp( sub->codecName(), "MPV" ) )
1033                 {
1034                     tk->fmt.i_codec = VLC_CODEC_MPGV;
1035                     tk->fmt.b_packetized = false;
1036                 }
1037                 else if( !strcmp( sub->codecName(), "H263" ) ||
1038                          !strcmp( sub->codecName(), "H263-1998" ) ||
1039                          !strcmp( sub->codecName(), "H263-2000" ) )
1040                 {
1041                     tk->fmt.i_codec = VLC_CODEC_H263;
1042                 }
1043                 else if( !strcmp( sub->codecName(), "H261" ) )
1044                 {
1045                     tk->fmt.i_codec = VLC_CODEC_H261;
1046                 }
1047                 else if( !strcmp( sub->codecName(), "H264" ) )
1048                 {
1049                     unsigned int i_extra = 0;
1050                     uint8_t      *p_extra = NULL;
1051
1052                     tk->fmt.i_codec = VLC_CODEC_H264;
1053                     tk->fmt.b_packetized = false;
1054
1055                     if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
1056                                                     i_extra ) ) )
1057                     {
1058                         tk->fmt.i_extra = i_extra;
1059                         tk->fmt.p_extra = xmalloc( i_extra );
1060                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
1061
1062                         delete[] p_extra;
1063                     }
1064                 }
1065 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1393372800 // 2014.02.26
1066                 else if( !strcmp( sub->codecName(), "H265" ) )
1067                 {
1068                    unsigned int i_extra1 = 0, i_extra2 = 0, i_extra3 = 0, i_extraTot;
1069                     uint8_t      *p_extra1 = NULL, *p_extra2 = NULL, *p_extra3 = NULL;
1070
1071                     tk->fmt.i_codec = VLC_CODEC_HEVC;
1072                     tk->fmt.b_packetized = false;
1073
1074                     p_extra1 = parseH264ConfigStr( sub->fmtp_spropvps(), i_extra1 );
1075                     p_extra2 = parseH264ConfigStr( sub->fmtp_spropsps(), i_extra2 );
1076                     p_extra3 = parseH264ConfigStr( sub->fmtp_sproppps(), i_extra3 );
1077                    i_extraTot = i_extra1 + i_extra2 + i_extra3;
1078                    if( i_extraTot > 0 )
1079                     {
1080                         tk->fmt.i_extra = i_extraTot;
1081                         tk->fmt.p_extra = xmalloc( i_extraTot );
1082                        if( p_extra1 )
1083                        {
1084                             memcpy( tk->fmt.p_extra, p_extra1, i_extra1 );
1085                        }
1086                        if( p_extra2 )
1087                        {
1088                          memcpy( ((char*)tk->fmt.p_extra)+i_extra1, p_extra2, i_extra2 );
1089                        }
1090                        if( p_extra3 )
1091                        {
1092                          memcpy( ((char*)tk->fmt.p_extra)+i_extra1+i_extra2, p_extra3, i_extra3 );
1093                        }
1094
1095                         delete[] p_extra1; delete[] p_extra2; delete[] p_extra3;
1096                     }
1097                 }
1098 #endif
1099                 else if( !strcmp( sub->codecName(), "JPEG" ) )
1100                 {
1101                     tk->fmt.i_codec = VLC_CODEC_MJPG;
1102                 }
1103                 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1104                 {
1105                     unsigned int i_extra;
1106                     uint8_t      *p_extra;
1107
1108                     tk->fmt.i_codec = VLC_CODEC_MP4V;
1109
1110                     if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1111                                                            i_extra ) ) )
1112                     {
1113                         tk->fmt.i_extra = i_extra;
1114                         tk->fmt.p_extra = xmalloc( i_extra );
1115                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
1116                         delete[] p_extra;
1117                     }
1118                 }
1119                 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1120                          !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1121                          !strcmp( sub->codecName(), "X-QDM" ) ||
1122                          !strcmp( sub->codecName(), "X-SV3V-ES" )  ||
1123                          !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1124                 {
1125                     tk->format = live_track_t::QUICKTIME_STREAM;
1126                 }
1127                 else if( !strcmp( sub->codecName(), "MP2T" ) )
1128                 {
1129                     tk->format = live_track_t::MULTIPLEXED_STREAM;
1130                     tk->p_out_muxed =
1131                         vlc_demux_chained_New( VLC_OBJECT(p_demux), "ts",
1132                                                p_demux->out );
1133                 }
1134                 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1135                          !strcmp( sub->codecName(), "MP1S" ) )
1136                 {
1137                     tk->format = live_track_t::MULTIPLEXED_STREAM;
1138                     tk->p_out_muxed =
1139                         vlc_demux_chained_New( VLC_OBJECT(p_demux), "ps",
1140                                                p_demux->out );
1141                 }
1142                 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1143                 {
1144                     tk->format = live_track_t::ASF_STREAM;
1145                     if( p_sys->p_out_asf == NULL )
1146                         p_sys->p_out_asf =
1147                             vlc_demux_chained_New( VLC_OBJECT(p_demux),
1148                                                    "asf", p_demux->out );
1149                 }
1150                 else if( !strcmp( sub->codecName(), "DV" ) )
1151                 {
1152                     tk->format = live_track_t::MULTIPLEXED_STREAM;
1153                     tk->b_discard_trunc = true;
1154                     tk->p_out_muxed =
1155                         vlc_demux_chained_New( VLC_OBJECT(p_demux), "rawdv",
1156                                                p_demux->out );
1157                 }
1158                 else if( !strcmp( sub->codecName(), "VP8" ) )
1159                 {
1160                     tk->fmt.i_codec = VLC_CODEC_VP8;
1161                 }
1162                 else if( !strcmp( sub->codecName(), "THEORA" ) )
1163                 {
1164                     tk->fmt.i_codec = VLC_CODEC_THEORA;
1165                     unsigned int i_extra;
1166                     unsigned char *p_extra;
1167                     if( ( p_extra=parseVorbisConfigStr( sub->fmtp_config(),
1168                                                         i_extra ) ) )
1169                     {
1170                         tk->fmt.i_extra = i_extra;
1171                         tk->fmt.p_extra = p_extra;
1172                     }
1173                     else
1174                         msg_Warn( p_demux,"Missing or unsupported theora header." );
1175                 }
1176             }
1177             else if( !strcmp( sub->mediumName(), "text" ) )
1178             {
1179                 es_format_Init( &tk->fmt, SPU_ES, VLC_CODEC_UNKNOWN );
1180
1181                 if( !strcmp( sub->codecName(), "T140" ) )
1182                 {
1183                     tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1184                 }
1185             }
1186
1187             /* Try and parse a=lang: attribute */
1188             p_lang = strstr( sub->savedSDPLines(), "a=lang:" );
1189             if( !p_lang )
1190                 p_lang = p_sess_lang;
1191
1192             if( p_lang )
1193             {
1194                 unsigned i_lang_len;
1195                 p_lang += 7;
1196                 i_lang_len = strcspn( p_lang, " \r\n" );
1197                 tk->fmt.psz_language = strndup( p_lang, i_lang_len );
1198             }
1199
1200             if( tk->format == live_track_t::SINGLE_STREAM )
1201             {
1202                 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1203             }
1204
1205             if( sub->rtcpInstance() != NULL )
1206             {
1207                 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1208             }
1209
1210             if( tk->p_es ||
1211                 tk->format == live_track_t::QUICKTIME_STREAM ||
1212                (tk->format == live_track_t::MULTIPLEXED_STREAM && tk->p_out_muxed ) ||
1213                (tk->format == live_track_t::ASF_STREAM && p_sys->p_out_asf ) )
1214             {
1215                 TAB_APPEND_CAST( (live_track_t **), p_sys->i_track, p_sys->track, tk );
1216             }
1217             else
1218             {
1219                 /* BUG ??? */
1220                 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1221                 es_format_Clean( &tk->fmt );
1222                 free( tk );
1223             }
1224         }
1225     }
1226     delete iter;
1227     if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1228
1229     /* Retrieve the starttime if possible */
1230     p_sys->f_npt_start = p_sys->ms->playStartTime();
1231
1232     /* Retrieve the duration if possible */
1233     p_sys->f_npt_length = p_sys->ms->playEndTime();
1234
1235     /* */
1236     msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1237
1238     /* */
1239     p_sys->b_no_data = true;
1240     p_sys->i_no_data_ti = 0;
1241     p_sys->b_rtcp_sync = false;
1242     p_sys->i_pcr = VLC_TS_INVALID;
1243
1244     return i_return;
1245 }
1246
1247 /*****************************************************************************
1248  * Play: starts the actual playback of the stream
1249  *****************************************************************************/
1250 static int Play( demux_t *p_demux )
1251 {
1252     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1253
1254     if( p_sys->rtsp )
1255     {
1256         /* The PLAY */
1257         p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_npt_start, -1, 1 );
1258
1259         if( !wait_Live555_response(p_demux) )
1260         {
1261             msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1262             return VLC_EGENERIC;
1263         }
1264
1265         /* Retrieve the timeout value and set up a timeout prevention thread */
1266         int timeout = p_sys->rtsp->sessionTimeoutParameter();
1267         if( timeout <= 2 )
1268             timeout = 60; /* default value from RFC2326 */
1269         msg_Dbg( p_demux, "We have a timeout of %d seconds", timeout );
1270
1271         mtime_t interval = (timeout - 2) * CLOCK_FREQ;
1272         vlc_timer_schedule( p_sys->timer, false, interval, interval);
1273     }
1274     p_sys->i_pcr = VLC_TS_INVALID;
1275
1276     /* Retrieve the starttime if possible */
1277     p_sys->f_npt_start = p_sys->ms->playStartTime();
1278     if( p_sys->ms->playEndTime() > 0 )
1279         p_sys->f_npt_length = p_sys->ms->playEndTime();
1280
1281     msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1282     return VLC_SUCCESS;
1283 }
1284
1285 /*****************************************************************************
1286  * HasSharedSession: returns if the session is shared with another stream
1287  *****************************************************************************/
1288 static bool HasSharedSession( MediaSubsession *session )
1289 {
1290     MediaSubsessionIterator *it =
1291             new MediaSubsessionIterator( session->parentSession() );
1292     MediaSubsession *subsession;
1293     bool b_shared = false;
1294     while( (subsession = it->next()) != NULL )
1295     {
1296         if( session == subsession )
1297             continue;
1298         if( !strcmp( session->sessionId(), subsession->sessionId() ) )
1299         {
1300             b_shared = true;
1301             break;
1302         }
1303     }
1304     delete it;
1305     return b_shared;
1306 }
1307
1308 /*****************************************************************************
1309  * ResumeTrack: setup or resume a silenced track
1310  *****************************************************************************/
1311 static void ResumeTrack( demux_t *p_demux, live_track_t *tk )
1312 {
1313     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1314
1315     bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1316             var_GetBool( p_demux, "rtsp-http" );
1317     p_sys->rtsp->sendSetupCommand( *tk->sub, default_live555_callback, False,
1318                                    toBool( b_rtsp_tcp ),
1319                                    toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
1320     if( !wait_Live555_response( p_demux ) )
1321     {
1322         msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
1323                  tk->sub->mediumName(), tk->sub->codecName(),
1324                  p_sys->env->getResultMsg() );
1325     }
1326     else
1327     {
1328         p_sys->rtsp->sendPlayCommand( *tk->sub, default_live555_callback, -1, -1, p_sys->ms->scale() );
1329         if( !wait_Live555_response(p_demux) )
1330         {
1331             msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1332             if( (p_sys->capabilities & CAP_SUBSESSION_TEARDOWN) ||
1333                 !HasSharedSession( tk->sub ) )
1334             {
1335                 tk->state = live_track_t::STATE_TEARDOWN;
1336                 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1337             }
1338         }
1339         else
1340             tk->state = live_track_t::STATE_SELECTED;
1341     }
1342 }
1343
1344 /*****************************************************************************
1345  * Demux:
1346  *****************************************************************************/
1347 static int Demux( demux_t *p_demux )
1348 {
1349     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1350     TaskToken      task;
1351
1352     bool            b_send_pcr = true;
1353     int             i;
1354
1355     /* Protect Live555 from simultaneous calls in TimeoutPrevention()
1356        during pause */
1357     vlc_mutex_locker locker(&p_sys->timeout_mutex);
1358
1359     for( i = 0; i < p_sys->i_track; i++ )
1360     {
1361         live_track_t *tk = p_sys->track[i];
1362
1363         if( tk->p_es )
1364         {
1365             bool b;
1366             es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1367             if( !b && (tk->state == live_track_t::STATE_SELECTED) && p_sys->rtsp )
1368             {
1369                 if( (p_sys->capabilities & CAP_SUBSESSION_TEARDOWN) ||
1370                     !HasSharedSession( tk->sub ) )
1371                 {
1372                     tk->state = live_track_t::STATE_TEARDOWN;
1373                     p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1374                 }
1375                 else tk->state = live_track_t::STATE_IGNORED;
1376             }
1377             else if( b && tk->state != live_track_t::STATE_SELECTED )
1378             {
1379                 if( tk->state != live_track_t::STATE_IGNORED )
1380                     ResumeTrack( p_demux, tk );
1381                 else
1382                     tk->state = live_track_t::STATE_SELECTED;
1383
1384                 if( tk->state != live_track_t::STATE_SELECTED )
1385                     es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1386             }
1387         }
1388
1389         if( tk->format == live_track_t::ASF_STREAM ||
1390             tk->format == live_track_t::MULTIPLEXED_STREAM )
1391         {
1392             b_send_pcr = false;
1393         }
1394     }
1395
1396     /* First warn we want to read data */
1397     p_sys->event_data = 0;
1398     for( i = 0; i < p_sys->i_track; i++ )
1399     {
1400         live_track_t *tk = p_sys->track[i];
1401
1402         if( tk->waiting == 0 )
1403         {
1404             tk->waiting = 1;
1405             tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1406                                           StreamRead, tk, StreamClose, tk );
1407         }
1408     }
1409     /* Create a task that will be called if we wait more than 300ms */
1410     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1411
1412     /* Do the read */
1413     p_sys->scheduler->doEventLoop( &p_sys->event_data );
1414
1415     /* remove the task */
1416     p_sys->scheduler->unscheduleDelayedTask( task );
1417
1418     if( b_send_pcr )
1419     {
1420         mtime_t i_minpcr = VLC_TS_INVALID;
1421         bool b_need_flush = false;
1422
1423         /* Check for gap in pts value */
1424         for( i = 0; i < p_sys->i_track; i++ )
1425         {
1426             live_track_t *tk = p_sys->track[i];
1427
1428             if( tk->state != live_track_t::STATE_SELECTED ||
1429                (p_sys->b_rtcp_sync && !tk->b_rtcp_sync) )
1430                 continue;
1431
1432             /* Check for gap in pts value */
1433             b_need_flush |= (tk->b_flushing_discontinuity);
1434
1435             if( i_minpcr == VLC_TS_INVALID || ( tk->i_pcr != VLC_TS_INVALID && i_minpcr > tk->i_pcr ) )
1436                 i_minpcr = tk->i_pcr;
1437         }
1438
1439         if( p_sys->i_pcr > VLC_TS_INVALID && b_need_flush )
1440         {
1441             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1442             p_sys->i_pcr = i_minpcr;
1443             p_sys->f_npt = 0.;
1444
1445             for( i = 0; i < p_sys->i_track; i++ )
1446             {
1447                 live_track_t *tk = p_sys->track[i];
1448                 tk->i_lastpts = VLC_TS_INVALID;
1449                 tk->i_pcr = VLC_TS_INVALID;
1450                 tk->f_npt = 0.;
1451                 tk->b_flushing_discontinuity = false;
1452                 tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1453             }
1454             if( p_sys->i_pcr != VLC_TS_INVALID )
1455                 es_out_SetPCR( p_demux->out, VLC_TS_0 +
1456                                __MAX(0, p_sys->i_pcr - PCR_OFF) );
1457         }
1458         else if( p_sys->i_pcr == VLC_TS_INVALID ||
1459                  i_minpcr > p_sys->i_pcr + PCR_OBS )
1460         {
1461             p_sys->i_pcr = __MAX(0, i_minpcr - PCR_OFF);
1462             if( p_sys->i_pcr != VLC_TS_INVALID )
1463                 es_out_SetPCR( p_demux->out, VLC_TS_0 + p_sys->i_pcr );
1464         }
1465     }
1466
1467     if( p_sys->b_multicast && p_sys->b_no_data &&
1468         ( p_sys->i_no_data_ti > 120 ) )
1469     {
1470         /* FIXME Make this configurable
1471         msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1472         return 0;
1473         */
1474     }
1475     else if( !p_sys->b_multicast && !p_sys->b_paused &&
1476               p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1477     {
1478         bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1479                                 var_GetBool( p_demux, "rtsp-http" );
1480
1481         if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1482         {
1483             msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1484             if( RollOverTcp( p_demux ) )
1485             {
1486                 msg_Err( p_demux, "TCP rollover failed, aborting" );
1487                 return 0;
1488             }
1489             return 1;
1490         }
1491         msg_Err( p_demux, "no data received in 10s, aborting" );
1492         return 0;
1493     }
1494     else if( !p_sys->b_multicast && !p_sys->b_paused &&
1495              ( p_sys->i_no_data_ti > 34 ) )
1496     {
1497         /* EOF ? */
1498         msg_Warn( p_demux, "no data received in 10s, eof ?" );
1499         return 0;
1500     }
1501     return p_sys->b_error ? 0 : 1;
1502 }
1503
1504 /*****************************************************************************
1505  * Control:
1506  *****************************************************************************/
1507 static int Control( demux_t *p_demux, int i_query, va_list args )
1508 {
1509     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1510     int64_t *pi64, i64;
1511     double  *pf, f;
1512     bool *pb;
1513
1514     vlc_mutex_locker locker(&p_sys->timeout_mutex); /* (see same in Demux) */
1515
1516     switch( i_query )
1517     {
1518         case DEMUX_GET_TIME:
1519             pi64 = va_arg( args, int64_t * );
1520             if( p_sys->f_npt > 0 )
1521             {
1522                 *pi64 = (int64_t)(p_sys->f_npt * 1000000.);
1523                 return VLC_SUCCESS;
1524             }
1525             return VLC_EGENERIC;
1526
1527         case DEMUX_GET_LENGTH:
1528             pi64 = va_arg( args, int64_t * );
1529             if( p_sys->f_npt_length > 0 )
1530             {
1531                 double d_length = p_sys->f_npt_length * 1000000.0;
1532                 if( d_length >= INT64_MAX )
1533                     *pi64 = INT64_MAX;
1534                 else
1535                     *pi64 = (int64_t)d_length;
1536                 return VLC_SUCCESS;
1537             }
1538             return VLC_EGENERIC;
1539
1540         case DEMUX_GET_POSITION:
1541             pf = va_arg( args, double * );
1542             if( (p_sys->f_npt_length > 0) && (p_sys->f_npt > 0) )
1543             {
1544                 *pf = p_sys->f_npt / p_sys->f_npt_length;
1545                 return VLC_SUCCESS;
1546             }
1547             return VLC_EGENERIC;
1548
1549         case DEMUX_SET_POSITION:
1550         case DEMUX_SET_TIME:
1551             if( p_sys->rtsp && (p_sys->f_npt_length > 0) )
1552             {
1553                 float time;
1554
1555                 if( (i_query == DEMUX_SET_TIME) && (p_sys->f_npt > 0) )
1556                 {
1557                     i64 = va_arg( args, int64_t );
1558                     time = (float)(i64 / 1000000.0); /* in second */
1559                 }
1560                 else if( i_query == DEMUX_SET_TIME )
1561                     return VLC_EGENERIC;
1562                 else
1563                 {
1564                     f = va_arg( args, double );
1565                     time = f * p_sys->f_npt_length;   /* in second */
1566                 }
1567
1568                 if( p_sys->b_paused )
1569                 {
1570                     p_sys->f_seek_request = time;
1571                     return VLC_SUCCESS;
1572                 }
1573
1574                 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1575
1576                 if( !wait_Live555_response( p_demux ) )
1577                 {
1578                     msg_Err( p_demux, "PAUSE before seek failed %s",
1579                         p_sys->env->getResultMsg() );
1580                     return VLC_EGENERIC;
1581                 }
1582
1583                 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1584
1585                 if( !wait_Live555_response( p_demux ) )
1586                 {
1587                     msg_Err( p_demux, "seek PLAY failed %s",
1588                         p_sys->env->getResultMsg() );
1589                     return VLC_EGENERIC;
1590                 }
1591                 p_sys->i_pcr = VLC_TS_INVALID;
1592
1593                 for( int i = 0; i < p_sys->i_track; i++ )
1594                 {
1595                     p_sys->track[i]->b_rtcp_sync = false;
1596                     p_sys->track[i]->i_lastpts = VLC_TS_INVALID;
1597                     p_sys->track[i]->i_pcr = VLC_TS_INVALID;
1598                 }
1599
1600                 /* Retrieve the starttime if possible */
1601                 p_sys->f_npt = p_sys->f_npt_start = p_sys->ms->playStartTime();
1602
1603                 /* Retrieve the duration if possible */
1604                 if( p_sys->ms->playEndTime() > 0 )
1605                     p_sys->f_npt_length = p_sys->ms->playEndTime();
1606
1607                 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1608                 return VLC_SUCCESS;
1609             }
1610             return VLC_EGENERIC;
1611
1612         /* Special for access_demux */
1613         case DEMUX_CAN_PAUSE:
1614         case DEMUX_CAN_SEEK:
1615             pb = va_arg( args, bool * );
1616             if( p_sys->rtsp && p_sys->f_npt_length > 0 )
1617                 /* Not always true, but will be handled in SET_PAUSE_STATE */
1618                 *pb = true;
1619             else
1620                 *pb = false;
1621             return VLC_SUCCESS;
1622
1623         case DEMUX_CAN_CONTROL_PACE:
1624             pb = va_arg( args, bool * );
1625
1626 #if 1       /* Disable for now until we have a clock synchro algo
1627              * which works with something else than MPEG over UDP */
1628             *pb = false;
1629 #else
1630             *pb = true;
1631 #endif
1632             return VLC_SUCCESS;
1633
1634         case DEMUX_CAN_CONTROL_RATE:
1635             pb = va_arg( args, bool * );
1636
1637             *pb = (p_sys->rtsp != NULL) &&
1638                   (p_sys->f_npt_length > 0) &&
1639                   (p_sys->capabilities & CAP_RATE_CONTROL);
1640             return VLC_SUCCESS;
1641
1642         case DEMUX_SET_RATE:
1643         {
1644             int *pi_int;
1645             double f_scale, f_old_scale;
1646
1647             if( !p_sys->rtsp || (p_sys->f_npt_length <= 0) ||
1648                 !(p_sys->capabilities & CAP_RATE_CONTROL) )
1649                 return VLC_EGENERIC;
1650
1651             /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1652              * supports Scale:
1653              *
1654              * "[...] should try to approximate the viewing rate, but
1655              *  may restrict the range of scale values that it supports.
1656              *  The response MUST contain the actual scale value chosen
1657              *  by the server."
1658              *
1659              * Scale = 1 indicates normal play
1660              * Scale > 1 indicates fast forward
1661              * Scale < 1 && Scale > 0 indicates slow motion
1662              * Scale < 0 value indicates rewind
1663              */
1664
1665             pi_int = va_arg( args, int * );
1666             f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1667             f_old_scale = p_sys->ms->scale();
1668
1669             /* Passing -1 for the start and end time will mean liveMedia won't
1670              * create a Range: section for the RTSP message. The server should
1671              * pick up from the current position */
1672             p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1673
1674             if( !wait_Live555_response( p_demux ) )
1675             {
1676                 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1677                         p_sys->env->getResultMsg() );
1678                 return VLC_EGENERIC;
1679             }
1680
1681             if( p_sys->ms->scale() == f_old_scale )
1682             {
1683                 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1684                           p_sys->ms->scale() );
1685                 return VLC_EGENERIC;
1686             }
1687
1688             /* ReSync the stream */
1689             p_sys->f_npt_start = 0;
1690             p_sys->i_pcr = VLC_TS_INVALID;
1691             p_sys->f_npt = 0.0;
1692
1693             *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1694             msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1695             return VLC_SUCCESS;
1696         }
1697
1698         case DEMUX_SET_PAUSE_STATE:
1699         {
1700             bool b_pause = (bool)va_arg( args, int );
1701             if( p_sys->rtsp == NULL )
1702                 return VLC_EGENERIC;
1703
1704             if( b_pause == p_sys->b_paused )
1705                 return VLC_SUCCESS;
1706             if( b_pause )
1707                 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1708             else
1709                 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1710                                               -1.0f, p_sys->ms->scale() );
1711
1712             if( !wait_Live555_response( p_demux ) )
1713             {
1714                 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1715                 return VLC_EGENERIC;
1716             }
1717             p_sys->f_seek_request = -1;
1718             p_sys->b_paused = b_pause;
1719
1720             if( !p_sys->b_paused )
1721             {
1722                 for( int i = 0; i < p_sys->i_track; i++ )
1723                 {
1724                     live_track_t *tk = p_sys->track[i];
1725                     tk->b_rtcp_sync = false;
1726                     tk->b_flushing_discontinuity = false;
1727                     tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1728                     tk->i_lastpts = VLC_TS_INVALID;
1729                     tk->i_pcr = VLC_TS_INVALID;
1730                 }
1731                 p_sys->i_pcr = VLC_TS_INVALID;
1732                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1733             }
1734
1735             /* Reset data received counter */
1736             p_sys->i_no_data_ti = 0;
1737
1738             /* Retrieve the starttime if possible */
1739             p_sys->f_npt_start = p_sys->ms->playStartTime();
1740
1741             /* Retrieve the duration if possible */
1742             if( p_sys->ms->playEndTime() )
1743                 p_sys->f_npt_length = p_sys->ms->playEndTime();
1744
1745             msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1746
1747             return VLC_SUCCESS;
1748         }
1749         case DEMUX_GET_TITLE_INFO:
1750         case DEMUX_SET_TITLE:
1751         case DEMUX_SET_SEEKPOINT:
1752             return VLC_EGENERIC;
1753
1754         case DEMUX_GET_PTS_DELAY:
1755             pi64 = va_arg( args, int64_t * );
1756             *pi64 = INT64_C(1000)
1757                   * var_InheritInteger( p_demux, "network-caching" );
1758             return VLC_SUCCESS;
1759
1760         default:
1761             return VLC_EGENERIC;
1762     }
1763 }
1764
1765 /*****************************************************************************
1766  * RollOverTcp: reopen the rtsp into TCP mode
1767  * XXX: ugly, a lot of code are duplicated from Open()
1768  * This should REALLY be fixed
1769  *****************************************************************************/
1770 static int RollOverTcp( demux_t *p_demux )
1771 {
1772     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1773     int i, i_return;
1774
1775     var_SetBool( p_demux, "rtsp-tcp", true );
1776
1777     /* We close the old RTSP session */
1778     vlc_timer_schedule(p_sys->timer, false, 0, 0);
1779     p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1780     Medium::close( p_sys->ms );
1781     RTSPClient::close( p_sys->rtsp );
1782
1783     for( i = 0; i < p_sys->i_track; i++ )
1784     {
1785         live_track_t *tk = p_sys->track[i];
1786
1787         if( tk->p_out_muxed ) vlc_demux_chained_Delete( tk->p_out_muxed );
1788         if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1789         if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1790         es_format_Clean( &tk->fmt );
1791         free( tk->p_buffer );
1792         free( tk );
1793     }
1794     TAB_CLEAN( p_sys->i_track, p_sys->track );
1795     if( p_sys->p_out_asf ) vlc_demux_chained_Delete( p_sys->p_out_asf );
1796
1797     p_sys->ms = NULL;
1798     p_sys->rtsp = NULL;
1799     p_sys->b_no_data = true;
1800     p_sys->i_no_data_ti = 0;
1801     p_sys->p_out_asf = NULL;
1802
1803     /* Reopen rtsp client */
1804     if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1805     {
1806         msg_Err( p_demux, "Failed to connect with %s", p_sys->psz_pl_url );
1807         goto error;
1808     }
1809
1810     if( p_sys->p_sdp == NULL )
1811     {
1812         msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1813         goto error;
1814     }
1815
1816     if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1817     {
1818         msg_Err( p_demux, "Nothing to play for %s", p_sys->psz_pl_url );
1819         goto error;
1820     }
1821
1822     if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1823         goto error;
1824
1825     return VLC_SUCCESS;
1826
1827 error:
1828     return VLC_EGENERIC;
1829 }
1830
1831
1832 /*****************************************************************************
1833  *
1834  *****************************************************************************/
1835 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1836                                 bool b_marker,
1837                                 const uint8_t *p_data, unsigned i_size )
1838 {
1839     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1840     const unsigned i_packet_size = p_sys->asfh.i_min_data_packet_size;
1841     block_t *p_list = NULL;
1842
1843     while( i_size >= 4 )
1844     {
1845         unsigned i_flags = p_data[0];
1846         unsigned i_length_offset = (p_data[1] << 16) |
1847                                    (p_data[2] <<  8) |
1848                                    (p_data[3]      );
1849         bool b_length = i_flags & 0x40;
1850         bool b_relative_ts = i_flags & 0x20;
1851         bool b_duration = i_flags & 0x10;
1852         bool b_location_id = i_flags & 0x08;
1853
1854         //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1855         //         b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1856         unsigned i_header_size = 4;
1857         if( b_relative_ts )
1858             i_header_size += 4;
1859         if( b_duration )
1860             i_header_size += 4;
1861         if( b_location_id )
1862             i_header_size += 4;
1863
1864         if( i_header_size > i_size )
1865         {
1866             msg_Warn( p_demux, "Invalid header size" );
1867             break;
1868         }
1869
1870         /* XXX
1871          * When b_length is true, the streams I found do not seems to respect
1872          * the documentation.
1873          * From them, I have failed to find which choice between '__MIN()' or
1874          * 'i_length_offset - i_header_size' is the right one.
1875          */
1876         unsigned i_payload;
1877         if( b_length )
1878             i_payload = __MIN( i_length_offset, i_size - i_header_size);
1879         else
1880             i_payload = i_size - i_header_size;
1881
1882         if( !tk->p_asf_block )
1883         {
1884             tk->p_asf_block = block_Alloc( i_packet_size );
1885             if( !tk->p_asf_block )
1886                 break;
1887             tk->p_asf_block->i_buffer = 0;
1888         }
1889         unsigned i_offset  = b_length ? 0 : i_length_offset;
1890         if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1891         {
1892             memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1893             tk->p_asf_block->i_buffer += i_payload;
1894             if( b_marker )
1895             {
1896                 /* We have a complete packet */
1897                 tk->p_asf_block->i_buffer = i_packet_size;
1898                 block_ChainAppend( &p_list, tk->p_asf_block );
1899                 tk->p_asf_block = NULL;
1900             }
1901         }
1902         else
1903         {
1904             /* Reset on broken stream */
1905             msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1906                      i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1907             tk->p_asf_block->i_buffer = 0;
1908         }
1909
1910         /* */
1911         p_data += i_header_size + i_payload;
1912         i_size -= i_header_size + i_payload;
1913     }
1914     return p_list;
1915 }
1916
1917 /*****************************************************************************
1918  *
1919  *****************************************************************************/
1920 static void StreamRead( void *p_private, unsigned int i_size,
1921                         unsigned int i_truncated_bytes, struct timeval pts,
1922                         unsigned int duration )
1923 {
1924     VLC_UNUSED( duration );
1925
1926     live_track_t   *tk = (live_track_t*)p_private;
1927     demux_t        *p_demux = tk->p_demux;
1928     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
1929     block_t        *p_block;
1930
1931     //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1932
1933     int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1934         (int64_t)pts.tv_usec;
1935
1936     /* XXX Beurk beurk beurk Avoid having negative value XXX */
1937     i_pts &= INT64_C(0x00ffffffffffffff);
1938
1939     /* Retrieve NPT for this pts */
1940     tk->f_npt = tk->sub->getNormalPlayTime(pts);
1941
1942     if( tk->format == live_track_t::QUICKTIME_STREAM && tk->p_es == NULL )
1943     {
1944         QuickTimeGenericRTPSource *qtRTPSource =
1945             (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1946         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1947         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1948
1949         /* Get codec information from the quicktime atoms :
1950          * http://developer.apple.com/quicktime/icefloe/dispatch026.html */
1951         if( tk->fmt.i_cat == VIDEO_ES ) {
1952             if( qtState.sdAtomSize < 16 + 32 )
1953             {
1954                 /* invalid */
1955                 p_sys->event_data = 0xff;
1956                 tk->waiting = 0;
1957                 return;
1958             }
1959             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1960             tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
1961             tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1962
1963             if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1964             {
1965                 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1966                 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1967                                   + qtRTPSource->qtState.sdAtomSize;
1968                 while (pos+8 < endpos) {
1969                     unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1970                     if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1971                     if( memcmp(pos+4, "avcC", 4) == 0 &&
1972                         atomLength > 8 &&
1973                         atomLength <= INT_MAX )
1974                     {
1975                         tk->fmt.i_extra = atomLength-8;
1976                         tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1977                         memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1978                         break;
1979                     }
1980                     pos += atomLength;
1981                 }
1982             }
1983             else
1984             {
1985                 tk->fmt.i_extra        = qtState.sdAtomSize - 16;
1986                 tk->fmt.p_extra        = xmalloc( tk->fmt.i_extra );
1987                 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1988             }
1989         }
1990         else {
1991             if( qtState.sdAtomSize < 24 )
1992             {
1993                 /* invalid */
1994                 p_sys->event_data = 0xff;
1995                 tk->waiting = 0;
1996                 return;
1997             }
1998             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1999             tk->fmt.audio.i_bitspersample = (sdAtom[22] << 8) | sdAtom[23];
2000         }
2001         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
2002     }
2003
2004 #if 0
2005     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
2006              i_size,
2007              pts.tv_sec * 1000000LL + pts.tv_usec );
2008 #endif
2009
2010     /* grow buffer if it looks like buffer is too small, but don't eat
2011      * up all the memory on strange streams */
2012     if( i_truncated_bytes > 0 )
2013     {
2014         if( tk->i_buffer < 2000000 )
2015         {
2016             void *p_tmp;
2017             msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
2018             msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
2019             p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
2020             if( p_tmp == NULL )
2021             {
2022                 msg_Warn( p_demux, "realloc failed" );
2023             }
2024             else
2025             {
2026                 tk->p_buffer = (uint8_t*)p_tmp;
2027                 tk->i_buffer *= 2;
2028             }
2029         }
2030
2031         if( tk->b_discard_trunc )
2032         {
2033             p_sys->event_data = 0xff;
2034             tk->waiting = 0;
2035             return;
2036         }
2037     }
2038
2039     assert( i_size <= tk->i_buffer );
2040
2041     if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
2042         tk->fmt.i_codec == VLC_CODEC_AMR_WB )
2043     {
2044         AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
2045
2046         if( (p_block = block_Alloc( i_size + 1 )) )
2047         {
2048             p_block->p_buffer[0] = amrSource->lastFrameHeader();
2049             memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
2050         }
2051     }
2052     else if( tk->fmt.i_codec == VLC_CODEC_H261 )
2053     {
2054         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
2055         uint32_t header = h261Source->lastSpecialHeader();
2056         if( (p_block = block_Alloc( i_size + 4 )) )
2057         {
2058             memcpy( p_block->p_buffer, &header, 4 );
2059             memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
2060         }
2061     }
2062     else if( tk->fmt.i_codec == VLC_CODEC_H264 || tk->fmt.i_codec == VLC_CODEC_HEVC )
2063     {
2064         if( tk->fmt.i_codec == VLC_CODEC_H264 && (tk->p_buffer[0] & 0x1f) >= 24 )
2065             msg_Warn( p_demux, "unsupported NAL type for H264" );
2066         else if( tk->fmt.i_codec == VLC_CODEC_HEVC && ((tk->p_buffer[0] & 0x7e)>>1) >= 48 )
2067             msg_Warn( p_demux, "unsupported NAL type for H265" );
2068
2069         /* Normal NAL type */
2070         if( (p_block = block_Alloc( i_size + 4 )) )
2071         {
2072             p_block->p_buffer[0] = 0x00;
2073             p_block->p_buffer[1] = 0x00;
2074             p_block->p_buffer[2] = 0x00;
2075             p_block->p_buffer[3] = 0x01;
2076             memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
2077         }
2078     }
2079     else if( tk->format == live_track_t::ASF_STREAM )
2080     {
2081         p_block = StreamParseAsf( p_demux, tk,
2082                                   tk->sub->rtpSource()->curPacketMarkerBit(),
2083                                   tk->p_buffer, i_size );
2084     }
2085     else
2086     {
2087         if( (p_block = block_Alloc( i_size )) )
2088             memcpy( p_block->p_buffer, tk->p_buffer, i_size );
2089     }
2090
2091     /* No data sent. Always in sync then */
2092     if( !tk->b_rtcp_sync && tk->sub->rtpSource() &&
2093          tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
2094     {
2095         msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
2096         p_sys->b_rtcp_sync = tk->b_rtcp_sync = true;
2097         if( tk->i_pcr != VLC_TS_INVALID )
2098         {
2099             tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
2100             const int64_t i_max_diff = CLOCK_FREQ * (( tk->fmt.i_cat == SPU_ES ) ? 60 : 1);
2101             tk->b_flushing_discontinuity = (llabs(i_pts - tk->i_pcr) > i_max_diff);
2102             tk->i_pcr = i_pts;
2103         }
2104     }
2105
2106     /* Update our global npt value */
2107     if( tk->f_npt > 0 &&
2108         ( tk->f_npt < p_sys->f_npt_length || p_sys->f_npt_length <= 0 ) )
2109         p_sys->f_npt = tk->f_npt;
2110
2111     if( p_block )
2112     {
2113         switch( tk->format )
2114         {
2115             case live_track_t::ASF_STREAM:
2116                 vlc_demux_chained_Send( p_sys->p_out_asf, p_block );
2117                 break;
2118             case live_track_t::MULTIPLEXED_STREAM:
2119                 vlc_demux_chained_Send( tk->p_out_muxed, p_block );
2120                 break;
2121             default:
2122                 if( i_pts != tk->i_lastpts )
2123                     p_block->i_pts = VLC_TS_0 + i_pts;
2124                 /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
2125                 switch( tk->fmt.i_codec )
2126                 {
2127                     case VLC_CODEC_MPGV:
2128                     case VLC_CODEC_H264:
2129                     case VLC_CODEC_HEVC:
2130                     case VLC_CODEC_VP8:
2131                         p_block->i_dts = VLC_TS_INVALID;
2132                         break;
2133                     default:
2134                         p_block->i_dts = VLC_TS_0 + i_pts;
2135                         break;
2136                 }
2137
2138                 if( i_truncated_bytes )
2139                     p_block->i_flags |= BLOCK_FLAG_CORRUPTED;
2140
2141                 if( unlikely(tk->i_next_block_flags) )
2142                 {
2143                     p_block->i_flags |= tk->i_next_block_flags;
2144                     tk->i_next_block_flags = 0;
2145                 }
2146                 es_out_Send( p_demux->out, tk->p_es, p_block );
2147                 if( i_pts > 0 )
2148                 {
2149                     if( tk->i_pcr < i_pts )
2150                         tk->i_pcr = i_pts;
2151                     tk->i_lastpts = i_pts;
2152                 }
2153                 break;
2154         }
2155     }
2156
2157     /* warn that's ok */
2158     p_sys->event_data = 0xff;
2159
2160     /* we have read data */
2161     tk->waiting = 0;
2162     p_sys->b_no_data = false;
2163     p_sys->i_no_data_ti = 0;
2164 }
2165
2166 /*****************************************************************************
2167  *
2168  *****************************************************************************/
2169 static void StreamClose( void *p_private )
2170 {
2171     live_track_t   *tk = (live_track_t*)p_private;
2172     demux_t        *p_demux = tk->p_demux;
2173     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2174     tk->state = live_track_t::STATE_IGNORED;
2175     p_sys->event_rtsp = 0xff;
2176     p_sys->event_data = 0xff;
2177
2178     if( tk->p_es )
2179         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
2180
2181     int nb_tracks = 0;
2182     for( int i = 0; i < p_sys->i_track; i++ )
2183     {
2184         if( p_sys->track[i]->state == live_track_t::STATE_SELECTED )
2185             nb_tracks++;
2186     }
2187     msg_Dbg( p_demux, "RTSP track Close, %d track remaining", nb_tracks );
2188     if( !nb_tracks )
2189         p_sys->b_error = true;
2190 }
2191
2192
2193 /*****************************************************************************
2194  *
2195  *****************************************************************************/
2196 static void TaskInterruptRTSP( void *p_private )
2197 {
2198     demux_t *p_demux = (demux_t*)p_private;
2199     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2200
2201     /* Avoid lock */
2202     p_sys->event_rtsp = 0xff;
2203 }
2204
2205 static void TaskInterruptData( void *p_private )
2206 {
2207     demux_t *p_demux = (demux_t*)p_private;
2208     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2209
2210     p_sys->i_no_data_ti++;
2211
2212     /* Avoid lock */
2213     p_sys->event_data = 0xff;
2214 }
2215
2216 /*****************************************************************************
2217  *
2218  *****************************************************************************/
2219 static void TimeoutPrevention( void *p_data )
2220 {
2221     demux_t *p_demux = (demux_t *) p_data;
2222     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2223     char *bye = NULL;
2224
2225     /* Protect Live555 from us calling their functions simultaneously
2226         with Demux() or Control() */
2227     vlc_mutex_locker locker(&p_sys->timeout_mutex);
2228
2229     /* If the timer fires while the demuxer owns the lock, and the demuxer
2230      * then torns the session down, the pointers will become NULL. By the time
2231      * this timer callback obtains the callback, either a new session was
2232      * created and the timer is rescheduled, or the pointers are still NULL
2233      * and the timer is descheduled. In the second case, bail out (then wait
2234      * for the timer to be rescheduled or destroyed). In the first case, this
2235      * might send an early refresh - that´s harmless but suboptimal (FIXME). */
2236     if( p_sys->rtsp == NULL || p_sys->ms == NULL )
2237         return;
2238
2239     bool use_get_param = p_sys->b_get_param;
2240
2241     /* Use GET_PARAMETERS if supported. wmserver dialect supports
2242      * it, but does not report this properly. */
2243     if( var_GetBool( p_demux, "rtsp-wmserver" ) )
2244         use_get_param = true;
2245
2246     if( use_get_param )
2247         p_sys->rtsp->sendGetParameterCommand( *p_sys->ms,
2248                                               default_live555_callback, bye );
2249     else
2250         p_sys->rtsp->sendOptionsCommand( default_live555_callback, NULL );
2251
2252     if( !wait_Live555_response( p_demux ) )
2253     {
2254         msg_Err( p_demux, "keep-alive failed: %s",
2255                  p_sys->env->getResultMsg() );
2256         /* Just continue, worst case is we get timed out later */
2257     }
2258 }
2259
2260 /*****************************************************************************
2261  *
2262  *****************************************************************************/
2263 static int ParseASF( demux_t *p_demux )
2264 {
2265     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
2266
2267     const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
2268     char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2269     char *psz_end;
2270     block_t *p_header;
2271
2272     /* Parse the asf header */
2273     if( psz_asf == NULL )
2274         return VLC_EGENERIC;
2275
2276     psz_asf += strlen( psz_marker );
2277     psz_asf = strdup( psz_asf );    /* Duplicate it */
2278     psz_end = strchr( psz_asf, '\n' );
2279
2280     while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2281         *psz_end-- = '\0';
2282
2283     if( psz_asf >= psz_end )
2284     {
2285         free( psz_asf );
2286         return VLC_EGENERIC;
2287     }
2288
2289     /* Always smaller */
2290     p_header = block_Alloc( psz_end - psz_asf );
2291     p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2292                                                p_header->i_buffer, psz_asf );
2293     //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2294     if( p_header->i_buffer <= 0 )
2295     {
2296         free( psz_asf );
2297         return VLC_EGENERIC;
2298     }
2299
2300     /* Parse it to get packet size */
2301     asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2302
2303     /* Send it to demuxer */
2304     vlc_demux_chained_Send( p_sys->p_out_asf, p_header );
2305
2306     free( psz_asf );
2307     return VLC_SUCCESS;
2308 }
2309
2310
2311 static unsigned char* parseH264ConfigStr( char const* configStr,
2312                                           unsigned int& configSize )
2313 {
2314     char *dup, *psz;
2315     size_t i_records = 1;
2316
2317     configSize = 0;
2318
2319     if( configStr == NULL || *configStr == '\0' )
2320         return NULL;
2321
2322     psz = dup = strdup( configStr );
2323
2324     /* Count the number of commas */
2325     for( psz = dup; *psz != '\0'; ++psz )
2326     {
2327         if( *psz == ',')
2328         {
2329             ++i_records;
2330             *psz = '\0';
2331         }
2332     }
2333
2334     size_t configMax = 5*strlen(dup);
2335     unsigned char *cfg = new unsigned char[configMax];
2336     psz = dup;
2337     for( size_t i = 0; i < i_records; ++i )
2338     {
2339         cfg[configSize++] = 0x00;
2340         cfg[configSize++] = 0x00;
2341         cfg[configSize++] = 0x00;
2342         cfg[configSize++] = 0x01;
2343
2344         configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2345                                           configMax-configSize, psz );
2346         psz += strlen(psz)+1;
2347     }
2348
2349     free( dup );
2350     return cfg;
2351 }
2352
2353 static uint8_t *parseVorbisConfigStr( char const* configStr,
2354                                       unsigned int& configSize )
2355 {
2356     configSize = 0;
2357     if( configStr == NULL || *configStr == '\0' )
2358         return NULL;
2359 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1332115200 // 2012.03.20
2360     unsigned char *p_cfg = base64Decode( configStr, configSize );
2361 #else
2362     char* configStr_dup = strdup( configStr );
2363     unsigned char *p_cfg = base64Decode( configStr_dup, configSize );
2364     free( configStr_dup );
2365 #endif
2366     uint8_t *p_extra = NULL;
2367     /* skip header count, ident number and length (cf. RFC 5215) */
2368     const unsigned int headerSkip = 9;
2369     if( configSize > headerSkip && ((uint8_t*)p_cfg)[3] == 1 )
2370     {
2371         configSize -= headerSkip;
2372         p_extra = (uint8_t*)xmalloc( configSize );
2373         memcpy( p_extra, p_cfg+headerSkip, configSize );
2374     }
2375     delete[] p_cfg;
2376     return p_extra;
2377 }
2378
2379 static char *passwordLessURL( vlc_url_t *p_url )
2380 {
2381     vlc_url_t url;
2382
2383     memcpy( &url, p_url, sizeof( vlc_url_t ) );
2384
2385     url.psz_username = NULL;
2386     url.psz_password = NULL;
2387     if( url.i_port == 0 )
2388         url.i_port = 554;
2389     return vlc_uri_compose( &url );
2390 }