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