]> git.sesse.net Git - vlc/blob - modules/demux/live555.cpp
s/livedotcom/live555/
[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         if( tk->fmt.i_codec != VLC_FOURCC( 'u', 'n', 'd', 'f' ) )
717         {
718             tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
719         }
720
721         if( sub->rtcpInstance() != NULL )
722         {
723             sub->rtcpInstance()->setByeHandler( StreamClose, tk );
724         }
725
726         if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
727         {
728             tk->readSource = sub->readSource();
729             tk->rtpSource  = sub->rtpSource();
730
731             /* Append */
732             p_sys->track = (live_track_t**)realloc( p_sys->track, sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
733             p_sys->track[p_sys->i_track++] = tk;
734         }
735         else
736         {
737             free( tk );
738         }
739     }
740
741     delete iter;
742
743     if( p_sys->p_out_asf && ParseASF( p_demux ) )
744     {
745         msg_Err( p_demux, "cannot find a usable asf header" );
746         /* TODO Clean tracks */
747         goto error;
748     }
749
750     p_sys->i_length = (mtime_t)(p_sys->ms->playEndTime() * 1000000.0);
751     if( p_sys->i_length < 0 )
752     {
753         p_sys->i_length = 0;
754     }
755     else if( p_sys->i_length > 0 )
756     {
757         /* FIXME */
758         /* p_input->stream.p_selected_area->i_size = 1000;*/ /* needed for now */
759     }
760
761     if( p_sys->i_track <= 0 )
762     {
763         msg_Err( p_demux, "no codec supported, aborting" );
764         goto error;
765     }
766
767     return VLC_SUCCESS;
768
769 error:
770     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
771     if( p_sys->ms ) Medium::close( p_sys->ms );
772     if( p_sys->rtsp ) Medium::close( p_sys->rtsp );
773     if( p_sys->env ) RECLAIM_ENV(p_sys->env);
774     if( p_sys->p_timeout )
775     {
776         p_sys->p_timeout->b_die = VLC_TRUE;
777         vlc_thread_join( p_sys->p_timeout );
778         vlc_object_detach( p_sys->p_timeout );
779         vlc_object_destroy( p_sys->p_timeout );
780     }
781     if( p_sys->scheduler ) delete p_sys->scheduler;
782     if( p_sys->p_sdp ) free( p_sys->p_sdp );
783     if( p_sys->psz_path ) free( p_sys->psz_path );
784
785     free( p_sys );
786     return VLC_EGENERIC;
787 }
788
789 /*****************************************************************************
790  * DemuxClose:
791  *****************************************************************************/
792 static void Close( vlc_object_t *p_this )
793 {
794     demux_t *p_demux = (demux_t*)p_this;
795     demux_sys_t *p_sys = p_demux->p_sys;
796     int i;
797
798     for( i = 0; i < p_sys->i_track; i++ )
799     {
800         live_track_t *tk = p_sys->track[i];
801
802         if( tk->b_muxed ) stream_DemuxDelete( tk->p_out_muxed );
803         free( tk->p_buffer );
804         free( tk );
805     }
806
807     if( p_sys->i_track ) free( p_sys->track );
808     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
809
810     if( p_sys->rtsp && p_sys->ms )
811     {
812         /* TEARDOWN */
813         p_sys->rtsp->teardownMediaSession( *p_sys->ms );
814     }
815
816     Medium::close( p_sys->ms );
817
818     if( p_sys->p_timeout )
819     {
820         p_sys->p_timeout->b_die = VLC_TRUE;
821         vlc_thread_join( p_sys->p_timeout );
822         vlc_object_detach( p_sys->p_timeout );
823         vlc_object_destroy( p_sys->p_timeout );
824     }
825
826     if( p_sys->rtsp ) Medium::close( p_sys->rtsp );
827     if( p_sys->env ) RECLAIM_ENV(p_sys->env);
828     if( p_sys->scheduler ) delete p_sys->scheduler;
829     if( p_sys->p_sdp ) free( p_sys->p_sdp );
830     if( p_sys->psz_path ) free( p_sys->psz_path );
831     free( p_sys );
832 }
833
834 /*****************************************************************************
835  * Demux:
836  *****************************************************************************/
837 static int Demux( demux_t *p_demux )
838 {
839     demux_sys_t    *p_sys = p_demux->p_sys;
840     TaskToken      task;
841
842     vlc_bool_t      b_send_pcr = VLC_TRUE;
843     mtime_t         i_pcr = 0;
844     int             i;
845
846     /* Check if we need to send the server a Keep-A-Live signal */
847     if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
848     {
849 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1138089600
850         char *psz_bye = NULL;
851         p_sys->rtsp->getMediaSessionParameter( *p_sys->ms, NULL, psz_bye );
852 #endif
853         p_sys->b_timeout_call = VLC_FALSE;
854     }
855
856     for( i = 0; i < p_sys->i_track; i++ )
857     {
858         live_track_t *tk = p_sys->track[i];
859
860         if( tk->b_asf || tk->b_muxed )
861             b_send_pcr = VLC_FALSE;
862
863         if( i_pcr == 0 )
864         {
865             i_pcr = tk->i_pts;
866         }
867         else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
868         {
869             i_pcr = tk->i_pts ;
870         }
871     }
872     if( i_pcr != p_sys->i_pcr && i_pcr > 0 )
873     {
874         p_sys->i_pcr = i_pcr;
875
876         if( b_send_pcr )
877             es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pcr );
878         if( p_sys->i_pcr_start <= 0 || p_sys->i_pcr_start > i_pcr ||
879             ( p_sys->i_length > 0 && i_pcr - p_sys->i_pcr_start > p_sys->i_length ) )
880         {
881             p_sys->i_pcr_start = i_pcr;
882         }
883     }
884
885     /* When a On Demand QT stream ends, the last frame keeps going with the same PCR/PTS value */
886     /* This tests for that, so we can later decide to end this session */
887     if( i_pcr > 0 && p_sys->i_pcr == p_sys->i_pcr_previous )
888     {
889         if( p_sys->i_pcr_repeats == 0 )
890             p_sys->i_pcr_repeatdate = mdate();
891         p_sys->i_pcr_repeats++;
892     }
893     else
894     {
895         p_sys->i_pcr_previous = p_sys->i_pcr;
896         p_sys->i_pcr_repeatdate = 0;
897         p_sys->i_pcr_repeats = 0;
898     }
899
900     if( p_sys->i_pcr_repeats > 5 && mdate() > p_sys->i_pcr_repeatdate + 1000000 )
901     {
902         /* We need at least 5 repeats over at least a second of time before we EOF */
903         msg_Dbg( p_demux, "suspect EOF due to end of VoD session" );
904         return 0;
905     }
906
907     /* First warm we want to read data */
908     p_sys->event = 0;
909     for( i = 0; i < p_sys->i_track; i++ )
910     {
911         live_track_t *tk = p_sys->track[i];
912
913         if( tk->waiting == 0 )
914         {
915             tk->waiting = 1;
916             tk->readSource->getNextFrame( tk->p_buffer, tk->i_buffer,
917                                           StreamRead, tk, StreamClose, tk );
918         }
919     }
920     /* Create a task that will be called if we wait more than 300ms */
921     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
922
923     /* Do the read */
924     p_sys->scheduler->doEventLoop( &p_sys->event );
925
926     /* remove the task */
927     p_sys->scheduler->unscheduleDelayedTask( task );
928
929     /* Check for gap in pts value */
930     for( i = 0; i < p_sys->i_track; i++ )
931     {
932         live_track_t *tk = p_sys->track[i];
933
934         if( !tk->b_muxed && !tk->b_rtcp_sync &&
935             tk->rtpSource && tk->rtpSource->hasBeenSynchronizedUsingRTCP() )
936         {
937             msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
938
939             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
940             tk->b_rtcp_sync = VLC_TRUE;
941
942             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
943             tk->i_pts = 0;
944             p_sys->i_pcr_start = 0;
945             p_sys->i_pcr = 0;
946             i_pcr = 0;
947         }
948     }
949
950     if( p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 120 )
951     {
952         /* FIXME Make this configurable
953         msg_Err( p_demux, "no multicast data received in 36s, aborting" );
954         return 0;
955         */
956     }
957     else if( !p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 34 )
958     {
959         vlc_bool_t b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" );
960
961         if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
962         {
963             msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
964             if( RollOverTcp( p_demux ) )
965             {
966                 msg_Err( p_demux, "TCP rollover failed, aborting" );
967                 return 0;
968             }
969             var_SetBool( p_demux, "rtsp-tcp", VLC_TRUE );
970         }
971         else if( p_sys->i_no_data_ti > 34 )
972         {
973             msg_Err( p_demux, "no data received in 10s, aborting" );
974             return 0;
975         }
976     }
977     else if( !p_sys->b_multicast && p_sys->b_no_data&& p_sys->i_no_data_ti > 34 )
978     {
979         /* EOF ? */
980         msg_Warn( p_demux, "no data received in 10s, eof ?" );
981         return 0;
982     }
983
984     return p_demux->b_error ? 0 : 1;
985 }
986
987 /*****************************************************************************
988  * Control:
989  *****************************************************************************/
990 static int Control( demux_t *p_demux, int i_query, va_list args )
991 {
992     demux_sys_t *p_sys = p_demux->p_sys;
993     int64_t *pi64;
994     double  *pf, f;
995     vlc_bool_t *pb, b_bool;
996
997     switch( i_query )
998     {
999         case DEMUX_GET_TIME:
1000             pi64 = (int64_t*)va_arg( args, int64_t * );
1001             *pi64 = p_sys->i_pcr - p_sys->i_pcr_start + p_sys->i_start;
1002             return VLC_SUCCESS;
1003
1004         case DEMUX_GET_LENGTH:
1005             pi64 = (int64_t*)va_arg( args, int64_t * );
1006             *pi64 = p_sys->i_length;
1007             return VLC_SUCCESS;
1008
1009         case DEMUX_GET_POSITION:
1010             pf = (double*)va_arg( args, double* );
1011             if( p_sys->i_length > 0 )
1012             {
1013                 *pf = (double)( p_sys->i_pcr - p_sys->i_pcr_start +
1014                                 p_sys->i_start ) / (double)(p_sys->i_length);
1015             }
1016             else
1017             {
1018                 *pf = 0;
1019             }
1020             return VLC_SUCCESS;
1021
1022         case DEMUX_SET_POSITION:
1023         {
1024             float time;
1025
1026             f = (double)va_arg( args, double );
1027             time = f * (double)p_sys->i_length / 1000000.0;   /* in second */
1028
1029             if( p_sys->rtsp && p_sys->i_length > 0 )
1030             {
1031                 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, time ) )
1032                 {
1033                     msg_Err( p_demux, "PLAY failed %s",
1034                         p_sys->env->getResultMsg() );
1035                     return VLC_EGENERIC;
1036                 }
1037                 p_sys->i_start = (mtime_t)(f * (double)p_sys->i_length);
1038                 p_sys->i_pcr_start = 0;
1039                 p_sys->i_pcr       = 0;
1040
1041                 return VLC_SUCCESS;
1042             }
1043             return VLC_SUCCESS;
1044         }
1045
1046         /* Special for access_demux */
1047         case DEMUX_CAN_PAUSE:
1048             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1049             if( p_sys->rtsp && p_sys->i_length )
1050                 /* Not always true, but will be handled in SET_PAUSE_STATE */
1051                 *pb = VLC_TRUE;
1052             else
1053                 *pb = VLC_FALSE;
1054             return VLC_SUCCESS;
1055
1056         case DEMUX_CAN_CONTROL_PACE:
1057             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1058
1059 #if 0       /* Disable for now until we have a clock synchro algo
1060              * which works with something else than MPEG over UDP */
1061             *pb = VLC_FALSE;
1062 #else
1063             *pb = VLC_TRUE;
1064 #endif
1065             return VLC_SUCCESS;
1066
1067         case DEMUX_SET_PAUSE_STATE:
1068             double d_npt;
1069
1070             d_npt = ( (double)( p_sys->i_pcr - p_sys->i_pcr_start +
1071                                 p_sys->i_start ) ) / 1000000.00;
1072
1073             b_bool = (vlc_bool_t)va_arg( args, vlc_bool_t );
1074             if( p_sys->rtsp == NULL )
1075                 return VLC_EGENERIC;
1076
1077             if( ( b_bool && !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) ) ||
1078                     ( !b_bool && !p_sys->rtsp->playMediaSession( *p_sys->ms,
1079                       d_npt > 0 ? d_npt : -1 ) ) )
1080             {
1081                     msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1082                     return VLC_EGENERIC;
1083             }
1084 #if 0
1085             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
1086             for( i = 0; i < p_sys->i_track; i++ )
1087             {
1088                 p_sys->track[i]->i_pts = 0;
1089             }
1090             p_sys->i_pcr_start = 0; /* FIXME Wrong */
1091             p_sys->i_pcr = 0;
1092 #endif
1093             return VLC_SUCCESS;
1094
1095         case DEMUX_GET_TITLE_INFO:
1096         case DEMUX_SET_TITLE:
1097         case DEMUX_SET_SEEKPOINT:
1098             return VLC_EGENERIC;
1099
1100         case DEMUX_GET_PTS_DELAY:
1101             pi64 = (int64_t*)va_arg( args, int64_t * );
1102             *pi64 = (int64_t)var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1103             return VLC_SUCCESS;
1104
1105         default:
1106             return VLC_EGENERIC;
1107     }
1108 }
1109
1110 /*****************************************************************************
1111  * RollOverTcp: reopen the rtsp into TCP mode
1112  * XXX: ugly, a lot of code are duplicated from Open()
1113  *****************************************************************************/
1114 static int RollOverTcp( demux_t *p_demux )
1115 {
1116     demux_sys_t *p_sys = p_demux->p_sys;
1117     MediaSubsessionIterator *iter;
1118     MediaSubsession *sub;
1119     char *psz_url;
1120     char *psz_options;
1121     char *psz_user;
1122     char *psz_pwd;
1123     uint8_t *p_sdp;
1124     int i_tk;
1125
1126     /* We close the old RTSP session */
1127     p_sys->rtsp->teardownMediaSession( *p_sys->ms );
1128
1129     Medium::close( p_sys->ms );
1130     Medium::close( p_sys->rtsp );
1131
1132     p_sys->ms = NULL;
1133     p_sys->rtsp = NULL;
1134
1135     /* Reopen rtsp client */
1136     if( ( p_sys->rtsp = RTSPClient::createNew(*p_sys->env, 1/*verbose*/,
1137           "VLC media player" ) ) == NULL )
1138     {
1139         msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
1140                  p_sys->env->getResultMsg() );
1141         return VLC_EGENERIC;
1142     }
1143
1144     asprintf( &psz_url, "rtsp://%s", p_sys->psz_path );
1145
1146     if( ( psz_options = p_sys->rtsp->sendOptionsCmd( psz_url ) ) )
1147         delete [] psz_options;
1148
1149     psz_user = var_CreateGetString( p_demux, "rtsp-user" );
1150     psz_pwd  = var_CreateGetString( p_demux, "rtsp-pwd" );
1151
1152     if ((*psz_user) && (*psz_pwd))
1153         p_sdp = (uint8_t*)p_sys->rtsp->describeWithPassword( psz_url,
1154                             psz_user, psz_pwd);
1155     else
1156         p_sdp = (uint8_t*)p_sys->rtsp->describeURL( psz_url,
1157                             NULL, var_CreateGetBool( p_demux, "rtsp-kasenna" ) );
1158
1159     free( psz_url );
1160     free( psz_user );
1161     free( psz_pwd );
1162
1163     if( p_sdp == NULL )
1164     {
1165         msg_Err( p_demux, "describeURL failed (%s)",
1166                  p_sys->env->getResultMsg() );
1167         return VLC_EGENERIC;
1168     }
1169
1170     /* malloc-ated copy */
1171     p_sys->p_sdp = strdup( (char*)p_sdp );
1172     delete[] p_sdp;
1173
1174     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
1175     {
1176         msg_Err( p_demux, "MediaSession::createNew failed" );
1177         return VLC_EGENERIC;
1178     }
1179
1180     /* Initialise each media subsession */
1181     iter = new MediaSubsessionIterator( *p_sys->ms );
1182     while( ( sub = iter->next() ) != NULL )
1183     {
1184         Boolean bInit;
1185
1186         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1187             bInit = sub->initiate( 4 ); /* Constant ? */
1188         else
1189             bInit = sub->initiate();
1190
1191         if( !bInit )
1192         {
1193             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
1194                       sub->mediumName(), sub->codecName(),
1195                       p_sys->env->getResultMsg() );
1196             continue;
1197         }
1198         msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
1199                  sub->codecName() );
1200
1201         /* Issue the SETUP */
1202         p_sys->rtsp->setupMediaSubsession( *sub, False, True /* tcp */ );
1203     }
1204
1205     /* The PLAY */
1206     if( !p_sys->rtsp->playMediaSession( *p_sys->ms ) )
1207     {
1208         msg_Err( p_demux, "PLAY failed %s", p_sys->env->getResultMsg() );
1209         return VLC_EGENERIC;
1210     }
1211
1212     /* Update all tracks */
1213     iter->reset();
1214     i_tk = 0;
1215     while( ( sub = iter->next() ) != NULL )
1216     {
1217         live_track_t *tk;
1218
1219         if( sub->readSource() == NULL )
1220             continue;
1221         if( i_tk >= p_sys->i_track )
1222         {
1223             msg_Err( p_demux, "WTF !" );
1224             break;
1225         }
1226
1227         tk = p_sys->track[i_tk];
1228
1229         /* Reset state */
1230         tk->waiting = 0;
1231         tk->i_pts   = 0;
1232         tk->b_rtcp_sync = VLC_FALSE;
1233
1234         if( sub->rtcpInstance() != NULL )
1235             sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1236
1237         tk->readSource = sub->readSource();
1238         tk->rtpSource  = sub->rtpSource();
1239
1240         i_tk++;
1241     }
1242
1243     delete iter;
1244
1245     return VLC_SUCCESS;
1246 }
1247
1248
1249 /*****************************************************************************
1250  *
1251  *****************************************************************************/
1252 static void StreamRead( void *p_private, unsigned int i_size,
1253                         unsigned int i_truncated_bytes, struct timeval pts,
1254                         unsigned int duration )
1255 {
1256     live_track_t   *tk = (live_track_t*)p_private;
1257     demux_t        *p_demux = tk->p_demux;
1258     demux_sys_t    *p_sys = p_demux->p_sys;
1259     block_t        *p_block;
1260
1261     mtime_t i_pts = (uint64_t)pts.tv_sec * UI64C(1000000) +
1262         (uint64_t)pts.tv_usec;
1263
1264     /* XXX Beurk beurk beurk Avoid having negative value XXX */
1265     i_pts &= UI64C(0x00ffffffffffffff);
1266
1267     if( tk->b_quicktime && tk->p_es == NULL )
1268     {
1269         QuickTimeGenericRTPSource *qtRTPSource =
1270             (QuickTimeGenericRTPSource*)tk->rtpSource;
1271         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1272         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1273
1274         if( qtState.sdAtomSize < 16 + 32 )
1275         {
1276             /* invalid */
1277             p_sys->event = 0xff;
1278             tk->waiting = 0;
1279             return;
1280         }
1281         tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1282         tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
1283         tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1284
1285         tk->fmt.i_extra        = qtState.sdAtomSize - 16;
1286         tk->fmt.p_extra        = malloc( tk->fmt.i_extra );
1287         memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1288
1289         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1290     }
1291
1292 #if 0
1293     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1294              i_size,
1295              pts.tv_sec * 1000000LL + pts.tv_usec );
1296 #endif
1297
1298     /* grow buffer if it looks like buffer is too small, but don't eat
1299      * up all the memory on strange streams */
1300     if( i_truncated_bytes > 0 && tk->i_buffer < 2000000 )
1301     {
1302         void *p_tmp;
1303         msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1304         msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1305         tk->i_buffer *= 2;
1306         p_tmp = realloc( tk->p_buffer, tk->i_buffer );
1307         if (p_tmp == NULL)
1308         {
1309             msg_Warn( p_demux, "realloc failed" );
1310         }
1311         else
1312         {
1313             tk->p_buffer = (uint8_t*)p_tmp;
1314         }
1315     }
1316     if( i_size > tk->i_buffer )
1317     {
1318         msg_Warn( p_demux, "buffer overflow" );
1319     }
1320     /* FIXME could i_size be > buffer size ? */
1321     if( tk->fmt.i_codec == VLC_FOURCC('s','a','m','r') ||
1322         tk->fmt.i_codec == VLC_FOURCC('s','a','w','b') )
1323     {
1324         AMRAudioSource *amrSource = (AMRAudioSource*)tk->readSource;
1325
1326         p_block = block_New( p_demux, i_size + 1 );
1327         p_block->p_buffer[0] = amrSource->lastFrameHeader();
1328         memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1329     }
1330     else if( tk->fmt.i_codec == VLC_FOURCC('H','2','6','1') )
1331     {
1332 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1081468800
1333         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->rtpSource;
1334         uint32_t header = h261Source->lastSpecialHeader();
1335 #else
1336         uint32_t header = 0;
1337         msg_Warn( p_demux, "need livemedia library >= \"2004.04.09\"" );
1338 #endif
1339         p_block = block_New( p_demux, i_size + 4 );
1340         memcpy( p_block->p_buffer, &header, 4 );
1341         memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1342
1343         if( tk->rtpSource->curPacketMarkerBit() )
1344             p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1345     }
1346     else if( tk->fmt.i_codec == VLC_FOURCC('H','2','6','4') )
1347     {
1348         if( (tk->p_buffer[0] & 0x1f) >= 24 )
1349             msg_Warn( p_demux, "unsupported NAL type for H264" );
1350
1351         /* Normal NAL type */
1352         p_block = block_New( p_demux, i_size + 4 );
1353         p_block->p_buffer[0] = 0x00;
1354         p_block->p_buffer[1] = 0x00;
1355         p_block->p_buffer[2] = 0x00;
1356         p_block->p_buffer[3] = 0x01;
1357         memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1358     }
1359     else if( tk->b_asf )
1360     {
1361         int i_copy = __MIN( p_sys->asfh.i_min_data_packet_size, (int)i_size );
1362         p_block = block_New( p_demux, p_sys->asfh.i_min_data_packet_size );
1363
1364         memcpy( p_block->p_buffer, tk->p_buffer, i_copy );
1365     }
1366     else
1367     {
1368         p_block = block_New( p_demux, i_size );
1369         memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1370     }
1371
1372     //p_block->i_rate = p_input->stream.control.i_rate;
1373
1374     if( i_pts != tk->i_pts && !tk->b_muxed )
1375     {
1376         p_block->i_dts = ( tk->fmt.i_cat == VIDEO_ES ) ? 0 : i_pts;
1377         p_block->i_pts = i_pts;
1378     }
1379
1380     if( tk->b_muxed )
1381     {
1382         stream_DemuxSend( tk->p_out_muxed, p_block );
1383     }
1384     else if( tk->b_asf )
1385     {
1386         stream_DemuxSend( p_sys->p_out_asf, p_block );
1387     }
1388     else
1389     {
1390         es_out_Send( p_demux->out, tk->p_es, p_block );
1391     }
1392
1393     /* warm that's ok */
1394     p_sys->event = 0xff;
1395
1396     /* we have read data */
1397     tk->waiting = 0;
1398     p_demux->p_sys->b_no_data = VLC_FALSE;
1399     p_demux->p_sys->i_no_data_ti = 0;
1400
1401     if( i_pts > 0 && !tk->b_muxed )
1402     {
1403         tk->i_pts = i_pts;
1404     }
1405 }
1406
1407 /*****************************************************************************
1408  *
1409  *****************************************************************************/
1410 static void StreamClose( void *p_private )
1411 {
1412     live_track_t   *tk = (live_track_t*)p_private;
1413     demux_t        *p_demux = tk->p_demux;
1414     demux_sys_t    *p_sys = p_demux->p_sys;
1415
1416     msg_Dbg( p_demux, "StreamClose" );
1417
1418     p_sys->event = 0xff;
1419     p_demux->b_error = VLC_TRUE;
1420 }
1421
1422
1423 /*****************************************************************************
1424  *
1425  *****************************************************************************/
1426 static void TaskInterrupt( void *p_private )
1427 {
1428     demux_t *p_demux = (demux_t*)p_private;
1429
1430     p_demux->p_sys->i_no_data_ti++;
1431
1432     /* Avoid lock */
1433     p_demux->p_sys->event = 0xff;
1434 }
1435
1436 /*****************************************************************************
1437  *  
1438  *****************************************************************************/
1439 static void TimeoutPrevention( timeout_thread_t *p_timeout )
1440 {
1441     p_timeout->b_die = VLC_FALSE;
1442     p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1443     p_timeout->i_remain *= 1000000;
1444
1445     vlc_thread_ready( p_timeout );
1446     
1447     /* Avoid lock */
1448     while( !p_timeout->b_die )
1449     {
1450         if( p_timeout->i_remain <= 0 )
1451         {
1452             p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1453             p_timeout->i_remain *= 1000000;
1454             p_timeout->p_sys->b_timeout_call = VLC_TRUE;
1455             msg_Dbg( p_timeout, "reset the timeout timer" );
1456         }
1457         p_timeout->i_remain -= 200000;
1458         msleep( 200000 ); /* 200 ms */
1459     }
1460 }
1461
1462 /*****************************************************************************
1463  *
1464  *****************************************************************************/
1465 static int b64_decode( char *dest, char *src );
1466
1467 static int ParseASF( demux_t *p_demux )
1468 {
1469     demux_sys_t    *p_sys = p_demux->p_sys;
1470
1471     const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1472     char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1473     char *psz_end;
1474     block_t *p_header;
1475
1476     /* Parse the asf header */
1477     if( psz_asf == NULL )
1478         return VLC_EGENERIC;
1479
1480     psz_asf += strlen( psz_marker );
1481     psz_asf = strdup( psz_asf );    /* Duplicate it */
1482     psz_end = strchr( psz_asf, '\n' );
1483
1484     while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1485         *psz_end-- = '\0';
1486
1487     if( psz_asf >= psz_end )
1488     {
1489         free( psz_asf );
1490         return VLC_EGENERIC;
1491     }
1492
1493     /* Always smaller */
1494     p_header = block_New( p_demux, psz_end - psz_asf );
1495     p_header->i_buffer = b64_decode( (char*)p_header->p_buffer, psz_asf );
1496     //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
1497     if( p_header->i_buffer <= 0 )
1498     {
1499         free( psz_asf );
1500         return VLC_EGENERIC;
1501     }
1502
1503     /* Parse it to get packet size */
1504     E_(asf_HeaderParse)( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
1505
1506     /* Send it to demuxer */
1507     stream_DemuxSend( p_sys->p_out_asf, p_header );
1508
1509     free( psz_asf );
1510     return VLC_SUCCESS;
1511 }
1512
1513 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
1514 static unsigned char* parseH264ConfigStr( char const* configStr,
1515                                           unsigned int& configSize )
1516 {
1517     char *dup, *psz;
1518
1519     if( configSize )
1520     configSize = 0;
1521
1522     if( configStr == NULL || *configStr == '\0' )
1523         return NULL;
1524
1525     psz = dup = strdup( configStr );
1526
1527     unsigned char *cfg = new unsigned char[5 * strlen(psz)];
1528     for( ;; )
1529     {
1530         char *p = strchr( psz, ',' );
1531         if( p )
1532             *p++ = '\0';
1533
1534         cfg[configSize++] = 0x00;
1535         cfg[configSize++] = 0x00;
1536         cfg[configSize++] = 0x00;
1537         cfg[configSize++] = 0x01;
1538         configSize += b64_decode( (char*)&cfg[configSize], psz );
1539
1540         if( p == NULL )
1541             break;
1542         psz = p;
1543     }
1544
1545     if( dup ) free( dup );
1546     return cfg;
1547 }
1548 #endif
1549
1550 /*char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";*/
1551 static int b64_decode( char *dest, char *src )
1552 {
1553     const char *dest_start = dest;
1554     int  i_level;
1555     int  last = 0;
1556     int  b64[256] = {
1557         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
1558         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
1559         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
1560         52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
1561         -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
1562         15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
1563         -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
1564         41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
1565         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
1566         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
1567         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
1568         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
1569         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
1570         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
1571         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
1572         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
1573         };
1574
1575     for( i_level = 0; *src != '\0'; src++ )
1576     {
1577         int  c;
1578
1579         c = b64[(unsigned int)*src];
1580         if( c == -1 )
1581         {
1582             continue;
1583         }
1584
1585         switch( i_level )
1586         {
1587             case 0:
1588                 i_level++;
1589                 break;
1590             case 1:
1591                 *dest++ = ( last << 2 ) | ( ( c >> 4)&0x03 );
1592                 i_level++;
1593                 break;
1594             case 2:
1595                 *dest++ = ( ( last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
1596                 i_level++;
1597                 break;
1598             case 3:
1599                 *dest++ = ( ( last &0x03 ) << 6 ) | c;
1600                 i_level = 0;
1601         }
1602         last = c;
1603     }
1604
1605     *dest = '\0';
1606
1607     return dest - dest_start;
1608 }