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