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