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