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