]> git.sesse.net Git - vlc/blob - modules/demux/live555.cpp
Forward port of revision 16113. Fixes a bug in live555 module, that made audio packet...
[vlc] / modules / demux / live555.cpp
1 /*****************************************************************************
2  * live555.cpp : LIVE555 Streaming Media support.
3  *****************************************************************************
4  * Copyright (C) 2003-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>                                      /* malloc(), free() */
28
29 #include <vlc/vlc.h>
30 #include <vlc/input.h>
31 #include "network.h"
32
33 #include <iostream>
34
35 #if defined( WIN32 )
36 #   include <winsock2.h>
37 #endif
38
39 #include "BasicUsageEnvironment.hh"
40 #include "GroupsockHelper.hh"
41 #include "liveMedia.hh"
42
43 extern "C" {
44 #include "../access/mms/asf.h"  /* Who said ugly ? */
45 }
46
47 #if (LIVEMEDIA_LIBRARY_VERSION_INT < 1089936000)
48 #define RECLAIM_ENV(env) delete (env)
49 #else
50 #define RECLAIM_ENV(env) (env)->reclaim()
51 #endif
52
53 using namespace std;
54
55 /*****************************************************************************
56  * Module descriptor
57  *****************************************************************************/
58 static int  Open ( vlc_object_t * );
59 static void Close( vlc_object_t * );
60
61 #define CACHING_TEXT N_("Caching value (ms)")
62 #define CACHING_LONGTEXT N_( \
63     "Allows you to modify the default caching value for RTSP streams. This " \
64     "value should be set in millisecond units." )
65
66 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
67 #define KASENNA_LONGTEXT N_( "Kasenna servers use an old and unstandard " \
68     "dialect of RTSP. When you set this parameter, VLC will try this dialect "\
69     "for communication. In this mode you cannot connect to normal RTSP servers." )
70
71 #define USER_TEXT N_("RTSP user name")
72 #define USER_LONGTEXT N_("Allows you to modify the user name that will " \
73     "be used for authenticating the connection.")
74 #define PASS_TEXT N_("RTSP password")
75 #define PASS_LONGTEXT N_("Allows you to modify the password that will be " \
76     "used for the connection.")
77
78 vlc_module_begin();
79     set_description( _("RTP/RTSP/SDP demuxer (using Live555)" ) );
80     set_capability( "demux2", 50 );
81     set_shortname( "RTP/RTSP");
82     set_callbacks( Open, Close );
83     add_shortcut( "live" );
84     add_shortcut( "livedotcom" );
85     set_category( CAT_INPUT );
86     set_subcategory( SUBCAT_INPUT_DEMUX );
87
88     add_submodule();
89         set_description( _("RTSP/RTP access and demux") );
90         add_shortcut( "rtsp" );
91         add_shortcut( "sdp" );
92         set_capability( "access_demux", 0 );
93         set_callbacks( Open, Close );
94         add_bool( "rtsp-tcp", 0, NULL,
95                   N_("Use RTP over RTSP (TCP)"),
96                   N_("Use RTP over RTSP (TCP)"), VLC_TRUE );
97         add_integer( "rtp-client-port", -1, NULL,
98                   N_("Client port"),
99                   N_("Port to use for the RTP source of the session"), VLC_TRUE );
100 #if LIVEMEDIA_LIBRARY_VERSION_INT > 1130457500
101         add_bool( "rtsp-http", 0, NULL,
102                   N_("Tunnel RTSP and RTP over HTTP"),
103                   N_("Tunnel RTSP and RTP over HTTP"), VLC_TRUE );
104         add_integer( "rtsp-http-port", 80, NULL,
105                   N_("HTTP tunnel port"),
106                   N_("Port to use for tunneling the RTSP/RTP over HTTP."),
107                   VLC_TRUE );
108 #endif
109         add_integer( "rtsp-caching", 4 * DEFAULT_PTS_DELAY / 1000, NULL,
110                   CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
111         add_bool( "rtsp-kasenna", VLC_FALSE, NULL, KASENNA_TEXT,
112                   KASENNA_LONGTEXT, VLC_TRUE );
113         add_string( "rtsp-user", NULL, NULL, USER_TEXT,
114                 USER_LONGTEXT, VLC_TRUE );
115         add_string( "rtsp-pwd", NULL, NULL, PASS_TEXT,
116                 PASS_LONGTEXT, VLC_TRUE );
117 vlc_module_end();
118
119 /* TODO:
120  *  - Improve support of PS/TS
121  *  - Support X-QT/X-QUICKTIME generic codec for audio.
122  *
123  *  - Check memory leak, delete/free -> still one when using rtsp-tcp but I'm
124  *  not sure if it comes from me.
125  *
126  */
127
128 /*****************************************************************************
129  * Local prototypes
130  *****************************************************************************/
131
132 typedef struct
133 {
134     demux_t     *p_demux;
135
136     vlc_bool_t   b_quicktime;
137     vlc_bool_t   b_muxed;
138     vlc_bool_t   b_asf;
139
140     es_format_t  fmt;
141     es_out_id_t  *p_es;
142
143     stream_t     *p_out_muxed;    /* for muxed stream */
144
145     RTPSource    *rtpSource;
146     FramedSource *readSource;
147     vlc_bool_t   b_rtcp_sync;
148
149     uint8_t      *p_buffer;
150     unsigned int  i_buffer;
151
152     char         waiting;
153
154     mtime_t      i_pts;
155
156 } live_track_t;
157
158 struct timeout_thread_t
159 {
160     VLC_COMMON_MEMBERS
161
162     int64_t      i_remain;
163     demux_sys_t  *p_sys;
164 };
165
166 struct demux_sys_t
167 {
168     char         *p_sdp;    /* XXX mallocated */
169     char         *psz_path; /* URL-encoded path */
170
171     MediaSession     *ms;
172     TaskScheduler    *scheduler;
173     UsageEnvironment *env ;
174     RTSPClient       *rtsp;
175
176     /* */
177     int              i_track;
178     live_track_t     **track;   /* XXX mallocated */
179     mtime_t          i_pcr;
180     mtime_t          i_pcr_start;
181     mtime_t          i_pcr_previous;
182     mtime_t          i_pcr_repeatdate;
183     int              i_pcr_repeats;
184
185     /* Asf */
186     asf_header_t     asfh;
187     stream_t         *p_out_asf;
188
189     /* */
190     mtime_t          i_length;
191     mtime_t          i_start;
192
193     /* timeout thread information */
194     int              i_timeout;     /* session timeout value in seconds */
195     vlc_bool_t       b_timeout_call;/* mark to send an RTSP call to prevent server timeout */
196     timeout_thread_t *p_timeout;    /* the actual thread that makes sure we don't timeout */
197
198     /* */
199     vlc_bool_t       b_multicast;   /* true if one of the tracks is multicasted */
200     vlc_bool_t       b_no_data;     /* true if we never receive any data */
201     int              i_no_data_ti;  /* consecutive number of TaskInterrupt */
202
203     char             event;
204 };
205
206 static int Demux  ( demux_t * );
207 static int Control( demux_t *, int, va_list );
208
209 static int ParseASF( demux_t * );
210 static int RollOverTcp( demux_t * );
211
212 static void StreamRead( void *, unsigned int, unsigned int,
213                         struct timeval, unsigned int );
214 static void StreamClose( void * );
215 static void TaskInterrupt( void * );
216
217 static void TimeoutPrevention( timeout_thread_t * );
218
219 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
220 static unsigned char* parseH264ConfigStr( char const* configStr,
221                                           unsigned int& configSize );
222 #endif
223
224 /*****************************************************************************
225  * DemuxOpen:
226  *****************************************************************************/
227 static int  Open ( vlc_object_t *p_this )
228 {
229     demux_t     *p_demux = (demux_t*)p_this;
230     demux_sys_t *p_sys = NULL;
231
232     MediaSubsessionIterator *iter;
233     MediaSubsession *sub;
234
235     vlc_bool_t b_rtsp_tcp;
236     uint8_t *p_peek;
237
238     char    *psz_user = NULL;
239     char    *psz_pwd  = NULL;
240
241     int     i_sdp;
242     int     i_sdp_max;
243     uint8_t *p_sdp;
244
245     if( p_demux->s )
246     {
247         /* See if it looks like a SDP
248            v, o, s fields are mandatory and in this order */
249         if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
250
251         if( memcmp( (char*)p_peek, "v=0\r\n", 5 ) &&
252             memcmp( (char*)p_peek, "v=0\n", 4 ) &&
253             ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
254         {
255             return VLC_EGENERIC;
256         }
257     }
258     else
259     {
260         var_Create( p_demux, "rtsp-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
261     }
262
263     p_demux->pf_demux  = Demux;
264     p_demux->pf_control= Control;
265     p_demux->p_sys     = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
266     if( !p_sys ) return VLC_ENOMEM;
267
268     p_sys->p_sdp = NULL;
269     p_sys->scheduler = NULL;
270     p_sys->env = NULL;
271     p_sys->ms = NULL;
272     p_sys->rtsp = NULL;
273     p_sys->i_track = 0;
274     p_sys->track   = NULL;
275     p_sys->i_pcr   = 0;
276     p_sys->i_pcr_start = 0;
277     p_sys->i_pcr_previous = 0;
278     p_sys->i_pcr_repeatdate = 0;
279     p_sys->i_pcr_repeats = 0;
280     p_sys->i_length = 0;
281     p_sys->i_start = 0;
282     p_sys->p_out_asf = NULL;
283     p_sys->b_no_data = VLC_TRUE;
284     p_sys->i_no_data_ti = 0;
285     p_sys->p_timeout = NULL;
286     p_sys->i_timeout = 0;
287     p_sys->b_timeout_call = VLC_FALSE;
288     p_sys->b_multicast = VLC_FALSE;
289     p_sys->psz_path = strdup(p_demux->psz_path);
290
291
292     if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
293     {
294         msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
295         goto error;
296     }
297     if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
298     {
299         msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
300         goto error;
301     }
302
303     if( strcasecmp( p_demux->psz_access, "sdp" ) )
304     {
305         char *p = p_sys->psz_path;
306         while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
307     }
308
309     if( p_demux->s == NULL && !strcasecmp( p_demux->psz_access, "rtsp" ) )
310     {
311         char *psz_url;
312         char *psz_options;
313 #if LIVEMEDIA_LIBRARY_VERSION_INT > 1130457500
314         int i_http_port = 0;
315
316         if( var_CreateGetBool( p_demux, "rtsp-http" ) )
317             i_http_port = var_CreateGetInteger( p_demux, "rtsp-http-port" );
318
319         if( ( p_sys->rtsp = RTSPClient::createNew(*p_sys->env, 1/*verbose*/,
320               "VLC media player", i_http_port ) ) == NULL )
321 #else
322         if( ( p_sys->rtsp = RTSPClient::createNew(*p_sys->env, 1/*verbose*/,
323               "VLC media player" ) ) == NULL )
324 #endif
325         {
326             msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
327                      p_sys->env->getResultMsg() );
328             goto error;
329         }
330         psz_url = (char*)malloc( strlen( p_sys->psz_path ) + 8 );
331         sprintf( psz_url, "rtsp://%s", p_sys->psz_path );
332
333         psz_options = p_sys->rtsp->sendOptionsCmd( psz_url );
334         if( psz_options ) delete [] psz_options;
335
336         psz_user = var_CreateGetString( p_demux, "rtsp-user" );
337         psz_pwd  = var_CreateGetString( p_demux, "rtsp-pwd" );
338
339         if ((*psz_user) && (*psz_pwd))
340             p_sdp = (uint8_t*)p_sys->rtsp->describeWithPassword( psz_url,
341                                psz_user, psz_pwd);
342         else
343             p_sdp = (uint8_t*)p_sys->rtsp->describeURL( psz_url,
344                                NULL, var_CreateGetBool( p_demux, "rtsp-kasenna" ) );
345         if( p_sdp == NULL )
346         {
347             msg_Err( p_demux, "describeURL failed (%s)",
348                      p_sys->env->getResultMsg() );
349             free( psz_url );
350             goto error;
351         }
352         free( psz_url );
353         free( psz_user );
354         free( psz_pwd );
355
356         /* malloc-ated copy */
357         p_sys->p_sdp = strdup( (char*)p_sdp );
358         delete[] p_sdp;
359         msg_Dbg( p_demux, "sdp=%s\n", p_sys->p_sdp );
360     }
361     else if( p_demux->s == NULL && !strcasecmp( p_demux->psz_access, "sdp" ) )
362     {
363         p_sys->p_sdp = strdup( p_sys->psz_path );
364     }
365     else
366     {
367         /* Gather the complete sdp file */
368         i_sdp = 0;
369         i_sdp_max = 1000;
370         p_sdp = (uint8_t*)malloc( i_sdp_max );
371         for( ;; )
372         {
373             int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
374                                       i_sdp_max - i_sdp - 1 );
375
376             if( i_read < 0 )
377             {
378                 msg_Err( p_demux, "failed to read SDP" );
379                 free( p_sys );
380                 return VLC_EGENERIC;
381             }
382
383             i_sdp += i_read;
384
385             if( i_read < i_sdp_max - i_sdp - 1 )
386             {
387                 p_sdp[i_sdp] = '\0';
388                 break;
389             }
390
391             i_sdp_max += 1000;
392             p_sdp = (uint8_t*)realloc( p_sdp, i_sdp_max );
393         }
394         p_sys->p_sdp = (char*)p_sdp;
395
396         msg_Dbg( p_demux, "sdp=%s\n", p_sys->p_sdp );
397     }
398     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
399     {
400         msg_Err( p_demux, "MediaSession::createNew failed" );
401         goto error;
402     }
403
404     b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" );
405
406     /* Initialise each media subsession */
407     iter = new MediaSubsessionIterator( *p_sys->ms );
408     while( ( sub = iter->next() ) != NULL )
409     {
410         unsigned int i_buffer = 0;
411         Boolean bInit;
412         int i_client_port;
413
414         i_client_port = var_CreateGetInteger( p_demux, "rtp-client-port" );
415         if( i_client_port != -1 )
416             sub->setClientPortNum( i_client_port );
417
418         /* Value taken from mplayer */
419         if( !strcmp( sub->mediumName(), "audio" ) )
420             i_buffer = 100000;
421         else if( !strcmp( sub->mediumName(), "video" ) )
422             i_buffer = 2000000;
423         else
424             continue;
425
426         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
427             bInit = sub->initiate( 4 ); /* Constant ? */
428         else
429             bInit = sub->initiate();
430
431         if( strcasestr( sub->codecName(), "REAL" ) )
432         {
433             msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
434             delete iter;
435             goto error; 
436         }
437
438         if( !bInit )
439         {
440             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
441                       sub->mediumName(), sub->codecName(),
442                       p_sys->env->getResultMsg() );
443         }
444         else
445         {
446             if( sub->rtpSource() )
447             {
448                 int fd = sub->rtpSource()->RTPgs()->socketNum();
449                 /* Increase the buffer size */
450                 increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
451             }
452
453             msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
454                      sub->codecName() );
455
456             /* Issue the SETUP */
457             if( p_sys->rtsp )
458             {
459                 p_sys->rtsp->setupMediaSubsession( *sub, False,
460                                                    b_rtsp_tcp ? True : False );
461             }
462             if( !p_sys->b_multicast )
463             {
464                 /* Check, because we need diff. rollover behaviour for multicast */
465                 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
466             }
467         }
468     }
469
470     if( p_sys->rtsp )
471     {
472         /* The PLAY */
473         if( !p_sys->rtsp->playMediaSession( *p_sys->ms ) )
474         {
475             msg_Err( p_demux, "PLAY failed %s", p_sys->env->getResultMsg() );
476             delete iter;
477             goto error;
478         }
479
480         /* Retrieve the timeout value and set up a timeout prevention thread */
481 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1138089600
482         p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
483 #endif
484         if( p_sys->i_timeout > 0 )
485         {
486             msg_Dbg( p_demux, "We have a timeout of %d seconds",  p_sys->i_timeout );
487             p_sys->p_timeout = (timeout_thread_t *)vlc_object_create( p_demux, sizeof(timeout_thread_t) );
488             p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
489             if( vlc_thread_create( p_sys->p_timeout, "liveMedia-timeout", TimeoutPrevention,
490                                    VLC_THREAD_PRIORITY_LOW, VLC_TRUE ) )
491             {
492                 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
493                 delete iter;
494                 vlc_object_destroy( p_sys->p_timeout );
495                 goto error;
496             }
497             msg_Dbg( p_demux, "spawned timeout thread" );
498             vlc_object_attach( p_sys->p_timeout, p_demux );
499         }
500     }
501
502     /* Create all es struct */
503     iter->reset();
504     while( ( sub = iter->next() ) != NULL )
505     {
506         live_track_t *tk;
507
508         if( sub->readSource() == NULL ) continue;
509
510         tk = (live_track_t*)malloc( sizeof( live_track_t ) );
511         tk->p_demux = p_demux;
512         tk->waiting = 0;
513         tk->i_pts   = 0;
514         tk->b_quicktime = VLC_FALSE;
515         tk->b_muxed     = VLC_FALSE;
516         tk->b_asf       = VLC_FALSE;
517         tk->b_rtcp_sync = VLC_FALSE;
518         tk->p_out_muxed = NULL;
519         tk->p_es        = NULL;
520         tk->i_buffer    = 65536;
521         tk->p_buffer    = (uint8_t *)malloc( 65536 );
522
523         /* Value taken from mplayer */
524         if( !strcmp( sub->mediumName(), "audio" ) )
525         {
526             es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
527             tk->fmt.audio.i_channels = sub->numChannels();
528             tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
529
530             if( !strcmp( sub->codecName(), "MPA" ) ||
531                 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
532                 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
533             {
534                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
535                 tk->fmt.audio.i_rate = 0;
536             }
537             else if( !strcmp( sub->codecName(), "AC3" ) )
538             {
539                 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
540                 tk->fmt.audio.i_rate = 0;
541             }
542             else if( !strcmp( sub->codecName(), "L16" ) )
543             {
544                 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
545                 tk->fmt.audio.i_bitspersample = 16;
546             }
547             else if( !strcmp( sub->codecName(), "L8" ) )
548             {
549                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
550                 tk->fmt.audio.i_bitspersample = 8;
551             }
552             else if( !strcmp( sub->codecName(), "PCMU" ) )
553             {
554                 tk->fmt.i_codec = VLC_FOURCC( 'u', 'l', 'a', 'w' );
555             }
556             else if( !strcmp( sub->codecName(), "PCMA" ) )
557             {
558                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'l', 'a', 'w' );
559             }
560             else if( !strncmp( sub->codecName(), "G726", 4 ) )
561             {
562                 tk->fmt.i_codec = VLC_FOURCC( 'g', '7', '2', '6' ); 
563                 tk->fmt.audio.i_rate = 8000;
564                 tk->fmt.audio.i_channels = 1;
565                 if( !strcmp( sub->codecName()+5, "40" ) )
566                     tk->fmt.i_bitrate = 40000;
567                 else if( !strcmp( sub->codecName()+5, "32" ) )
568                     tk->fmt.i_bitrate = 32000;
569                 else if( !strcmp( sub->codecName()+5, "24" ) )
570                     tk->fmt.i_bitrate = 24000;
571                 else if( !strcmp( sub->codecName()+5, "16" ) )
572                     tk->fmt.i_bitrate = 16000;
573             }
574             else if( !strcmp( sub->codecName(), "AMR" ) )
575             {
576                 tk->fmt.i_codec = VLC_FOURCC( 's', 'a', 'm', 'r' );
577             }
578             else if( !strcmp( sub->codecName(), "AMR-WB" ) )
579             {
580                 tk->fmt.i_codec = VLC_FOURCC( 's', 'a', 'w', 'b' );
581             }
582             else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
583             {
584                 unsigned int i_extra;
585                 uint8_t      *p_extra;
586
587                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
588
589                 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
590                                                          i_extra ) ) )
591                 {
592                     tk->fmt.i_extra = i_extra;
593                     tk->fmt.p_extra = malloc( i_extra );
594                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
595                     delete[] p_extra;
596                 }
597
598 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1141257600
599                 /* Because the "faad" decoder does not handle the LATM data length field
600                    at the start of each returned LATM frame, tell the RTP source to omit it. */
601                 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
602 #endif
603             }
604             else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
605             {
606                 unsigned int i_extra;
607                 uint8_t      *p_extra;
608
609                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
610
611                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
612                                                        i_extra ) ) )
613                 {
614                     tk->fmt.i_extra = i_extra;
615                     tk->fmt.p_extra = malloc( i_extra );
616                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
617                     delete[] p_extra;
618                 }
619             }
620             else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
621             {
622                 tk->b_asf = VLC_TRUE;
623                 if( p_sys->p_out_asf == NULL )
624                     p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
625                                                         p_demux->out );
626             }
627         }
628         else if( !strcmp( sub->mediumName(), "video" ) )
629         {
630             es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
631             if( !strcmp( sub->codecName(), "MPV" ) )
632             {
633                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
634             }
635             else if( !strcmp( sub->codecName(), "H263" ) ||
636                      !strcmp( sub->codecName(), "H263-1998" ) ||
637                      !strcmp( sub->codecName(), "H263-2000" ) )
638             {
639                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '3' );
640             }
641             else if( !strcmp( sub->codecName(), "H261" ) )
642             {
643                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '1' );
644             }
645             else if( !strcmp( sub->codecName(), "H264" ) )
646             {
647 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
648                 unsigned int i_extra = 0;
649                 uint8_t      *p_extra = NULL;
650 #endif
651                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '4' );
652                 tk->fmt.b_packetized = VLC_FALSE;
653
654                 /* XXX not the right minimal version I fear */
655 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
656                 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
657                                                 i_extra ) ) )
658                 {
659                     tk->fmt.i_extra = i_extra;
660                     tk->fmt.p_extra = malloc( i_extra );
661                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
662
663                     delete[] p_extra;
664                 }
665 #endif
666             }
667             else if( !strcmp( sub->codecName(), "JPEG" ) )
668             {
669                 tk->fmt.i_codec = VLC_FOURCC( 'M', 'J', 'P', 'G' );
670             }
671             else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
672             {
673                 unsigned int i_extra;
674                 uint8_t      *p_extra;
675
676                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
677
678                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
679                                                        i_extra ) ) )
680                 {
681                     tk->fmt.i_extra = i_extra;
682                     tk->fmt.p_extra = malloc( i_extra );
683                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
684                     delete[] p_extra;
685                 }
686             }
687             else if( !strcmp( sub->codecName(), "X-QT" ) ||
688                      !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
689                      !strcmp( sub->codecName(), "X-QDM" ) ||
690                      !strcmp( sub->codecName(), "X-SV3V-ES" )  ||
691                      !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
692             {
693                 tk->b_quicktime = VLC_TRUE;
694             }
695             else if( !strcmp( sub->codecName(), "MP2T" ) )
696             {
697                 tk->b_muxed = VLC_TRUE;
698                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
699             }
700             else if( !strcmp( sub->codecName(), "MP2P" ) ||
701                      !strcmp( sub->codecName(), "MP1S" ) )
702             {
703                 tk->b_muxed = VLC_TRUE;
704                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
705                                                    p_demux->out );
706             }
707             else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
708             {
709                 tk->b_asf = VLC_TRUE;
710                 if( p_sys->p_out_asf == NULL )
711                     p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
712                                                         p_demux->out );;
713             }
714         }
715
716         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
717
718         if( sub->rtcpInstance() != NULL )
719         {
720             sub->rtcpInstance()->setByeHandler( StreamClose, tk );
721         }
722
723         if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
724         {
725             tk->readSource = sub->readSource();
726             tk->rtpSource  = sub->rtpSource();
727
728             /* Append */
729             p_sys->track = (live_track_t**)realloc( p_sys->track, sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
730             p_sys->track[p_sys->i_track++] = tk;
731         }
732         else
733         {
734             free( tk );
735         }
736     }
737
738     delete iter;
739
740     if( p_sys->p_out_asf && ParseASF( p_demux ) )
741     {
742         msg_Err( p_demux, "cannot find a usable asf header" );
743         /* TODO Clean tracks */
744         goto error;
745     }
746
747     p_sys->i_length = (mtime_t)(p_sys->ms->playEndTime() * 1000000.0);
748     if( p_sys->i_length < 0 )
749     {
750         p_sys->i_length = 0;
751     }
752     else if( p_sys->i_length > 0 )
753     {
754         /* FIXME */
755         /* p_input->stream.p_selected_area->i_size = 1000;*/ /* needed for now */
756     }
757
758     if( p_sys->i_track <= 0 )
759     {
760         msg_Err( p_demux, "no codec supported, aborting" );
761         goto error;
762     }
763
764     return VLC_SUCCESS;
765
766 error:
767     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
768     if( p_sys->ms ) Medium::close( p_sys->ms );
769     if( p_sys->rtsp ) Medium::close( p_sys->rtsp );
770     if( p_sys->env ) RECLAIM_ENV(p_sys->env);
771     if( p_sys->p_timeout )
772     {
773         p_sys->p_timeout->b_die = VLC_TRUE;
774         vlc_thread_join( p_sys->p_timeout );
775         vlc_object_detach( p_sys->p_timeout );
776         vlc_object_destroy( p_sys->p_timeout );
777     }
778     if( p_sys->scheduler ) delete p_sys->scheduler;
779     if( p_sys->p_sdp ) free( p_sys->p_sdp );
780     if( p_sys->psz_path ) free( p_sys->psz_path );
781
782     free( p_sys );
783     return VLC_EGENERIC;
784 }
785
786 /*****************************************************************************
787  * DemuxClose:
788  *****************************************************************************/
789 static void Close( vlc_object_t *p_this )
790 {
791     demux_t *p_demux = (demux_t*)p_this;
792     demux_sys_t *p_sys = p_demux->p_sys;
793     int i;
794
795     for( i = 0; i < p_sys->i_track; i++ )
796     {
797         live_track_t *tk = p_sys->track[i];
798
799         if( tk->b_muxed ) stream_DemuxDelete( tk->p_out_muxed );
800         free( tk->p_buffer );
801         free( tk );
802     }
803
804     if( p_sys->i_track ) free( p_sys->track );
805     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
806
807     if( p_sys->rtsp && p_sys->ms )
808     {
809         /* TEARDOWN */
810         p_sys->rtsp->teardownMediaSession( *p_sys->ms );
811     }
812
813     Medium::close( p_sys->ms );
814
815     if( p_sys->p_timeout )
816     {
817         p_sys->p_timeout->b_die = VLC_TRUE;
818         vlc_thread_join( p_sys->p_timeout );
819         vlc_object_detach( p_sys->p_timeout );
820         vlc_object_destroy( p_sys->p_timeout );
821     }
822
823     if( p_sys->rtsp ) Medium::close( p_sys->rtsp );
824     if( p_sys->env ) RECLAIM_ENV(p_sys->env);
825     if( p_sys->scheduler ) delete p_sys->scheduler;
826     if( p_sys->p_sdp ) free( p_sys->p_sdp );
827     if( p_sys->psz_path ) free( p_sys->psz_path );
828     free( p_sys );
829 }
830
831 /*****************************************************************************
832  * Demux:
833  *****************************************************************************/
834 static int Demux( demux_t *p_demux )
835 {
836     demux_sys_t    *p_sys = p_demux->p_sys;
837     TaskToken      task;
838
839     vlc_bool_t      b_send_pcr = VLC_TRUE;
840     mtime_t         i_pcr = 0;
841     int             i;
842
843     /* Check if we need to send the server a Keep-A-Live signal */
844     if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
845     {
846 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1138089600
847         char *psz_bye = NULL;
848         p_sys->rtsp->getMediaSessionParameter( *p_sys->ms, NULL, psz_bye );
849 #endif
850         p_sys->b_timeout_call = VLC_FALSE;
851     }
852
853     for( i = 0; i < p_sys->i_track; i++ )
854     {
855         live_track_t *tk = p_sys->track[i];
856
857         if( tk->b_asf || tk->b_muxed )
858             b_send_pcr = VLC_FALSE;
859
860         if( i_pcr == 0 )
861         {
862             i_pcr = tk->i_pts;
863         }
864         else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
865         {
866             i_pcr = tk->i_pts ;
867         }
868     }
869     if( i_pcr != p_sys->i_pcr && i_pcr > 0 )
870     {
871         p_sys->i_pcr = i_pcr;
872
873         if( b_send_pcr )
874             es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pcr );
875         if( p_sys->i_pcr_start <= 0 || p_sys->i_pcr_start > i_pcr ||
876             ( p_sys->i_length > 0 && i_pcr - p_sys->i_pcr_start > p_sys->i_length ) )
877         {
878             p_sys->i_pcr_start = i_pcr;
879         }
880     }
881
882     /* When a On Demand QT stream ends, the last frame keeps going with the same PCR/PTS value */
883     /* This tests for that, so we can later decide to end this session */
884     if( i_pcr > 0 && p_sys->i_pcr == p_sys->i_pcr_previous )
885     {
886         if( p_sys->i_pcr_repeats == 0 )
887             p_sys->i_pcr_repeatdate = mdate();
888         p_sys->i_pcr_repeats++;
889     }
890     else
891     {
892         p_sys->i_pcr_previous = p_sys->i_pcr;
893         p_sys->i_pcr_repeatdate = 0;
894         p_sys->i_pcr_repeats = 0;
895     }
896
897     if( p_sys->i_pcr_repeats > 5 && mdate() > p_sys->i_pcr_repeatdate + 1000000 )
898     {
899         /* We need at least 5 repeats over at least a second of time before we EOF */
900         msg_Dbg( p_demux, "suspect EOF due to end of VoD session" );
901         return 0;
902     }
903
904     /* First warm we want to read data */
905     p_sys->event = 0;
906     for( i = 0; i < p_sys->i_track; i++ )
907     {
908         live_track_t *tk = p_sys->track[i];
909
910         if( tk->waiting == 0 )
911         {
912             tk->waiting = 1;
913             tk->readSource->getNextFrame( tk->p_buffer, tk->i_buffer,
914                                           StreamRead, tk, StreamClose, tk );
915         }
916     }
917     /* Create a task that will be called if we wait more than 300ms */
918     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
919
920     /* Do the read */
921     p_sys->scheduler->doEventLoop( &p_sys->event );
922
923     /* remove the task */
924     p_sys->scheduler->unscheduleDelayedTask( task );
925
926     /* Check for gap in pts value */
927     for( i = 0; i < p_sys->i_track; i++ )
928     {
929         live_track_t *tk = p_sys->track[i];
930
931         if( !tk->b_muxed && !tk->b_rtcp_sync &&
932             tk->rtpSource && tk->rtpSource->hasBeenSynchronizedUsingRTCP() )
933         {
934             msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
935
936             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
937             tk->b_rtcp_sync = VLC_TRUE;
938
939             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
940             tk->i_pts = 0;
941             p_sys->i_pcr_start = 0;
942             p_sys->i_pcr = 0;
943             i_pcr = 0;
944         }
945     }
946
947     if( p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 120 )
948     {
949         /* FIXME Make this configurable
950         msg_Err( p_demux, "no multicast data received in 36s, aborting" );
951         return 0;
952         */
953     }
954     else if( !p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 34 )
955     {
956         vlc_bool_t b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" );
957
958         if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
959         {
960             msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
961             if( RollOverTcp( p_demux ) )
962             {
963                 msg_Err( p_demux, "TCP rollover failed, aborting" );
964                 return 0;
965             }
966             var_SetBool( p_demux, "rtsp-tcp", VLC_TRUE );
967         }
968         else if( p_sys->i_no_data_ti > 34 )
969         {
970             msg_Err( p_demux, "no data received in 10s, aborting" );
971             return 0;
972         }
973     }
974     else if( !p_sys->b_multicast && p_sys->b_no_data&& p_sys->i_no_data_ti > 34 )
975     {
976         /* EOF ? */
977         msg_Warn( p_demux, "no data received in 10s, eof ?" );
978         return 0;
979     }
980
981     return p_demux->b_error ? 0 : 1;
982 }
983
984 /*****************************************************************************
985  * Control:
986  *****************************************************************************/
987 static int Control( demux_t *p_demux, int i_query, va_list args )
988 {
989     demux_sys_t *p_sys = p_demux->p_sys;
990     int64_t *pi64;
991     double  *pf, f;
992     vlc_bool_t *pb, b_bool;
993
994     switch( i_query )
995     {
996         case DEMUX_GET_TIME:
997             pi64 = (int64_t*)va_arg( args, int64_t * );
998             *pi64 = p_sys->i_pcr - p_sys->i_pcr_start + p_sys->i_start;
999             return VLC_SUCCESS;
1000
1001         case DEMUX_GET_LENGTH:
1002             pi64 = (int64_t*)va_arg( args, int64_t * );
1003             *pi64 = p_sys->i_length;
1004             return VLC_SUCCESS;
1005
1006         case DEMUX_GET_POSITION:
1007             pf = (double*)va_arg( args, double* );
1008             if( p_sys->i_length > 0 )
1009             {
1010                 *pf = (double)( p_sys->i_pcr - p_sys->i_pcr_start +
1011                                 p_sys->i_start ) / (double)(p_sys->i_length);
1012             }
1013             else
1014             {
1015                 *pf = 0;
1016             }
1017             return VLC_SUCCESS;
1018
1019         case DEMUX_SET_POSITION:
1020         {
1021             float time;
1022
1023             f = (double)va_arg( args, double );
1024             time = f * (double)p_sys->i_length / 1000000.0;   /* in second */
1025
1026             if( p_sys->rtsp && p_sys->i_length > 0 )
1027             {
1028                 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, time ) )
1029                 {
1030                     msg_Err( p_demux, "PLAY failed %s",
1031                         p_sys->env->getResultMsg() );
1032                     return VLC_EGENERIC;
1033                 }
1034                 p_sys->i_start = (mtime_t)(f * (double)p_sys->i_length);
1035                 p_sys->i_pcr_start = 0;
1036                 p_sys->i_pcr       = 0;
1037
1038                 return VLC_SUCCESS;
1039             }
1040             return VLC_SUCCESS;
1041         }
1042
1043         /* Special for access_demux */
1044         case DEMUX_CAN_PAUSE:
1045             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1046             if( p_sys->rtsp && p_sys->i_length )
1047                 /* Not always true, but will be handled in SET_PAUSE_STATE */
1048                 *pb = VLC_TRUE;
1049             else
1050                 *pb = VLC_FALSE;
1051             return VLC_SUCCESS;
1052
1053         case DEMUX_CAN_CONTROL_PACE:
1054             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1055
1056 #if 0       /* Disable for now until we have a clock synchro algo
1057              * which works with something else than MPEG over UDP */
1058             *pb = VLC_FALSE;
1059 #else
1060             *pb = VLC_TRUE;
1061 #endif
1062             return VLC_SUCCESS;
1063
1064         case DEMUX_SET_PAUSE_STATE:
1065             double d_npt;
1066
1067             d_npt = ( (double)( p_sys->i_pcr - p_sys->i_pcr_start +
1068                                 p_sys->i_start ) ) / 1000000.00;
1069
1070             b_bool = (vlc_bool_t)va_arg( args, vlc_bool_t );
1071             if( p_sys->rtsp == NULL )
1072                 return VLC_EGENERIC;
1073
1074             if( ( b_bool && !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) ) ||
1075                     ( !b_bool && !p_sys->rtsp->playMediaSession( *p_sys->ms,
1076                       d_npt > 0 ? d_npt : -1 ) ) )
1077             {
1078                     msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1079                     return VLC_EGENERIC;
1080             }
1081 #if 0
1082             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
1083             for( i = 0; i < p_sys->i_track; i++ )
1084             {
1085                 p_sys->track[i]->i_pts = 0;
1086             }
1087             p_sys->i_pcr_start = 0; /* FIXME Wrong */
1088             p_sys->i_pcr = 0;
1089 #endif
1090             return VLC_SUCCESS;
1091
1092         case DEMUX_GET_TITLE_INFO:
1093         case DEMUX_SET_TITLE:
1094         case DEMUX_SET_SEEKPOINT:
1095             return VLC_EGENERIC;
1096
1097         case DEMUX_GET_PTS_DELAY:
1098             pi64 = (int64_t*)va_arg( args, int64_t * );
1099             *pi64 = (int64_t)var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1100             return VLC_SUCCESS;
1101
1102         default:
1103             return VLC_EGENERIC;
1104     }
1105 }
1106
1107 /*****************************************************************************
1108  * RollOverTcp: reopen the rtsp into TCP mode
1109  * XXX: ugly, a lot of code are duplicated from Open()
1110  *****************************************************************************/
1111 static int RollOverTcp( demux_t *p_demux )
1112 {
1113     demux_sys_t *p_sys = p_demux->p_sys;
1114     MediaSubsessionIterator *iter;
1115     MediaSubsession *sub;
1116     char *psz_url;
1117     char *psz_options;
1118     char *psz_user;
1119     char *psz_pwd;
1120     uint8_t *p_sdp;
1121     int i_tk;
1122
1123     /* We close the old RTSP session */
1124     p_sys->rtsp->teardownMediaSession( *p_sys->ms );
1125
1126     Medium::close( p_sys->ms );
1127     Medium::close( p_sys->rtsp );
1128
1129     p_sys->ms = NULL;
1130     p_sys->rtsp = NULL;
1131
1132     /* Reopen rtsp client */
1133     if( ( p_sys->rtsp = RTSPClient::createNew(*p_sys->env, 1/*verbose*/,
1134           "VLC media player" ) ) == NULL )
1135     {
1136         msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
1137                  p_sys->env->getResultMsg() );
1138         return VLC_EGENERIC;
1139     }
1140
1141     asprintf( &psz_url, "rtsp://%s", p_sys->psz_path );
1142
1143     if( ( psz_options = p_sys->rtsp->sendOptionsCmd( psz_url ) ) )
1144         delete [] psz_options;
1145
1146     psz_user = var_CreateGetString( p_demux, "rtsp-user" );
1147     psz_pwd  = var_CreateGetString( p_demux, "rtsp-pwd" );
1148
1149     if ((*psz_user) && (*psz_pwd))
1150         p_sdp = (uint8_t*)p_sys->rtsp->describeWithPassword( psz_url,
1151                             psz_user, psz_pwd);
1152     else
1153         p_sdp = (uint8_t*)p_sys->rtsp->describeURL( psz_url,
1154                             NULL, var_CreateGetBool( p_demux, "rtsp-kasenna" ) );
1155
1156     free( psz_url );
1157     free( psz_user );
1158     free( psz_pwd );
1159
1160     if( p_sdp == NULL )
1161     {
1162         msg_Err( p_demux, "describeURL failed (%s)",
1163                  p_sys->env->getResultMsg() );
1164         return VLC_EGENERIC;
1165     }
1166
1167     /* malloc-ated copy */
1168     p_sys->p_sdp = strdup( (char*)p_sdp );
1169     delete[] p_sdp;
1170
1171     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
1172     {
1173         msg_Err( p_demux, "MediaSession::createNew failed" );
1174         return VLC_EGENERIC;
1175     }
1176
1177     /* Initialise each media subsession */
1178     iter = new MediaSubsessionIterator( *p_sys->ms );
1179     while( ( sub = iter->next() ) != NULL )
1180     {
1181         Boolean bInit;
1182
1183         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1184             bInit = sub->initiate( 4 ); /* Constant ? */
1185         else
1186             bInit = sub->initiate();
1187
1188         if( !bInit )
1189         {
1190             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
1191                       sub->mediumName(), sub->codecName(),
1192                       p_sys->env->getResultMsg() );
1193             continue;
1194         }
1195         msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
1196                  sub->codecName() );
1197
1198         /* Issue the SETUP */
1199         p_sys->rtsp->setupMediaSubsession( *sub, False, True /* tcp */ );
1200     }
1201
1202     /* The PLAY */
1203     if( !p_sys->rtsp->playMediaSession( *p_sys->ms ) )
1204     {
1205         msg_Err( p_demux, "PLAY failed %s", p_sys->env->getResultMsg() );
1206         return VLC_EGENERIC;
1207     }
1208
1209     /* Update all tracks */
1210     iter->reset();
1211     i_tk = 0;
1212     while( ( sub = iter->next() ) != NULL )
1213     {
1214         live_track_t *tk;
1215
1216         if( sub->readSource() == NULL )
1217             continue;
1218         if( i_tk >= p_sys->i_track )
1219         {
1220             msg_Err( p_demux, "WTF !" );
1221             break;
1222         }
1223
1224         tk = p_sys->track[i_tk];
1225
1226         /* Reset state */
1227         tk->waiting = 0;
1228         tk->i_pts   = 0;
1229         tk->b_rtcp_sync = VLC_FALSE;
1230
1231         if( sub->rtcpInstance() != NULL )
1232             sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1233
1234         tk->readSource = sub->readSource();
1235         tk->rtpSource  = sub->rtpSource();
1236
1237         i_tk++;
1238     }
1239
1240     delete iter;
1241
1242     return VLC_SUCCESS;
1243 }
1244
1245
1246 /*****************************************************************************
1247  *
1248  *****************************************************************************/
1249 static void StreamRead( void *p_private, unsigned int i_size,
1250                         unsigned int i_truncated_bytes, struct timeval pts,
1251                         unsigned int duration )
1252 {
1253     live_track_t   *tk = (live_track_t*)p_private;
1254     demux_t        *p_demux = tk->p_demux;
1255     demux_sys_t    *p_sys = p_demux->p_sys;
1256     block_t        *p_block;
1257
1258     mtime_t i_pts = (uint64_t)pts.tv_sec * UI64C(1000000) +
1259         (uint64_t)pts.tv_usec;
1260
1261     /* XXX Beurk beurk beurk Avoid having negative value XXX */
1262     i_pts &= UI64C(0x00ffffffffffffff);
1263
1264     if( tk->b_quicktime && tk->p_es == NULL )
1265     {
1266         QuickTimeGenericRTPSource *qtRTPSource =
1267             (QuickTimeGenericRTPSource*)tk->rtpSource;
1268         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1269         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1270
1271         if( qtState.sdAtomSize < 16 + 32 )
1272         {
1273             /* invalid */
1274             p_sys->event = 0xff;
1275             tk->waiting = 0;
1276             return;
1277         }
1278         tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1279         tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
1280         tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1281
1282         tk->fmt.i_extra        = qtState.sdAtomSize - 16;
1283         tk->fmt.p_extra        = malloc( tk->fmt.i_extra );
1284         memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1285
1286         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1287     }
1288
1289 #if 0
1290     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1291              i_size,
1292              pts.tv_sec * 1000000LL + pts.tv_usec );
1293 #endif
1294
1295     /* grow buffer if it looks like buffer is too small, but don't eat
1296      * up all the memory on strange streams */
1297     if( i_truncated_bytes > 0 && tk->i_buffer < 2000000 )
1298     {
1299         void *p_tmp;
1300         msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1301         msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1302         tk->i_buffer *= 2;
1303         p_tmp = realloc( tk->p_buffer, tk->i_buffer );
1304         if (p_tmp == NULL)
1305         {
1306             msg_Warn( p_demux, "realloc failed" );
1307         }
1308         else
1309         {
1310             tk->p_buffer = (uint8_t*)p_tmp;
1311         }
1312     }
1313     if( i_size > tk->i_buffer )
1314     {
1315         msg_Warn( p_demux, "buffer overflow" );
1316     }
1317     /* FIXME could i_size be > buffer size ? */
1318     if( tk->fmt.i_codec == VLC_FOURCC('s','a','m','r') ||
1319         tk->fmt.i_codec == VLC_FOURCC('s','a','w','b') )
1320     {
1321         AMRAudioSource *amrSource = (AMRAudioSource*)tk->readSource;
1322
1323         p_block = block_New( p_demux, i_size + 1 );
1324         p_block->p_buffer[0] = amrSource->lastFrameHeader();
1325         memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1326     }
1327     else if( tk->fmt.i_codec == VLC_FOURCC('H','2','6','1') )
1328     {
1329 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1081468800
1330         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->rtpSource;
1331         uint32_t header = h261Source->lastSpecialHeader();
1332 #else
1333         uint32_t header = 0;
1334         msg_Warn( p_demux, "need livemedia library >= \"2004.04.09\"" );
1335 #endif
1336         p_block = block_New( p_demux, i_size + 4 );
1337         memcpy( p_block->p_buffer, &header, 4 );
1338         memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1339
1340         if( tk->rtpSource->curPacketMarkerBit() )
1341             p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1342     }
1343     else if( tk->fmt.i_codec == VLC_FOURCC('H','2','6','4') )
1344     {
1345         if( (tk->p_buffer[0] & 0x1f) >= 24 )
1346             msg_Warn( p_demux, "unsupported NAL type for H264" );
1347
1348         /* Normal NAL type */
1349         p_block = block_New( p_demux, i_size + 4 );
1350         p_block->p_buffer[0] = 0x00;
1351         p_block->p_buffer[1] = 0x00;
1352         p_block->p_buffer[2] = 0x00;
1353         p_block->p_buffer[3] = 0x01;
1354         memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1355     }
1356     else if( tk->b_asf )
1357     {
1358         int i_copy = __MIN( p_sys->asfh.i_min_data_packet_size, (int)i_size );
1359         p_block = block_New( p_demux, p_sys->asfh.i_min_data_packet_size );
1360
1361         memcpy( p_block->p_buffer, tk->p_buffer, i_copy );
1362     }
1363     else
1364     {
1365         p_block = block_New( p_demux, i_size );
1366         memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1367     }
1368
1369     //p_block->i_rate = p_input->stream.control.i_rate;
1370
1371     if( i_pts != tk->i_pts && !tk->b_muxed )
1372     {
1373         p_block->i_dts = ( tk->fmt.i_cat == VIDEO_ES ) ? 0 : i_pts;
1374         p_block->i_pts = i_pts;
1375     }
1376
1377     if( tk->b_muxed )
1378     {
1379         stream_DemuxSend( tk->p_out_muxed, p_block );
1380     }
1381     else if( tk->b_asf )
1382     {
1383         stream_DemuxSend( p_sys->p_out_asf, p_block );
1384     }
1385     else
1386     {
1387         es_out_Send( p_demux->out, tk->p_es, p_block );
1388     }
1389
1390     /* warm that's ok */
1391     p_sys->event = 0xff;
1392
1393     /* we have read data */
1394     tk->waiting = 0;
1395     p_demux->p_sys->b_no_data = VLC_FALSE;
1396     p_demux->p_sys->i_no_data_ti = 0;
1397
1398     if( i_pts > 0 && !tk->b_muxed )
1399     {
1400         tk->i_pts = i_pts;
1401     }
1402 }
1403
1404 /*****************************************************************************
1405  *
1406  *****************************************************************************/
1407 static void StreamClose( void *p_private )
1408 {
1409     live_track_t   *tk = (live_track_t*)p_private;
1410     demux_t        *p_demux = tk->p_demux;
1411     demux_sys_t    *p_sys = p_demux->p_sys;
1412
1413     msg_Dbg( p_demux, "StreamClose" );
1414
1415     p_sys->event = 0xff;
1416     p_demux->b_error = VLC_TRUE;
1417 }
1418
1419
1420 /*****************************************************************************
1421  *
1422  *****************************************************************************/
1423 static void TaskInterrupt( void *p_private )
1424 {
1425     demux_t *p_demux = (demux_t*)p_private;
1426
1427     p_demux->p_sys->i_no_data_ti++;
1428
1429     /* Avoid lock */
1430     p_demux->p_sys->event = 0xff;
1431 }
1432
1433 /*****************************************************************************
1434  *  
1435  *****************************************************************************/
1436 static void TimeoutPrevention( timeout_thread_t *p_timeout )
1437 {
1438     p_timeout->b_die = VLC_FALSE;
1439     p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1440     p_timeout->i_remain *= 1000000;
1441
1442     vlc_thread_ready( p_timeout );
1443     
1444     /* Avoid lock */
1445     while( !p_timeout->b_die )
1446     {
1447         if( p_timeout->i_remain <= 0 )
1448         {
1449             p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1450             p_timeout->i_remain *= 1000000;
1451             p_timeout->p_sys->b_timeout_call = VLC_TRUE;
1452             msg_Dbg( p_timeout, "reset the timeout timer" );
1453         }
1454         p_timeout->i_remain -= 200000;
1455         msleep( 200000 ); /* 200 ms */
1456     }
1457 }
1458
1459 /*****************************************************************************
1460  *
1461  *****************************************************************************/
1462 static int b64_decode( char *dest, char *src );
1463
1464 static int ParseASF( demux_t *p_demux )
1465 {
1466     demux_sys_t    *p_sys = p_demux->p_sys;
1467
1468     const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1469     char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1470     char *psz_end;
1471     block_t *p_header;
1472
1473     /* Parse the asf header */
1474     if( psz_asf == NULL )
1475         return VLC_EGENERIC;
1476
1477     psz_asf += strlen( psz_marker );
1478     psz_asf = strdup( psz_asf );    /* Duplicate it */
1479     psz_end = strchr( psz_asf, '\n' );
1480
1481     while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1482         *psz_end-- = '\0';
1483
1484     if( psz_asf >= psz_end )
1485     {
1486         free( psz_asf );
1487         return VLC_EGENERIC;
1488     }
1489
1490     /* Always smaller */
1491     p_header = block_New( p_demux, psz_end - psz_asf );
1492     p_header->i_buffer = b64_decode( (char*)p_header->p_buffer, psz_asf );
1493     //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
1494     if( p_header->i_buffer <= 0 )
1495     {
1496         free( psz_asf );
1497         return VLC_EGENERIC;
1498     }
1499
1500     /* Parse it to get packet size */
1501     E_(asf_HeaderParse)( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
1502
1503     /* Send it to demuxer */
1504     stream_DemuxSend( p_sys->p_out_asf, p_header );
1505
1506     free( psz_asf );
1507     return VLC_SUCCESS;
1508 }
1509
1510 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
1511 static unsigned char* parseH264ConfigStr( char const* configStr,
1512                                           unsigned int& configSize )
1513 {
1514     char *dup, *psz;
1515
1516     if( configSize )
1517     configSize = 0;
1518
1519     if( configStr == NULL || *configStr == '\0' )
1520         return NULL;
1521
1522     psz = dup = strdup( configStr );
1523
1524     unsigned char *cfg = new unsigned char[5 * strlen(psz)];
1525     for( ;; )
1526     {
1527         char *p = strchr( psz, ',' );
1528         if( p )
1529             *p++ = '\0';
1530
1531         cfg[configSize++] = 0x00;
1532         cfg[configSize++] = 0x00;
1533         cfg[configSize++] = 0x00;
1534         cfg[configSize++] = 0x01;
1535         configSize += b64_decode( (char*)&cfg[configSize], psz );
1536
1537         if( p == NULL )
1538             break;
1539         psz = p;
1540     }
1541
1542     if( dup ) free( dup );
1543     return cfg;
1544 }
1545 #endif
1546
1547 /*char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";*/
1548 static int b64_decode( char *dest, char *src )
1549 {
1550     const char *dest_start = dest;
1551     int  i_level;
1552     int  last = 0;
1553     int  b64[256] = {
1554         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
1555         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
1556         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
1557         52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
1558         -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
1559         15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
1560         -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
1561         41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
1562         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
1563         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
1564         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
1565         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
1566         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
1567         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
1568         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
1569         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
1570         };
1571
1572     for( i_level = 0; *src != '\0'; src++ )
1573     {
1574         int  c;
1575
1576         c = b64[(unsigned int)*src];
1577         if( c == -1 )
1578         {
1579             continue;
1580         }
1581
1582         switch( i_level )
1583         {
1584             case 0:
1585                 i_level++;
1586                 break;
1587             case 1:
1588                 *dest++ = ( last << 2 ) | ( ( c >> 4)&0x03 );
1589                 i_level++;
1590                 break;
1591             case 2:
1592                 *dest++ = ( ( last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
1593                 i_level++;
1594                 break;
1595             case 3:
1596                 *dest++ = ( ( last &0x03 ) << 6 ) | c;
1597                 i_level = 0;
1598         }
1599         last = c;
1600     }
1601
1602     *dest = '\0';
1603
1604     return dest - dest_start;
1605 }