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