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