]> git.sesse.net Git - vlc/blob - modules/demux/livedotcom.cpp
* Fix AMR from liveMedia decoding. Patch by Alex Antropoff <alant at transtelecom...
[vlc] / modules / demux / livedotcom.cpp
1 /*****************************************************************************
2  * livedotcom.cpp : LIVE555 Streaming Media support.
3  *****************************************************************************
4  * Copyright (C) 2003-2005 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( !bInit )
407         {
408             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
409                       sub->mediumName(), sub->codecName(),
410                       p_sys->env->getResultMsg() );
411         }
412         else
413         {
414             if( sub->rtpSource() )
415             {
416                 int fd = sub->rtpSource()->RTPgs()->socketNum();
417                 /* Increase the buffer size */
418                 increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
419             }
420
421             msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
422                      sub->codecName() );
423
424             /* Issue the SETUP */
425             if( p_sys->rtsp )
426             {
427                 p_sys->rtsp->setupMediaSubsession( *sub, False,
428                                                    b_rtsp_tcp ? True : False );
429             }
430             if( !p_sys->b_multicast )
431             {
432                 /* Check, because we need diff. rollover behaviour for multicast */
433                 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
434             }
435         }
436     }
437
438     if( p_sys->rtsp )
439     {
440         /* The PLAY */
441         if( !p_sys->rtsp->playMediaSession( *p_sys->ms ) )
442         {
443             msg_Err( p_demux, "PLAY failed %s", p_sys->env->getResultMsg() );
444             delete iter;
445             goto error;
446         }
447
448         /* Retrieve the timeout value and set up a timeout prevention thread */
449 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1138089600
450         p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
451 #endif
452         if( p_sys->i_timeout > 0 )
453         {
454             msg_Dbg( p_demux, "We have a timeout of %d seconds",  p_sys->i_timeout );
455             p_sys->p_timeout = (timeout_thread_t *)vlc_object_create( p_demux, sizeof(timeout_thread_t) );
456             p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
457             if( vlc_thread_create( p_sys->p_timeout, "liveMedia-timeout", TimeoutPrevention,
458                                    VLC_THREAD_PRIORITY_LOW, VLC_TRUE ) )
459             {
460                 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
461                 delete iter;
462                 vlc_object_destroy( p_sys->p_timeout );
463                 goto error;
464             }
465             msg_Dbg( p_demux, "spawned timeout thread" );
466             vlc_object_attach( p_sys->p_timeout, p_demux );
467         }
468     }
469
470     /* Create all es struct */
471     iter->reset();
472     while( ( sub = iter->next() ) != NULL )
473     {
474         live_track_t *tk;
475
476         if( sub->readSource() == NULL ) continue;
477
478         tk = (live_track_t*)malloc( sizeof( live_track_t ) );
479         tk->p_demux = p_demux;
480         tk->waiting = 0;
481         tk->i_pts   = 0;
482         tk->b_quicktime = VLC_FALSE;
483         tk->b_muxed     = VLC_FALSE;
484         tk->b_asf       = VLC_FALSE;
485         tk->b_rtcp_sync = VLC_FALSE;
486         tk->p_out_muxed = NULL;
487         tk->p_es        = NULL;
488         tk->i_buffer    = 65536;
489         tk->p_buffer    = (uint8_t *)malloc( 65536 );
490
491         /* Value taken from mplayer */
492         if( !strcmp( sub->mediumName(), "audio" ) )
493         {
494             es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
495             tk->fmt.audio.i_channels = sub->numChannels();
496             tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
497
498             if( !strcmp( sub->codecName(), "MPA" ) ||
499                 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
500                 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
501             {
502                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
503                 tk->fmt.audio.i_rate = 0;
504             }
505             else if( !strcmp( sub->codecName(), "AC3" ) )
506             {
507                 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
508                 tk->fmt.audio.i_rate = 0;
509             }
510             else if( !strcmp( sub->codecName(), "L16" ) )
511             {
512                 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
513                 tk->fmt.audio.i_bitspersample = 16;
514             }
515             else if( !strcmp( sub->codecName(), "L8" ) )
516             {
517                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
518                 tk->fmt.audio.i_bitspersample = 8;
519             }
520             else if( !strcmp( sub->codecName(), "PCMU" ) )
521             {
522                 tk->fmt.i_codec = VLC_FOURCC( 'u', 'l', 'a', 'w' );
523             }
524             else if( !strcmp( sub->codecName(), "PCMA" ) )
525             {
526                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'l', 'a', 'w' );
527             }
528             else if( !strncmp( sub->codecName(), "G726", 4 ) )
529             {
530                 tk->fmt.i_codec = VLC_FOURCC( 'g', '7', '2', '6' ); 
531                 tk->fmt.audio.i_rate = 8000;
532                 tk->fmt.audio.i_channels = 1;
533                 if( !strcmp( sub->codecName()+5, "40" ) )
534                     tk->fmt.i_bitrate = 40000;
535                 else if( !strcmp( sub->codecName()+5, "32" ) )
536                     tk->fmt.i_bitrate = 32000;
537                 else if( !strcmp( sub->codecName()+5, "24" ) )
538                     tk->fmt.i_bitrate = 24000;
539                 else if( !strcmp( sub->codecName()+5, "16" ) )
540                     tk->fmt.i_bitrate = 16000;
541             }
542             else if( !strcmp( sub->codecName(), "AMR" ) )
543             {
544                 tk->fmt.i_codec = VLC_FOURCC( 's', 'a', 'm', 'r' );
545             }
546             else if( !strcmp( sub->codecName(), "AMR-WB" ) )
547             {
548                 tk->fmt.i_codec = VLC_FOURCC( 's', 'a', 'w', 'b' );
549             }
550             else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
551             {
552                 unsigned int i_extra;
553                 uint8_t      *p_extra;
554
555                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
556
557                 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
558                                                          i_extra ) ) )
559                 {
560                     tk->fmt.i_extra = i_extra;
561                     tk->fmt.p_extra = malloc( i_extra );
562                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
563                     delete[] p_extra;
564                 }
565
566 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1141257600
567                 /* Because the "faad" decoder does not handle the LATM data length field
568                    at the start of each returned LATM frame, tell the RTP source to omit it. */
569                 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
570 #endif
571             }
572             else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
573             {
574                 unsigned int i_extra;
575                 uint8_t      *p_extra;
576
577                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
578
579                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
580                                                        i_extra ) ) )
581                 {
582                     tk->fmt.i_extra = i_extra;
583                     tk->fmt.p_extra = malloc( i_extra );
584                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
585                     delete[] p_extra;
586                 }
587             }
588             else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
589             {
590                 tk->b_asf = VLC_TRUE;
591                 if( p_sys->p_out_asf == NULL )
592                     p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
593                                                         p_demux->out );
594             }
595         }
596         else if( !strcmp( sub->mediumName(), "video" ) )
597         {
598             es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
599             if( !strcmp( sub->codecName(), "MPV" ) )
600             {
601                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
602             }
603             else if( !strcmp( sub->codecName(), "H263" ) ||
604                      !strcmp( sub->codecName(), "H263-1998" ) ||
605                      !strcmp( sub->codecName(), "H263-2000" ) )
606             {
607                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '3' );
608             }
609             else if( !strcmp( sub->codecName(), "H261" ) )
610             {
611                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '1' );
612             }
613             else if( !strcmp( sub->codecName(), "H264" ) )
614             {
615 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
616                 unsigned int i_extra = 0;
617                 uint8_t      *p_extra = NULL;
618 #endif
619                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '4' );
620                 tk->fmt.b_packetized = VLC_FALSE;
621
622                 /* XXX not the right minimal version I fear */
623 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
624                 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
625                                                 i_extra ) ) )
626                 {
627                     tk->fmt.i_extra = i_extra;
628                     tk->fmt.p_extra = malloc( i_extra );
629                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
630
631                     delete[] p_extra;
632                 }
633 #endif
634             }
635             else if( !strcmp( sub->codecName(), "JPEG" ) )
636             {
637                 tk->fmt.i_codec = VLC_FOURCC( 'M', 'J', 'P', 'G' );
638             }
639             else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
640             {
641                 unsigned int i_extra;
642                 uint8_t      *p_extra;
643
644                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
645
646                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
647                                                        i_extra ) ) )
648                 {
649                     tk->fmt.i_extra = i_extra;
650                     tk->fmt.p_extra = malloc( i_extra );
651                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
652                     delete[] p_extra;
653                 }
654             }
655             else if( !strcmp( sub->codecName(), "X-QT" ) ||
656                      !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
657                      !strcmp( sub->codecName(), "X-QDM" ) ||
658                      !strcmp( sub->codecName(), "X-SV3V-ES" )  ||
659                      !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
660             {
661                 tk->b_quicktime = VLC_TRUE;
662             }
663             else if( !strcmp( sub->codecName(), "MP2T" ) )
664             {
665                 tk->b_muxed = VLC_TRUE;
666                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
667             }
668             else if( !strcmp( sub->codecName(), "MP2P" ) ||
669                      !strcmp( sub->codecName(), "MP1S" ) )
670             {
671                 tk->b_muxed = VLC_TRUE;
672                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
673                                                    p_demux->out );
674             }
675             else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
676             {
677                 tk->b_asf = VLC_TRUE;
678                 if( p_sys->p_out_asf == NULL )
679                     p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
680                                                         p_demux->out );;
681             }
682         }
683
684         if( tk->fmt.i_codec != VLC_FOURCC( 'u', 'n', 'd', 'f' ) )
685         {
686             tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
687         }
688
689         if( sub->rtcpInstance() != NULL )
690         {
691             sub->rtcpInstance()->setByeHandler( StreamClose, tk );
692         }
693
694         if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
695         {
696             tk->readSource = sub->readSource();
697             tk->rtpSource  = sub->rtpSource();
698
699             /* Append */
700             p_sys->track = (live_track_t**)realloc( p_sys->track, sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
701             p_sys->track[p_sys->i_track++] = tk;
702         }
703         else
704         {
705             free( tk );
706         }
707     }
708
709     delete iter;
710
711     if( p_sys->p_out_asf && ParseASF( p_demux ) )
712     {
713         msg_Err( p_demux, "cannot find a usable asf header" );
714         /* TODO Clean tracks */
715         goto error;
716     }
717
718     p_sys->i_length = (mtime_t)(p_sys->ms->playEndTime() * 1000000.0);
719     if( p_sys->i_length < 0 )
720     {
721         p_sys->i_length = 0;
722     }
723     else if( p_sys->i_length > 0 )
724     {
725         /* FIXME */
726         /* p_input->stream.p_selected_area->i_size = 1000;*/ /* needed for now */
727     }
728
729     if( p_sys->i_track <= 0 )
730     {
731         msg_Err( p_demux, "no codec supported, aborting" );
732         goto error;
733     }
734
735     return VLC_SUCCESS;
736
737 error:
738     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
739     if( p_sys->ms ) Medium::close( p_sys->ms );
740     if( p_sys->rtsp ) Medium::close( p_sys->rtsp );
741     if( p_sys->env ) RECLAIM_ENV(p_sys->env);
742     if( p_sys->p_timeout )
743     {
744         p_sys->p_timeout->b_die = VLC_TRUE;
745         vlc_thread_join( p_sys->p_timeout );
746         vlc_object_detach( p_sys->p_timeout );
747         vlc_object_destroy( p_sys->p_timeout );
748     }
749     if( p_sys->scheduler ) delete p_sys->scheduler;
750     if( p_sys->p_sdp ) free( p_sys->p_sdp );
751     if( p_sys->psz_path ) free( p_sys->psz_path );
752
753     free( p_sys );
754     return VLC_EGENERIC;
755 }
756
757 /*****************************************************************************
758  * DemuxClose:
759  *****************************************************************************/
760 static void Close( vlc_object_t *p_this )
761 {
762     demux_t *p_demux = (demux_t*)p_this;
763     demux_sys_t *p_sys = p_demux->p_sys;
764     int i;
765
766     for( i = 0; i < p_sys->i_track; i++ )
767     {
768         live_track_t *tk = p_sys->track[i];
769
770         if( tk->b_muxed ) stream_DemuxDelete( tk->p_out_muxed );
771         free( tk->p_buffer );
772         free( tk );
773     }
774
775     if( p_sys->i_track ) free( p_sys->track );
776     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
777
778     if( p_sys->rtsp && p_sys->ms )
779     {
780         /* TEARDOWN */
781         p_sys->rtsp->teardownMediaSession( *p_sys->ms );
782     }
783
784     Medium::close( p_sys->ms );
785
786     if( p_sys->p_timeout )
787     {
788         p_sys->p_timeout->b_die = VLC_TRUE;
789         vlc_thread_join( p_sys->p_timeout );
790         vlc_object_detach( p_sys->p_timeout );
791         vlc_object_destroy( p_sys->p_timeout );
792     }
793
794     if( p_sys->rtsp ) Medium::close( p_sys->rtsp );
795     if( p_sys->env ) RECLAIM_ENV(p_sys->env);
796     if( p_sys->scheduler ) delete p_sys->scheduler;
797     if( p_sys->p_sdp ) free( p_sys->p_sdp );
798     if( p_sys->psz_path ) free( p_sys->psz_path );
799     free( p_sys );
800 }
801
802 /*****************************************************************************
803  * Demux:
804  *****************************************************************************/
805 static int Demux( demux_t *p_demux )
806 {
807     demux_sys_t    *p_sys = p_demux->p_sys;
808     TaskToken      task;
809
810     vlc_bool_t      b_send_pcr = VLC_TRUE;
811     mtime_t         i_pcr = 0;
812     int             i;
813
814     /* Check if we need to send the server a Keep-A-Live signal */
815     if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
816     {
817         char *psz_bye = NULL;
818 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1138089600
819         p_sys->rtsp->getMediaSessionParameter( *p_sys->ms, NULL, psz_bye );
820 #endif
821         p_sys->b_timeout_call = VLC_FALSE;
822     }
823
824     for( i = 0; i < p_sys->i_track; i++ )
825     {
826         live_track_t *tk = p_sys->track[i];
827
828         if( tk->b_asf || tk->b_muxed )
829             b_send_pcr = VLC_FALSE;
830
831         if( i_pcr == 0 )
832         {
833             i_pcr = tk->i_pts;
834         }
835         else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
836         {
837             i_pcr = tk->i_pts ;
838         }
839     }
840     if( i_pcr != p_sys->i_pcr && i_pcr > 0 )
841     {
842         p_sys->i_pcr = i_pcr;
843
844         if( b_send_pcr )
845             es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pcr );
846         if( p_sys->i_pcr_start <= 0 || p_sys->i_pcr_start > i_pcr ||
847             ( p_sys->i_length > 0 && i_pcr - p_sys->i_pcr_start > p_sys->i_length ) )
848         {
849             p_sys->i_pcr_start = i_pcr;
850         }
851     }
852
853     /* When a On Demand QT stream ends, the last frame keeps going with the same PCR/PTS value */
854     /* This tests for that, so we can later decide to end this session */
855     if( i_pcr > 0 && p_sys->i_pcr == p_sys->i_pcr_previous )
856     {
857         if( p_sys->i_pcr_repeats == 0 )
858             p_sys->i_pcr_repeatdate = mdate();
859         p_sys->i_pcr_repeats++;
860     }
861     else
862     {
863         p_sys->i_pcr_previous = p_sys->i_pcr;
864         p_sys->i_pcr_repeatdate = 0;
865         p_sys->i_pcr_repeats = 0;
866     }
867
868     if( p_sys->i_pcr_repeats > 5 && mdate() > p_sys->i_pcr_repeatdate + 1000000 )
869     {
870         /* We need at least 5 repeats over at least a second of time before we EOF */
871         msg_Dbg( p_demux, "suspect EOF due to end of VoD session" );
872         return 0;
873     }
874
875     /* First warm we want to read data */
876     p_sys->event = 0;
877     for( i = 0; i < p_sys->i_track; i++ )
878     {
879         live_track_t *tk = p_sys->track[i];
880
881         if( tk->waiting == 0 )
882         {
883             tk->waiting = 1;
884             tk->readSource->getNextFrame( tk->p_buffer, tk->i_buffer,
885                                           StreamRead, tk, StreamClose, tk );
886         }
887     }
888     /* Create a task that will be called if we wait more than 300ms */
889     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
890
891     /* Do the read */
892     p_sys->scheduler->doEventLoop( &p_sys->event );
893
894     /* remove the task */
895     p_sys->scheduler->unscheduleDelayedTask( task );
896
897     /* Check for gap in pts value */
898     for( i = 0; i < p_sys->i_track; i++ )
899     {
900         live_track_t *tk = p_sys->track[i];
901
902         if( !tk->b_muxed && !tk->b_rtcp_sync &&
903             tk->rtpSource && tk->rtpSource->hasBeenSynchronizedUsingRTCP() )
904         {
905             msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
906
907             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
908             tk->b_rtcp_sync = VLC_TRUE;
909
910             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
911             tk->i_pts = 0;
912             p_sys->i_pcr_start = 0;
913             p_sys->i_pcr = 0;
914             i_pcr = 0;
915         }
916     }
917
918     if( p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 120 )
919     {
920         /* FIXME Make this configurable
921         msg_Err( p_demux, "no multicast data received in 36s, aborting" );
922         return 0;
923         */
924     }
925     else if( !p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 34 )
926     {
927         vlc_bool_t b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" );
928
929         if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
930         {
931             msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
932             if( RollOverTcp( p_demux ) )
933             {
934                 msg_Err( p_demux, "TCP rollover failed, aborting" );
935                 return 0;
936             }
937             var_SetBool( p_demux, "rtsp-tcp", VLC_TRUE );
938         }
939         else if( p_sys->i_no_data_ti > 34 )
940         {
941             msg_Err( p_demux, "no data received in 10s, aborting" );
942             return 0;
943         }
944     }
945     else if( !p_sys->b_multicast && p_sys->b_no_data&& p_sys->i_no_data_ti > 34 )
946     {
947         /* EOF ? */
948         msg_Warn( p_demux, "no data received in 10s, eof ?" );
949         return 0;
950     }
951
952     return p_demux->b_error ? 0 : 1;
953 }
954
955 /*****************************************************************************
956  * Control:
957  *****************************************************************************/
958 static int Control( demux_t *p_demux, int i_query, va_list args )
959 {
960     demux_sys_t *p_sys = p_demux->p_sys;
961     int64_t *pi64;
962     double  *pf, f;
963     vlc_bool_t *pb, b_bool;
964
965     switch( i_query )
966     {
967         case DEMUX_GET_TIME:
968             pi64 = (int64_t*)va_arg( args, int64_t * );
969             *pi64 = p_sys->i_pcr - p_sys->i_pcr_start + p_sys->i_start;
970             return VLC_SUCCESS;
971
972         case DEMUX_GET_LENGTH:
973             pi64 = (int64_t*)va_arg( args, int64_t * );
974             *pi64 = p_sys->i_length;
975             return VLC_SUCCESS;
976
977         case DEMUX_GET_POSITION:
978             pf = (double*)va_arg( args, double* );
979             if( p_sys->i_length > 0 )
980             {
981                 *pf = (double)( p_sys->i_pcr - p_sys->i_pcr_start +
982                                 p_sys->i_start ) / (double)(p_sys->i_length);
983             }
984             else
985             {
986                 *pf = 0;
987             }
988             return VLC_SUCCESS;
989
990         case DEMUX_SET_POSITION:
991         {
992             float time;
993
994             f = (double)va_arg( args, double );
995             time = f * (double)p_sys->i_length / 1000000.0;   /* in second */
996
997             if( p_sys->rtsp && p_sys->i_length > 0 )
998             {
999                 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, time ) )
1000                 {
1001                     msg_Err( p_demux, "PLAY failed %s", p_sys->env->getResultMsg() );
1002                     return VLC_EGENERIC;
1003                 }
1004                 p_sys->i_start = (mtime_t)(f * (double)p_sys->i_length);
1005                 p_sys->i_pcr_start = 0;
1006                 p_sys->i_pcr       = 0;
1007
1008                 return VLC_SUCCESS;
1009             }
1010             return VLC_SUCCESS;
1011         }
1012
1013         /* Special for access_demux */
1014         case DEMUX_CAN_PAUSE:
1015             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1016             if( p_sys->rtsp && p_sys->i_length )
1017                 /* Not always true, but will be handled in SET_PAUSE_STATE */
1018                 *pb = VLC_TRUE;
1019             else
1020                 *pb = VLC_FALSE;
1021             return VLC_SUCCESS;
1022
1023         case DEMUX_CAN_CONTROL_PACE:
1024             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1025
1026 #if 0       /* Disable for now until we have a clock synchro algo
1027              * which works with something else than MPEG over UDP */
1028             *pb = VLC_FALSE;
1029 #else
1030             *pb = VLC_TRUE;
1031 #endif
1032             return VLC_SUCCESS;
1033
1034         case DEMUX_SET_PAUSE_STATE:
1035             double d_npt;
1036
1037             d_npt = ( (double)( p_sys->i_pcr - p_sys->i_pcr_start +
1038                                 p_sys->i_start ) ) / 1000000.00;
1039
1040             b_bool = (vlc_bool_t)va_arg( args, vlc_bool_t );
1041             if( p_sys->rtsp == NULL )
1042                 return VLC_EGENERIC;
1043
1044             if( ( b_bool && !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) ) ||
1045                     ( !b_bool && !p_sys->rtsp->playMediaSession( *p_sys->ms,
1046                       d_npt > 0 ? d_npt : -1 ) ) )
1047             {
1048                     msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1049                     return VLC_EGENERIC;
1050             }
1051 #if 0
1052             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
1053             for( i = 0; i < p_sys->i_track; i++ )
1054             {
1055                 p_sys->track[i]->i_pts = 0;
1056             }
1057             p_sys->i_pcr_start = 0; /* FIXME Wrong */
1058             p_sys->i_pcr = 0;
1059 #endif
1060             return VLC_SUCCESS;
1061
1062         case DEMUX_GET_TITLE_INFO:
1063         case DEMUX_SET_TITLE:
1064         case DEMUX_SET_SEEKPOINT:
1065             return VLC_EGENERIC;
1066
1067         case DEMUX_GET_PTS_DELAY:
1068             pi64 = (int64_t*)va_arg( args, int64_t * );
1069             *pi64 = (int64_t)var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1070             return VLC_SUCCESS;
1071
1072         default:
1073             return VLC_EGENERIC;
1074     }
1075 }
1076
1077 /*****************************************************************************
1078  * RollOverTcp: reopen the rtsp into TCP mode
1079  * XXX: ugly, a lot of code are duplicated from Open()
1080  *****************************************************************************/
1081 static int RollOverTcp( demux_t *p_demux )
1082 {
1083     demux_sys_t *p_sys = p_demux->p_sys;
1084     MediaSubsessionIterator *iter;
1085     MediaSubsession *sub;
1086     char *psz_url;
1087     char *psz_options;
1088     uint8_t *p_sdp;
1089     int i_tk;
1090
1091     /* We close the old RTSP session */
1092     p_sys->rtsp->teardownMediaSession( *p_sys->ms );
1093
1094     Medium::close( p_sys->ms );
1095     Medium::close( p_sys->rtsp );
1096
1097     p_sys->ms = NULL;
1098     p_sys->rtsp = NULL;
1099
1100     /* Reopen rtsp client */
1101     if( ( p_sys->rtsp = RTSPClient::createNew(*p_sys->env, 1/*verbose*/,
1102           "VLC Media Player" ) ) == NULL )
1103     {
1104         msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
1105                  p_sys->env->getResultMsg() );
1106         return VLC_EGENERIC;
1107     }
1108
1109     asprintf( &psz_url, "rtsp://%s", p_sys->psz_path );
1110
1111     if( ( psz_options = p_sys->rtsp->sendOptionsCmd( psz_url ) ) )
1112         delete [] psz_options;
1113
1114     p_sdp = (uint8_t*)p_sys->rtsp->describeURL( psz_url,
1115                           NULL, var_CreateGetBool( p_demux, "rtsp-kasenna" ) );
1116     free( psz_url );
1117     if( p_sdp == NULL )
1118     {
1119         msg_Err( p_demux, "describeURL failed (%s)",
1120                  p_sys->env->getResultMsg() );
1121         return VLC_EGENERIC;
1122     }
1123
1124     /* malloc-ated copy */
1125     p_sys->p_sdp = strdup( (char*)p_sdp );
1126     delete[] p_sdp;
1127
1128     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
1129     {
1130         msg_Err( p_demux, "MediaSession::createNew failed" );
1131         return VLC_EGENERIC;
1132     }
1133
1134     /* Initialise each media subsession */
1135     iter = new MediaSubsessionIterator( *p_sys->ms );
1136     while( ( sub = iter->next() ) != NULL )
1137     {
1138         Boolean bInit;
1139
1140         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1141             bInit = sub->initiate( 4 ); /* Constant ? */
1142         else
1143             bInit = sub->initiate();
1144
1145         if( !bInit )
1146         {
1147             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
1148                       sub->mediumName(), sub->codecName(),
1149                       p_sys->env->getResultMsg() );
1150             continue;
1151         }
1152         msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
1153                  sub->codecName() );
1154
1155         /* Issue the SETUP */
1156         p_sys->rtsp->setupMediaSubsession( *sub, False, True /* tcp */ );
1157     }
1158
1159     /* The PLAY */
1160     if( !p_sys->rtsp->playMediaSession( *p_sys->ms ) )
1161     {
1162         msg_Err( p_demux, "PLAY failed %s", p_sys->env->getResultMsg() );
1163         return VLC_EGENERIC;
1164     }
1165
1166     /* Update all tracks */
1167     iter->reset();
1168     i_tk = 0;
1169     while( ( sub = iter->next() ) != NULL )
1170     {
1171         live_track_t *tk;
1172
1173         if( sub->readSource() == NULL )
1174             continue;
1175         if( i_tk >= p_sys->i_track )
1176         {
1177             msg_Err( p_demux, "WTF !" );
1178             break;
1179         }
1180
1181         tk = p_sys->track[i_tk];
1182
1183         /* Reset state */
1184         tk->waiting = 0;
1185         tk->i_pts   = 0;
1186         tk->b_rtcp_sync = VLC_FALSE;
1187
1188         if( sub->rtcpInstance() != NULL )
1189             sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1190
1191         tk->readSource = sub->readSource();
1192         tk->rtpSource  = sub->rtpSource();
1193
1194         i_tk++;
1195     }
1196
1197     delete iter;
1198
1199     return VLC_SUCCESS;
1200 }
1201
1202
1203 /*****************************************************************************
1204  *
1205  *****************************************************************************/
1206 static void StreamRead( void *p_private, unsigned int i_size,
1207                         unsigned int i_truncated_bytes, struct timeval pts,
1208                         unsigned int duration )
1209 {
1210     live_track_t   *tk = (live_track_t*)p_private;
1211     demux_t        *p_demux = tk->p_demux;
1212     demux_sys_t    *p_sys = p_demux->p_sys;
1213     block_t        *p_block;
1214
1215     mtime_t i_pts = (uint64_t)pts.tv_sec * UI64C(1000000) +
1216         (uint64_t)pts.tv_usec;
1217
1218     /* XXX Beurk beurk beurk Avoid having negative value XXX */
1219     i_pts &= UI64C(0x00ffffffffffffff);
1220
1221     if( tk->b_quicktime && tk->p_es == NULL )
1222     {
1223         QuickTimeGenericRTPSource *qtRTPSource =
1224             (QuickTimeGenericRTPSource*)tk->rtpSource;
1225         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1226         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1227
1228         if( qtState.sdAtomSize < 16 + 32 )
1229         {
1230             /* invalid */
1231             p_sys->event = 0xff;
1232             tk->waiting = 0;
1233             return;
1234         }
1235         tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1236         tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
1237         tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1238
1239         tk->fmt.i_extra        = qtState.sdAtomSize - 16;
1240         tk->fmt.p_extra        = malloc( tk->fmt.i_extra );
1241         memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1242
1243         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1244     }
1245
1246 #if 0
1247     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1248              i_size,
1249              pts.tv_sec * 1000000LL + pts.tv_usec );
1250 #endif
1251
1252     /* grow buffer if it looks like buffer is too small, but don't eat
1253      * up all the memory on strange streams */
1254     if( i_truncated_bytes > 0 && tk->i_buffer < 2000000 )
1255     {
1256         void *p_tmp;
1257         msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1258         msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1259         tk->i_buffer *= 2;
1260         p_tmp = realloc( tk->p_buffer, tk->i_buffer );
1261         if (p_tmp == NULL)
1262         {
1263             msg_Warn( p_demux, "realloc failed" );
1264         }
1265         else
1266         {
1267             tk->p_buffer = (uint8_t*)p_tmp;
1268         }
1269     }
1270     if( i_size > tk->i_buffer )
1271     {
1272         msg_Warn( p_demux, "buffer overflow" );
1273     }
1274     /* FIXME could i_size be > buffer size ? */
1275     if( tk->fmt.i_codec == VLC_FOURCC('s','a','m','r') ||
1276         tk->fmt.i_codec == VLC_FOURCC('s','a','w','b') )
1277     {
1278         AMRAudioSource *amrSource = (AMRAudioSource*)tk->readSource;
1279
1280         p_block = block_New( p_demux, i_size + 1 );
1281         p_block->p_buffer[0] = amrSource->lastFrameHeader();
1282         memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1283     }
1284     else if( tk->fmt.i_codec == VLC_FOURCC('H','2','6','1') )
1285     {
1286 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1081468800
1287         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->rtpSource;
1288         uint32_t header = h261Source->lastSpecialHeader();
1289 #else
1290         uint32_t header = 0;
1291         msg_Warn( p_demux, "need livemedia library >= \"2004.04.09\"" );
1292 #endif
1293         p_block = block_New( p_demux, i_size + 4 );
1294         memcpy( p_block->p_buffer, &header, 4 );
1295         memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1296
1297         if( tk->rtpSource->curPacketMarkerBit() )
1298             p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1299     }
1300     else if( tk->fmt.i_codec == VLC_FOURCC('H','2','6','4') )
1301     {
1302         if( (tk->p_buffer[0] & 0x1f) >= 24 )
1303             msg_Warn( p_demux, "unsupported NAL type for H264" );
1304
1305         /* Normal NAL type */
1306         p_block = block_New( p_demux, i_size + 4 );
1307         p_block->p_buffer[0] = 0x00;
1308         p_block->p_buffer[1] = 0x00;
1309         p_block->p_buffer[2] = 0x00;
1310         p_block->p_buffer[3] = 0x01;
1311         memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1312     }
1313     else if( tk->b_asf )
1314     {
1315         int i_copy = __MIN( p_sys->asfh.i_min_data_packet_size, (int)i_size );
1316         p_block = block_New( p_demux, p_sys->asfh.i_min_data_packet_size );
1317
1318         memcpy( p_block->p_buffer, tk->p_buffer, i_copy );
1319     }
1320     else
1321     {
1322         p_block = block_New( p_demux, i_size );
1323         memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1324     }
1325
1326     //p_block->i_rate = p_input->stream.control.i_rate;
1327
1328     if( i_pts != tk->i_pts && !tk->b_muxed )
1329     {
1330         p_block->i_dts = ( tk->fmt.i_cat == VIDEO_ES ) ? 0 : i_pts;
1331         p_block->i_pts = i_pts;
1332     }
1333
1334     if( tk->b_muxed )
1335     {
1336         stream_DemuxSend( tk->p_out_muxed, p_block );
1337     }
1338     else if( tk->b_asf )
1339     {
1340         stream_DemuxSend( p_sys->p_out_asf, p_block );
1341     }
1342     else
1343     {
1344         es_out_Send( p_demux->out, tk->p_es, p_block );
1345     }
1346
1347     /* warm that's ok */
1348     p_sys->event = 0xff;
1349
1350     /* we have read data */
1351     tk->waiting = 0;
1352     p_demux->p_sys->b_no_data = VLC_FALSE;
1353     p_demux->p_sys->i_no_data_ti = 0;
1354
1355     if( i_pts > 0 && !tk->b_muxed )
1356     {
1357         tk->i_pts = i_pts;
1358     }
1359 }
1360
1361 /*****************************************************************************
1362  *
1363  *****************************************************************************/
1364 static void StreamClose( void *p_private )
1365 {
1366     live_track_t   *tk = (live_track_t*)p_private;
1367     demux_t        *p_demux = tk->p_demux;
1368     demux_sys_t    *p_sys = p_demux->p_sys;
1369
1370     msg_Dbg( p_demux, "StreamClose" );
1371
1372     p_sys->event = 0xff;
1373     p_demux->b_error = VLC_TRUE;
1374 }
1375
1376
1377 /*****************************************************************************
1378  *
1379  *****************************************************************************/
1380 static void TaskInterrupt( void *p_private )
1381 {
1382     demux_t *p_demux = (demux_t*)p_private;
1383
1384     p_demux->p_sys->i_no_data_ti++;
1385
1386     /* Avoid lock */
1387     p_demux->p_sys->event = 0xff;
1388 }
1389
1390 /*****************************************************************************
1391  *  
1392  *****************************************************************************/
1393 static void TimeoutPrevention( timeout_thread_t *p_timeout )
1394 {
1395     p_timeout->b_die = VLC_FALSE;
1396     p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1397     p_timeout->i_remain *= 1000000;
1398
1399     vlc_thread_ready( p_timeout );
1400     
1401     /* Avoid lock */
1402     while( !p_timeout->b_die )
1403     {
1404         if( p_timeout->i_remain <= 0 )
1405         {
1406             p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1407             p_timeout->i_remain *= 1000000;
1408             p_timeout->p_sys->b_timeout_call = VLC_TRUE;
1409             msg_Dbg( p_timeout, "reset the timeout timer" );
1410         }
1411         p_timeout->i_remain -= 200000;
1412         msleep( 200000 ); /* 200 ms */
1413     }
1414 }
1415
1416 /*****************************************************************************
1417  *
1418  *****************************************************************************/
1419 static int b64_decode( char *dest, char *src );
1420
1421 static int ParseASF( demux_t *p_demux )
1422 {
1423     demux_sys_t    *p_sys = p_demux->p_sys;
1424
1425     const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1426     char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1427     char *psz_end;
1428     block_t *p_header;
1429
1430     /* Parse the asf header */
1431     if( psz_asf == NULL )
1432         return VLC_EGENERIC;
1433
1434     psz_asf += strlen( psz_marker );
1435     psz_asf = strdup( psz_asf );    /* Duplicate it */
1436     psz_end = strchr( psz_asf, '\n' );
1437
1438     while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1439         *psz_end-- = '\0';
1440
1441     if( psz_asf >= psz_end )
1442     {
1443         free( psz_asf );
1444         return VLC_EGENERIC;
1445     }
1446
1447     /* Always smaller */
1448     p_header = block_New( p_demux, psz_end - psz_asf );
1449     p_header->i_buffer = b64_decode( (char*)p_header->p_buffer, psz_asf );
1450     //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
1451     if( p_header->i_buffer <= 0 )
1452     {
1453         free( psz_asf );
1454         return VLC_EGENERIC;
1455     }
1456
1457     /* Parse it to get packet size */
1458     E_(asf_HeaderParse)( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
1459
1460     /* Send it to demuxer */
1461     stream_DemuxSend( p_sys->p_out_asf, p_header );
1462
1463     free( psz_asf );
1464     return VLC_SUCCESS;
1465 }
1466
1467 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
1468 static unsigned char* parseH264ConfigStr( char const* configStr,
1469                                           unsigned int& configSize )
1470 {
1471     char *dup, *psz;
1472
1473     if( configSize )
1474     configSize = 0;
1475
1476     if( configStr == NULL || *configStr == '\0' )
1477         return NULL;
1478
1479     psz = dup = strdup( configStr );
1480
1481     unsigned char *cfg = new unsigned char[5 * strlen(psz)];
1482     for( ;; )
1483     {
1484         char *p = strchr( psz, ',' );
1485         if( p )
1486             *p++ = '\0';
1487
1488         cfg[configSize++] = 0x00;
1489         cfg[configSize++] = 0x00;
1490         cfg[configSize++] = 0x00;
1491         cfg[configSize++] = 0x01;
1492         configSize += b64_decode( (char*)&cfg[configSize], psz );
1493
1494         if( p == NULL )
1495             break;
1496         psz = p;
1497     }
1498
1499     if( dup ) free( dup );
1500     return cfg;
1501 }
1502 #endif
1503
1504 /*char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";*/
1505 static int b64_decode( char *dest, char *src )
1506 {
1507     const char *dest_start = dest;
1508     int  i_level;
1509     int  last = 0;
1510     int  b64[256] = {
1511         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
1512         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
1513         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
1514         52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
1515         -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
1516         15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
1517         -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
1518         41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
1519         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
1520         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
1521         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
1522         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
1523         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
1524         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
1525         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
1526         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
1527         };
1528
1529     for( i_level = 0; *src != '\0'; src++ )
1530     {
1531         int  c;
1532
1533         c = b64[(unsigned int)*src];
1534         if( c == -1 )
1535         {
1536             continue;
1537         }
1538
1539         switch( i_level )
1540         {
1541             case 0:
1542                 i_level++;
1543                 break;
1544             case 1:
1545                 *dest++ = ( last << 2 ) | ( ( c >> 4)&0x03 );
1546                 i_level++;
1547                 break;
1548             case 2:
1549                 *dest++ = ( ( last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
1550                 i_level++;
1551                 break;
1552             case 3:
1553                 *dest++ = ( ( last &0x03 ) << 6 ) | c;
1554                 i_level = 0;
1555         }
1556         last = c;
1557     }
1558
1559     *dest = '\0';
1560
1561     return dest - dest_start;
1562 }