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