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