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