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