]> git.sesse.net Git - vlc/blob - modules/demux/livedotcom.cpp
Fix breakage in transcode file selection
[vlc] / modules / demux / livedotcom.cpp
1 /*****************************************************************************
2  * live.cpp : live.com support.
3  *****************************************************************************
4  * Copyright (C) 2003-2004 VideoLAN
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., 59 Temple Place - Suite 330, Boston, MA  02111, 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
32 #include <iostream>
33
34 #if defined( WIN32 )
35 #   include <winsock2.h>
36 #endif
37
38 #include "BasicUsageEnvironment.hh"
39 #include "GroupsockHelper.hh"
40 #include "liveMedia.hh"
41
42 extern "C" {
43 #include "../access/mms/asf.h"  /* Who said ugly ? */
44 }
45
46 #if (LIVEMEDIA_LIBRARY_VERSION_INT < 1089936000)
47 #define RECLAIM_ENV(env) delete (env)
48 #else
49 #define RECLAIM_ENV(env) (env)->reclaim()
50 #endif
51
52 using namespace std;
53
54 /*****************************************************************************
55  * Module descriptor
56  *****************************************************************************/
57 static int  Open ( vlc_object_t * );
58 static void Close( vlc_object_t * );
59
60 #define CACHING_TEXT N_("Caching value (ms)")
61 #define CACHING_LONGTEXT N_( \
62     "Allows you to modify the default caching value for RTSP streams. This " \
63     "value should be set in millisecond units." )
64
65 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
66 #define KASENNA_LONGTEXT N_( "Kasenna server speak an old and unstandard " \
67     "dialect of RTSP. When you set this parameter, VLC will try this dialect "\
68     "for communication. In this mode you cannot talk to normal RTSP servers." )
69
70 vlc_module_begin();
71     set_description( _("live.com (RTSP/RTP/SDP) demuxer" ) );
72     set_capability( "demux2", 50 );
73     set_shortname( "Live.com RTP/RTSP");
74     set_callbacks( Open, Close );
75     add_shortcut( "live" );
76     set_category( CAT_INPUT );
77     set_subcategory( SUBCAT_INPUT_DEMUX );
78
79     add_submodule();
80         set_description( _("RTSP/RTP access and demux") );
81         add_shortcut( "rtsp" );
82         add_shortcut( "sdp" );
83         set_capability( "access_demux", 0 );
84         set_callbacks( Open, Close );
85         add_bool( "rtsp-tcp", 0, NULL,
86                   N_("Use RTP over RTSP (TCP)"),
87                   N_("Use RTP over RTSP (TCP)"), VLC_TRUE );
88         add_integer( "rtsp-caching", 4 * DEFAULT_PTS_DELAY / 1000, NULL,
89             CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
90         add_bool( "rtsp-kasenna", VLC_FALSE, NULL, KASENNA_TEXT,
91                   KASENNA_LONGTEXT, VLC_TRUE );
92 vlc_module_end();
93
94 /* TODO:
95  *  - Improve support of PS/TS
96  *  - Support X-QT/X-QUICKTIME generic codec for audio.
97  *
98  *  - Check memory leak, delete/free -> still one when using rtsp-tcp but I'm
99  *  not sure if it comes from me.
100  *
101  */
102
103 /*****************************************************************************
104  * Local prototypes
105  *****************************************************************************/
106 typedef struct
107 {
108     demux_t     *p_demux;
109
110     vlc_bool_t   b_quicktime;
111     vlc_bool_t   b_muxed;
112     vlc_bool_t   b_asf;
113
114     es_format_t  fmt;
115     es_out_id_t  *p_es;
116
117     stream_t     *p_out_muxed;    /* for muxed stream */
118
119     RTPSource    *rtpSource;
120     FramedSource *readSource;
121     vlc_bool_t   b_rtcp_sync;
122
123     uint8_t      *p_buffer;
124     unsigned int  i_buffer;
125
126     char         waiting;
127
128     mtime_t      i_pts;
129
130 } live_track_t;
131
132 struct demux_sys_t
133 {
134     char         *p_sdp;    /* XXX mallocated */
135
136     MediaSession     *ms;
137     TaskScheduler    *scheduler;
138     UsageEnvironment *env ;
139     RTSPClient       *rtsp;
140
141     /* */
142     int              i_track;
143     live_track_t     **track;   /* XXX mallocated */
144     mtime_t          i_pcr;
145     mtime_t          i_pcr_start;
146
147     /* Asf */
148     asf_header_t     asfh;
149     stream_t         *p_out_asf;
150
151     /* */
152     mtime_t          i_length;
153     mtime_t          i_start;
154
155     char             event;
156 };
157
158 static int Demux  ( demux_t * );
159 static int Control( demux_t *, int, va_list );
160
161 static int ParseASF( demux_t * );
162
163 static void StreamRead( void *, unsigned int, unsigned int,
164                         struct timeval, unsigned int );
165 static void StreamClose( void * );
166 static void TaskInterrupt( void * );
167
168 /*****************************************************************************
169  * DemuxOpen:
170  *****************************************************************************/
171 static int  Open ( vlc_object_t *p_this )
172 {
173     demux_t     *p_demux = (demux_t*)p_this;
174     demux_sys_t *p_sys;
175
176     MediaSubsessionIterator *iter;
177     MediaSubsession *sub;
178
179     vlc_bool_t b_rtsp_tcp;
180     uint8_t *p_peek;
181
182     int     i_sdp;
183     int     i_sdp_max;
184     uint8_t *p_sdp;
185
186     if( p_demux->s )
187     {
188         /* See if it looks like a SDP
189            v, o, s fields are mandatory and in this order */
190         if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 )
191         {
192             msg_Err( p_demux, "cannot peek" );
193             return VLC_EGENERIC;
194         }
195         if( strncmp( (char*)p_peek, "v=0\r\n", 5 ) &&
196             strncmp( (char*)p_peek, "v=0\n", 4 ) &&
197             ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
198         {
199             msg_Warn( p_demux, "SDP module discarded" );
200             return VLC_EGENERIC;
201         }
202     }
203     else
204     {
205         var_Create( p_demux, "rtsp-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
206     }
207
208     p_demux->pf_demux  = Demux;
209     p_demux->pf_control= Control;
210     p_demux->p_sys     = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
211     p_sys->p_sdp = NULL;
212     p_sys->scheduler = NULL;
213     p_sys->env = NULL;
214     p_sys->ms = NULL;
215     p_sys->rtsp = NULL;
216     p_sys->i_track = 0;
217     p_sys->track   = NULL;
218     p_sys->i_pcr   = 0;
219     p_sys->i_pcr_start = 0;
220     p_sys->i_length = 0;
221     p_sys->i_start = 0;
222     p_sys->p_out_asf = NULL;
223
224
225     if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
226     {
227         msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
228         goto error;
229     }
230     if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
231     {
232         msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
233         goto error;
234     }
235
236     if( p_demux->s == NULL && !strcasecmp( p_demux->psz_access, "rtsp" ) )
237     {
238         char *psz_url;
239         char *psz_options;
240
241         if( ( p_sys->rtsp = RTSPClient::createNew(*p_sys->env, 1/*verbose*/,
242               "VLC Media Player" ) ) == NULL )
243         {
244             msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
245                      p_sys->env->getResultMsg() );
246             goto error;
247         }
248         psz_url = (char*)malloc( strlen( p_demux->psz_path ) + 8 );
249         sprintf( psz_url, "rtsp://%s", p_demux->psz_path );
250
251         psz_options = p_sys->rtsp->sendOptionsCmd( psz_url );
252         if( psz_options )
253             delete [] psz_options;
254
255         p_sdp = (uint8_t*)p_sys->rtsp->describeURL( psz_url,
256                               NULL, var_CreateGetBool( p_demux, "rtsp-kasenna" ) );
257         if( p_sdp == NULL )
258         {
259             msg_Err( p_demux, "describeURL failed (%s)",
260                      p_sys->env->getResultMsg() );
261             free( psz_url );
262             goto error;
263         }
264         free( psz_url );
265
266         /* malloc-ated copy */
267         p_sys->p_sdp = strdup( (char*)p_sdp );
268         delete[] p_sdp;
269         fprintf( stderr, "sdp=%s\n", p_sys->p_sdp );
270     }
271     else if( p_demux->s == NULL && !strcasecmp( p_demux->psz_access, "sdp" ) )
272     {
273         p_sys->p_sdp = strdup( p_demux->psz_path );
274     }
275     else
276     {
277         /* Gather the complete sdp file */
278         i_sdp = 0;
279         i_sdp_max = 1000;
280         p_sdp = (uint8_t*)malloc( i_sdp_max );
281         for( ;; )
282         {
283             int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
284                                       i_sdp_max - i_sdp - 1 );
285
286             if( i_read < 0 )
287             {
288                 msg_Err( p_demux, "failed to read SDP" );
289                 free( p_sys );
290                 return VLC_EGENERIC;
291             }
292
293             i_sdp += i_read;
294
295             if( i_read < i_sdp_max - i_sdp - 1 )
296             {
297                 p_sdp[i_sdp] = '\0';
298                 break;
299             }
300
301             i_sdp_max += 1000;
302             p_sdp = (uint8_t*)realloc( p_sdp, i_sdp_max );
303         }
304         p_sys->p_sdp = (char*)p_sdp;
305
306         msg_Dbg( p_demux, "sdp=%s\n", p_sys->p_sdp );
307     }
308     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
309     {
310         msg_Err( p_demux, "MediaSession::createNew failed" );
311         goto error;
312     }
313
314     b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" );
315
316     /* Initialise each media subsession */
317     iter = new MediaSubsessionIterator( *p_sys->ms );
318     while( ( sub = iter->next() ) != NULL )
319     {
320         unsigned int i_buffer = 0;
321         Boolean bInit;
322
323         /* Value taken from mplayer */
324         if( !strcmp( sub->mediumName(), "audio" ) )
325             i_buffer = 100000;
326         else if( !strcmp( sub->mediumName(), "video" ) )
327             i_buffer = 2000000;
328         else
329             continue;
330
331         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
332             bInit = sub->initiate( 4 ); /* Constant ? */
333         else
334             bInit = sub->initiate();
335
336         if( !bInit )
337         {
338             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
339                       sub->mediumName(), sub->codecName(),
340                       p_sys->env->getResultMsg() );
341         }
342         else
343         {
344             if( sub->rtpSource() )
345             {
346                 int fd = sub->rtpSource()->RTPgs()->socketNum();
347                 /* Increase the buffer size */
348                 increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
349             }
350
351             msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
352                      sub->codecName() );
353
354             /* Issue the SETUP */
355             if( p_sys->rtsp )
356             {
357                 p_sys->rtsp->setupMediaSubsession( *sub, False,
358                                                    b_rtsp_tcp ? True : False );
359             }
360         }
361     }
362
363     if( p_sys->rtsp )
364     {
365         /* The PLAY */
366         if( !p_sys->rtsp->playMediaSession( *p_sys->ms ) )
367         {
368             msg_Err( p_demux, "PLAY failed %s", p_sys->env->getResultMsg() );
369             goto error;
370         }
371     }
372
373     /* Create all es struct */
374     iter->reset();
375     while( ( sub = iter->next() ) != NULL )
376     {
377         live_track_t *tk;
378
379         if( sub->readSource() == NULL )
380         {
381             continue;
382         }
383
384         tk = (live_track_t*)malloc( sizeof( live_track_t ) );
385         tk->p_demux = p_demux;
386         tk->waiting = 0;
387         tk->i_pts   = 0;
388         tk->b_quicktime = VLC_FALSE;
389         tk->b_muxed     = VLC_FALSE;
390         tk->b_asf       = VLC_FALSE;
391         tk->b_rtcp_sync = VLC_FALSE;
392         tk->p_out_muxed = NULL;
393         tk->p_es        = NULL;
394         tk->i_buffer    = 65536;
395         tk->p_buffer    = (uint8_t *)malloc( 65536 );
396
397         /* Value taken from mplayer */
398         if( !strcmp( sub->mediumName(), "audio" ) )
399         {
400             es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
401             tk->fmt.audio.i_channels = sub->numChannels();
402             tk->fmt.audio.i_rate = sub->rtpSource()->timestampFrequency();
403
404             if( !strcmp( sub->codecName(), "MPA" ) ||
405                 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
406                 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
407             {
408                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
409                 tk->fmt.audio.i_rate = 0;
410             }
411             else if( !strcmp( sub->codecName(), "AC3" ) )
412             {
413                 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
414                 tk->fmt.audio.i_rate = 0;
415             }
416             else if( !strcmp( sub->codecName(), "L16" ) )
417             {
418                 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
419                 tk->fmt.audio.i_bitspersample = 16;
420             }
421             else if( !strcmp( sub->codecName(), "L8" ) )
422             {
423                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
424                 tk->fmt.audio.i_bitspersample = 8;
425             }
426             else if( !strcmp( sub->codecName(), "PCMU" ) )
427             {
428                 tk->fmt.i_codec = VLC_FOURCC( 'u', 'l', 'a', 'w' );
429             }
430             else if( !strcmp( sub->codecName(), "PCMA" ) )
431             {
432                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'l', 'a', 'w' );
433             }
434             else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
435             {
436                 unsigned int i_extra;
437                 uint8_t      *p_extra;
438
439                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
440
441                 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
442                                                          i_extra ) ) )
443                 {
444                     tk->fmt.i_extra = i_extra;
445                     tk->fmt.p_extra = malloc( i_extra );
446                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
447                     delete[] p_extra;
448                 }
449             }
450             else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
451             {
452                 unsigned int i_extra;
453                 uint8_t      *p_extra;
454
455                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
456
457                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
458                                                        i_extra ) ) )
459                 {
460                     tk->fmt.i_extra = i_extra;
461                     tk->fmt.p_extra = malloc( i_extra );
462                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
463                     delete[] p_extra;
464                 }
465             }
466             else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
467             {
468                 tk->b_asf = VLC_TRUE;
469                 if( p_sys->p_out_asf == NULL )
470                     p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
471                                                         p_demux->out );
472             }
473         }
474         else if( !strcmp( sub->mediumName(), "video" ) )
475         {
476             es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
477             if( !strcmp( sub->codecName(), "MPV" ) )
478             {
479                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
480             }
481             else if( !strcmp( sub->codecName(), "H263" ) ||
482                      !strcmp( sub->codecName(), "H263-1998" ) ||
483                      !strcmp( sub->codecName(), "H263-2000" ) )
484             {
485                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '3' );
486             }
487             else if( !strcmp( sub->codecName(), "H261" ) )
488             {
489                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '1' );
490             }
491             else if( !strcmp( sub->codecName(), "JPEG" ) )
492             {
493                 tk->fmt.i_codec = VLC_FOURCC( 'M', 'J', 'P', 'G' );
494             }
495             else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
496             {
497                 unsigned int i_extra;
498                 uint8_t      *p_extra;
499
500                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
501
502                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
503                                                        i_extra ) ) )
504                 {
505                     tk->fmt.i_extra = i_extra;
506                     tk->fmt.p_extra = malloc( i_extra );
507                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
508                     delete[] p_extra;
509                 }
510             }
511             else if( !strcmp( sub->codecName(), "X-QT" ) ||
512                      !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
513                      !strcmp( sub->codecName(), "X-QDM" ) ||
514                      !strcmp( sub->codecName(), "X-SV3V-ES" )  ||
515                      !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
516             {
517                 tk->b_quicktime = VLC_TRUE;
518             }
519             else if( !strcmp( sub->codecName(), "MP2T" ) )
520             {
521                 tk->b_muxed = VLC_TRUE;
522                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
523             }
524             else if( !strcmp( sub->codecName(), "MP2P" ) ||
525                      !strcmp( sub->codecName(), "MP1S" ) )
526             {
527                 tk->b_muxed = VLC_TRUE;
528                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
529                                                    p_demux->out );
530             }
531             else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
532             {
533                 tk->b_asf = VLC_TRUE;
534                 if( p_sys->p_out_asf == NULL )
535                     p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
536                                                         p_demux->out );;
537             }
538         }
539
540         if( tk->fmt.i_codec != VLC_FOURCC( 'u', 'n', 'd', 'f' ) )
541         {
542             tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
543         }
544
545         if( sub->rtcpInstance() != NULL )
546         {
547             sub->rtcpInstance()->setByeHandler( StreamClose, tk );
548         }
549
550         if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
551         {
552             tk->readSource = sub->readSource();
553             tk->rtpSource  = sub->rtpSource();
554
555             /* Append */
556             p_sys->track = (live_track_t**)realloc( p_sys->track, sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
557             p_sys->track[p_sys->i_track++] = tk;
558         }
559         else
560         {
561             free( tk );
562         }
563     }
564
565     delete iter;
566
567     if( p_sys->p_out_asf && ParseASF( p_demux ) )
568     {
569         msg_Err( p_demux, "cannot find a usable asf header" );
570         /* TODO Clean tracks */
571         goto error;
572     }
573
574     p_sys->i_length = (mtime_t)(p_sys->ms->playEndTime() * 1000000.0);
575     if( p_sys->i_length < 0 )
576     {
577         p_sys->i_length = 0;
578     }
579     else if( p_sys->i_length > 0 )
580     {
581         /* FIXME */
582         /* p_input->stream.p_selected_area->i_size = 1000;*/ /* needed for now */
583     }
584
585     if( p_sys->i_track <= 0 )
586     {
587         msg_Err( p_demux, "no codec supported, aborting" );
588         goto error;
589     }
590
591     return VLC_SUCCESS;
592
593 error:
594     if( p_sys->p_out_asf )
595     {
596         stream_DemuxDelete( p_sys->p_out_asf );
597     }
598     if( p_sys->ms )
599     {
600         Medium::close( p_sys->ms );
601     }
602     if( p_sys->rtsp )
603     {
604         Medium::close( p_sys->rtsp );
605     }
606     if( p_sys->env )
607     {
608         RECLAIM_ENV(p_sys->env);
609     }
610     if( p_sys->scheduler )
611     {
612         delete p_sys->scheduler;
613     }
614     if( p_sys->p_sdp )
615     {
616         free( p_sys->p_sdp );
617     }
618     free( p_sys );
619     return VLC_EGENERIC;
620 }
621
622 /*****************************************************************************
623  * DemuxClose:
624  *****************************************************************************/
625 static void Close( vlc_object_t *p_this )
626 {
627     demux_t *p_demux = (demux_t*)p_this;
628     demux_sys_t *p_sys = p_demux->p_sys;
629     int i;
630
631     for( i = 0; i < p_sys->i_track; i++ )
632     {
633         live_track_t *tk = p_sys->track[i];
634
635         if( tk->b_muxed ) stream_DemuxDelete( tk->p_out_muxed );
636         free( tk->p_buffer );
637         free( tk );
638     }
639
640     if( p_sys->i_track ) free( p_sys->track );
641     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
642
643     if( p_sys->rtsp && p_sys->ms )
644     {
645         /* TEARDOWN */
646         p_sys->rtsp->teardownMediaSession( *p_sys->ms );
647     }
648
649     Medium::close( p_sys->ms );
650
651     if( p_sys->rtsp ) Medium::close( p_sys->rtsp );
652     if( p_sys->env ) RECLAIM_ENV(p_sys->env);
653     if( p_sys->scheduler ) delete p_sys->scheduler;
654     if( p_sys->p_sdp ) free( p_sys->p_sdp );
655     free( p_sys );
656 }
657
658 /*****************************************************************************
659  * Demux:
660  *****************************************************************************/
661 static int Demux( demux_t *p_demux )
662 {
663     demux_sys_t    *p_sys = p_demux->p_sys;
664     TaskToken      task;
665
666     vlc_bool_t      b_send_pcr = VLC_TRUE;
667     mtime_t         i_pcr = 0;
668     int             i;
669
670     for( i = 0; i < p_sys->i_track; i++ )
671     {
672         live_track_t *tk = p_sys->track[i];
673
674         if( tk->b_asf || tk->b_muxed )
675             b_send_pcr = VLC_FALSE;
676
677         if( i_pcr == 0 )
678         {
679             i_pcr = tk->i_pts;
680         }
681         else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
682         {
683             i_pcr = tk->i_pts ;
684         }
685     }
686     if( i_pcr != p_sys->i_pcr && i_pcr > 0 )
687     {
688         p_sys->i_pcr = i_pcr;
689
690         if( b_send_pcr )
691             es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pcr );
692         if( p_sys->i_pcr_start <= 0 || p_sys->i_pcr_start > i_pcr ||
693             ( p_sys->i_length > 0 && i_pcr - p_sys->i_pcr_start > p_sys->i_length ) )
694         {
695             p_sys->i_pcr_start = i_pcr;
696         }
697     }
698
699     /* First warm we want to read data */
700     p_sys->event = 0;
701     for( i = 0; i < p_sys->i_track; i++ )
702     {
703         live_track_t *tk = p_sys->track[i];
704
705         if( tk->waiting == 0 )
706         {
707             tk->waiting = 1;
708             tk->readSource->getNextFrame( tk->p_buffer, tk->i_buffer,
709                                           StreamRead, tk, StreamClose, tk );
710         }
711     }
712     /* Create a task that will be called if we wait more than 300ms */
713     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
714
715     /* Do the read */
716     p_sys->scheduler->doEventLoop( &p_sys->event );
717
718     /* remove the task */
719     p_sys->scheduler->unscheduleDelayedTask( task );
720
721     /* Check for gap in pts value */
722     for( i = 0; i < p_sys->i_track; i++ )
723     {
724         live_track_t *tk = p_sys->track[i];
725
726         if( !tk->b_muxed && !tk->b_rtcp_sync &&
727             tk->rtpSource->hasBeenSynchronizedUsingRTCP() )
728         {
729             msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
730
731             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
732             tk->b_rtcp_sync = VLC_TRUE;
733
734             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
735             tk->i_pts = 0;
736             p_sys->i_pcr_start = 0;
737             p_sys->i_pcr = 0;
738             i_pcr = 0;
739         }
740     }
741
742     return p_demux->b_error ? 0 : 1;
743 }
744
745 /*****************************************************************************
746  * Control:
747  *****************************************************************************/
748 static int Control( demux_t *p_demux, int i_query, va_list args )
749 {
750     demux_sys_t *p_sys = p_demux->p_sys;
751     int64_t *pi64;
752     double  *pf, f;
753     vlc_bool_t *pb, b_bool;
754
755     switch( i_query )
756     {
757         case DEMUX_GET_TIME:
758             pi64 = (int64_t*)va_arg( args, int64_t * );
759             *pi64 = p_sys->i_pcr - p_sys->i_pcr_start + p_sys->i_start;
760             return VLC_SUCCESS;
761
762         case DEMUX_GET_LENGTH:
763             pi64 = (int64_t*)va_arg( args, int64_t * );
764             *pi64 = p_sys->i_length;
765             return VLC_SUCCESS;
766
767         case DEMUX_GET_POSITION:
768             pf = (double*)va_arg( args, double* );
769             if( p_sys->i_length > 0 )
770             {
771                 *pf = (double)( p_sys->i_pcr - p_sys->i_pcr_start +
772                                 p_sys->i_start ) / (double)(p_sys->i_length);
773             }
774             else
775             {
776                 *pf = 0;
777             }
778             return VLC_SUCCESS;
779
780         case DEMUX_SET_POSITION:
781         {
782             float time;
783
784             f = (double)va_arg( args, double );
785             time = f * (double)p_sys->i_length / 1000000.0;   /* in second */
786
787             if( p_sys->rtsp && p_sys->i_length > 0 )
788             {
789                 MediaSubsessionIterator *iter =
790                     new MediaSubsessionIterator( *p_sys->ms );
791                 MediaSubsession *sub;
792                 int i;
793
794                 while( ( sub = iter->next() ) != NULL )
795                 {
796                     p_sys->rtsp->playMediaSubsession( *sub, time );
797                 }
798                 delete iter;
799                 p_sys->i_start = (mtime_t)(f * (double)p_sys->i_length);
800                 p_sys->i_pcr_start = 0;
801                 p_sys->i_pcr       = 0;
802                 
803                 for( i = 0; i < p_sys->i_track; i++ )
804                 {
805                     p_sys->track[i]->i_pts = 0;
806                 }
807
808                 return VLC_SUCCESS;
809             }
810             return VLC_SUCCESS;
811         }
812
813         /* Special for access_demux */
814         case DEMUX_CAN_PAUSE:
815             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
816             if( p_sys->rtsp && p_sys->i_length )
817                 /* Not always true, but will be handled in SET_PAUSE_STATE */
818                 *pb = VLC_TRUE;
819             else
820                 *pb = VLC_FALSE;
821             return VLC_SUCCESS;
822
823         case DEMUX_CAN_CONTROL_PACE:
824             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
825             *pb = VLC_FALSE;
826             return VLC_SUCCESS;
827
828         case DEMUX_SET_PAUSE_STATE:
829             double d_npt;
830             MediaSubsessionIterator *iter;
831             MediaSubsession *sub;
832
833             d_npt = ( (double)( p_sys->i_pcr - p_sys->i_pcr_start +
834                                 p_sys->i_start ) ) / 1000000.00;
835
836             b_bool = (vlc_bool_t)va_arg( args, vlc_bool_t );
837             if( p_sys->rtsp == NULL )
838                 return VLC_EGENERIC;
839
840             iter = new MediaSubsessionIterator( *p_sys->ms );
841             while( ( sub = iter->next() ) != NULL )
842             {
843                 if( ( b_bool && !p_sys->rtsp->pauseMediaSubsession( *sub ) ) ||
844                     ( !b_bool && !p_sys->rtsp->playMediaSubsession( *sub,
845                       d_npt > 0 ? d_npt : -1 ) ) )
846                 {
847                     delete iter;
848                     return VLC_EGENERIC;
849                 }
850             }
851             delete iter;
852 #if 0
853             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
854             for( i = 0; i < p_sys->i_track; i++ )
855             {
856                 p_sys->track[i]->i_pts = 0;
857             }
858             p_sys->i_pcr_start = 0; /* FIXME Wrong */
859             p_sys->i_pcr = 0;
860 #endif
861             return VLC_SUCCESS;
862
863         case DEMUX_GET_TITLE_INFO:
864         case DEMUX_SET_TITLE:
865         case DEMUX_SET_SEEKPOINT:
866             return VLC_EGENERIC;
867
868         case DEMUX_GET_PTS_DELAY:
869             pi64 = (int64_t*)va_arg( args, int64_t * );
870             *pi64 = (int64_t)var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
871             return VLC_SUCCESS;
872
873         default:
874             return VLC_EGENERIC;
875     }
876 }
877
878 /*****************************************************************************
879  *
880  *****************************************************************************/
881 static void StreamRead( void *p_private, unsigned int i_size,
882                         unsigned int i_truncated_bytes, struct timeval pts,
883                         unsigned int duration )
884 {
885     live_track_t   *tk = (live_track_t*)p_private;
886     demux_t        *p_demux = tk->p_demux;
887     demux_sys_t    *p_sys = p_demux->p_sys;
888     block_t        *p_block;
889
890     mtime_t i_pts = (uint64_t)pts.tv_sec * UI64C(1000000) +
891         (uint64_t)pts.tv_usec;
892
893     /* XXX Beurk beurk beurk Avoid having negative value XXX */
894     i_pts &= UI64C(0x00ffffffffffffff);
895
896     if( tk->b_quicktime && tk->p_es == NULL )
897     {
898         QuickTimeGenericRTPSource *qtRTPSource =
899             (QuickTimeGenericRTPSource*)tk->rtpSource;
900         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
901         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
902
903         if( qtState.sdAtomSize < 16 + 32 )
904         {
905             /* invalid */
906             p_sys->event = 0xff;
907             tk->waiting = 0;
908             return;
909         }
910         tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
911         tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
912         tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
913
914         tk->fmt.i_extra        = qtState.sdAtomSize - 16;
915         tk->fmt.p_extra        = malloc( tk->fmt.i_extra );
916         memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
917
918         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
919     }
920
921 #if 0
922     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
923              i_size,
924              pts.tv_sec * 1000000LL + pts.tv_usec );
925 #endif
926
927     /* grow buffer if it looks like buffer is too small, but don't eat
928      * up all the memory on strange streams */
929     if( i_truncated_bytes > 0 && tk->i_buffer < 2000000 )
930     {
931         void *p_tmp;
932         msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
933         msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
934         tk->i_buffer *= 2;
935         p_tmp = realloc( tk->p_buffer, tk->i_buffer );
936         if (p_tmp == NULL)
937         {
938             msg_Warn( p_demux, "realloc failed" );
939         }
940         else
941         {
942             tk->p_buffer = (uint8_t*)p_tmp;
943         }
944     }
945     if( i_size > tk->i_buffer )
946     {
947         msg_Warn( p_demux, "buffer overflow" );
948     }
949     /* FIXME could i_size be > buffer size ? */
950     if( tk->fmt.i_codec == VLC_FOURCC('h','2','6','1') )
951     {
952 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1081468800
953         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->rtpSource;
954         uint32_t header = h261Source->lastSpecialHeader();
955 #else
956         uint32_t header = 0;
957         msg_Warn( p_demux, "need livemedia library >= \"2004.04.09\"" );
958 #endif
959         p_block = block_New( p_demux, i_size + 4 );
960         memcpy( p_block->p_buffer, &header, 4 );
961         memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
962     }
963     else if( tk->b_asf )
964     {
965         int i_copy = __MIN( p_sys->asfh.i_min_data_packet_size, (int)i_size );
966         p_block = block_New( p_demux, p_sys->asfh.i_min_data_packet_size );
967
968         memcpy( p_block->p_buffer, tk->p_buffer, i_copy );
969     }
970     else
971     {
972         p_block = block_New( p_demux, i_size );
973         memcpy( p_block->p_buffer, tk->p_buffer, i_size );
974     }
975     if( tk->fmt.i_codec == VLC_FOURCC('h','2','6','1') &&
976         tk->rtpSource->curPacketMarkerBit() )
977     {
978         p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
979     }
980     //p_block->i_rate = p_input->stream.control.i_rate;
981
982     if( i_pts != tk->i_pts && !tk->b_muxed )
983     {
984         p_block->i_dts = i_pts;
985         p_block->i_pts = i_pts;
986     }
987     //fprintf( stderr, "tk -> dpts=%lld\n", i_pts - tk->i_pts );
988
989     if( tk->b_muxed )
990     {
991         stream_DemuxSend( tk->p_out_muxed, p_block );
992     }
993     else if( tk->b_asf )
994     {
995         stream_DemuxSend( p_sys->p_out_asf, p_block );
996     }
997     else
998     {
999         es_out_Send( p_demux->out, tk->p_es, p_block );
1000     }
1001
1002     /* warm that's ok */
1003     p_sys->event = 0xff;
1004
1005     /* we have read data */
1006     tk->waiting = 0;
1007
1008     if( i_pts > 0 && !tk->b_muxed )
1009     {
1010         tk->i_pts = i_pts;
1011     }
1012 }
1013
1014 /*****************************************************************************
1015  *
1016  *****************************************************************************/
1017 static void StreamClose( void *p_private )
1018 {
1019     live_track_t   *tk = (live_track_t*)p_private;
1020     demux_t        *p_demux = tk->p_demux;
1021     demux_sys_t    *p_sys = p_demux->p_sys;
1022
1023     fprintf( stderr, "StreamClose\n" );
1024
1025     p_sys->event = 0xff;
1026     p_demux->b_error = VLC_TRUE;
1027 }
1028
1029
1030 /*****************************************************************************
1031  *
1032  *****************************************************************************/
1033 static void TaskInterrupt( void *p_private )
1034 {
1035     demux_t *p_demux = (demux_t*)p_private;
1036
1037     fprintf( stderr, "TaskInterrupt\n" );
1038
1039     /* Avoid lock */
1040     p_demux->p_sys->event = 0xff;
1041 }
1042
1043 /*****************************************************************************
1044  *
1045  *****************************************************************************/
1046 static int b64_decode( char *dest, char *src );
1047
1048 static int ParseASF( demux_t *p_demux )
1049 {
1050     demux_sys_t    *p_sys = p_demux->p_sys;
1051
1052     const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1053     char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1054     char *psz_end;
1055     block_t *p_header;
1056
1057     /* Parse the asf header */
1058     if( psz_asf == NULL )
1059         return VLC_EGENERIC;
1060
1061     psz_asf += strlen( psz_marker );
1062     psz_asf = strdup( psz_asf );    /* Duplicate it */
1063     psz_end = strchr( psz_asf, '\n' );
1064
1065     while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1066         *psz_end-- = '\0';
1067
1068     if( psz_asf >= psz_end )
1069     {
1070         free( psz_asf );
1071         return VLC_EGENERIC;
1072     }
1073
1074     /* Always smaller */
1075     p_header = block_New( p_demux, psz_end - psz_asf );
1076     p_header->i_buffer = b64_decode( (char*)p_header->p_buffer, psz_asf );
1077     fprintf( stderr, "Size=%d Hdrb64=%s\n", p_header->i_buffer, psz_asf );
1078     if( p_header->i_buffer <= 0 )
1079     {
1080         free( psz_asf );
1081         return VLC_EGENERIC;
1082     }
1083
1084     /* Parse it to get packet size */
1085     E_(asf_HeaderParse)( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
1086
1087     /* Send it to demuxer */
1088     stream_DemuxSend( p_sys->p_out_asf, p_header );
1089
1090     free( psz_asf );
1091     return VLC_SUCCESS;
1092 }
1093 /*char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";*/
1094 static int b64_decode( char *dest, char *src )
1095 {
1096     const char *dest_start = dest;
1097     int  i_level;
1098     int  last = 0;
1099     int  b64[256] = {
1100         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
1101         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
1102         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
1103         52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
1104         -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
1105         15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
1106         -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
1107         41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
1108         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
1109         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
1110         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
1111         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
1112         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
1113         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
1114         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
1115         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
1116         };
1117
1118     for( i_level = 0; *src != '\0'; src++ )
1119     {
1120         int  c;
1121
1122         c = b64[(unsigned int)*src];
1123         if( c == -1 )
1124         {
1125             continue;
1126         }
1127
1128         switch( i_level )
1129         {
1130             case 0:
1131                 i_level++;
1132                 break;
1133             case 1:
1134                 *dest++ = ( last << 2 ) | ( ( c >> 4)&0x03 );
1135                 i_level++;
1136                 break;
1137             case 2:
1138                 *dest++ = ( ( last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
1139                 i_level++;
1140                 break;
1141             case 3:
1142                 *dest++ = ( ( last &0x03 ) << 6 ) | c;
1143                 i_level = 0;
1144         }
1145         last = c;
1146     }
1147
1148     *dest = '\0';
1149
1150     return dest - dest_start;
1151 }