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