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