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