]> git.sesse.net Git - vlc/blob - modules/demux/livedotcom.cpp
4a8584c1ab4cbffddaef975a0699e8409e73fa3f
[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 miliseconds 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         /* FIXME psz_options -> delete or free */
420         free( psz_url );
421     }
422     if( ( p_sys->ms = MediaSession::createNew(*p_sys->env, p_sys->p_sdp ) ) == NULL )
423     {
424         msg_Err( p_demux, "MediaSession::createNew failed" );
425         goto error;
426     }
427
428     var_Create( p_demux, "rtsp-tcp", VLC_VAR_BOOL|VLC_VAR_DOINHERIT );
429     var_Get( p_demux, "rtsp-tcp", &val );
430
431     /* Initialise each media subsession */
432     iter = new MediaSubsessionIterator( *p_sys->ms );
433     while( ( sub = iter->next() ) != NULL )
434     {
435         unsigned int i_buffer = 0;
436
437         /* Value taken from mplayer */
438         if( !strcmp( sub->mediumName(), "audio" ) )
439         {
440             i_buffer = 100000;
441         }
442         else if( !strcmp( sub->mediumName(), "video" ) )
443         {
444             i_buffer = 2000000;
445         }
446         else
447         {
448             continue;
449         }
450
451         if( !sub->initiate() )
452         {
453             msg_Warn( p_demux, "RTP subsession '%s/%s' failed(%s)", sub->mediumName(), sub->codecName(), p_sys->env->getResultMsg() );
454         }
455         else
456         {
457             int fd = sub->rtpSource()->RTPgs()->socketNum();
458
459             msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(), sub->codecName() );
460
461             /* Increase the buffer size */
462             increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
463             /* Issue the SETUP */
464             if( p_sys->rtsp )
465             {
466                 p_sys->rtsp->setupMediaSubsession( *sub, False, val.b_bool ? True : False );
467             }
468         }
469     }
470
471     if( p_sys->rtsp )
472     {
473         /* The PLAY */
474         if( !p_sys->rtsp->playMediaSession( *p_sys->ms ) )
475         {
476             msg_Err( p_demux, "PLAY failed %s", p_sys->env->getResultMsg() );
477             goto error;
478         }
479     }
480
481     /* Create all es struct */
482     iter->reset();
483     while( ( sub = iter->next() ) != NULL )
484     {
485         live_track_t *tk;
486
487         if( sub->readSource() == NULL )
488         {
489             continue;
490         }
491
492         tk = (live_track_t*)malloc( sizeof( live_track_t ) );
493         tk->p_demux = p_demux;
494         tk->waiting = 0;
495         tk->i_pts   = 0;
496         tk->b_quicktime = VLC_FALSE;
497         tk->b_muxed     = VLC_FALSE;
498         tk->b_rtcp_sync = VLC_FALSE;
499         tk->p_out_muxed = NULL;
500         tk->p_es        = NULL;
501
502         /* Value taken from mplayer */
503         if( !strcmp( sub->mediumName(), "audio" ) )
504         {
505             es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC( 'u', 'n', 'd', 'f' ) );
506             tk->fmt.audio.i_channels = sub->numChannels();
507             tk->fmt.audio.i_rate = sub->rtpSource()->timestampFrequency();
508
509             if( !strcmp( sub->codecName(), "MPA" ) ||
510                 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
511                 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
512             {
513                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
514                 tk->fmt.audio.i_rate = 0;
515             }
516             else if( !strcmp( sub->codecName(), "AC3" ) )
517             {
518                 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
519                 tk->fmt.audio.i_rate = 0;
520             }
521             else if( !strcmp( sub->codecName(), "L16" ) )
522             {
523                 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
524                 tk->fmt.audio.i_bitspersample = 16;
525             }
526             else if( !strcmp( sub->codecName(), "L8" ) )
527             {
528                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
529                 tk->fmt.audio.i_bitspersample = 8;
530             }
531             else if( !strcmp( sub->codecName(), "PCMU" ) )
532             {
533                 tk->fmt.i_codec = VLC_FOURCC( 'u', 'l', 'a', 'w' );
534             }
535             else if( !strcmp( sub->codecName(), "PCMA" ) )
536             {
537                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'l', 'a', 'w' );
538             }
539             else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
540             {
541                 unsigned int i_extra;
542                 uint8_t      *p_extra;
543
544                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
545
546                 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(), i_extra ) ) )
547                 {
548                     tk->fmt.i_extra = i_extra;
549                     tk->fmt.p_extra = malloc( i_extra );
550                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
551                     delete[] p_extra;
552                 }
553             }
554             else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
555             {
556                 unsigned int i_extra;
557                 uint8_t      *p_extra;
558
559                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
560
561                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(), i_extra ) ) )
562                 {
563                     tk->fmt.i_extra = i_extra;
564                     tk->fmt.p_extra = malloc( i_extra );
565                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
566                     delete[] p_extra;
567                 }
568             }
569         }
570         else if( !strcmp( sub->mediumName(), "video" ) )
571         {
572             es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC( 'u', 'n', 'd', 'f' ) );
573             if( !strcmp( sub->codecName(), "MPV" ) )
574             {
575                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
576             }
577             else if( !strcmp( sub->codecName(), "H263" ) ||
578                      !strcmp( sub->codecName(), "H263-1998" ) )
579             {
580                 tk->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '3' );
581             }
582             else if( !strcmp( sub->codecName(), "H261" ) )
583             {
584                 tk->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '1' );
585             }
586             else if( !strcmp( sub->codecName(), "JPEG" ) )
587             {
588                 tk->fmt.i_codec = VLC_FOURCC( 'M', 'J', 'P', 'G' );
589             }
590             else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
591             {
592                 unsigned int i_extra;
593                 uint8_t      *p_extra;
594
595                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
596
597                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(), i_extra ) ) )
598                 {
599                     tk->fmt.i_extra = i_extra;
600                     tk->fmt.p_extra = malloc( i_extra );
601                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
602                     delete[] p_extra;
603                 }
604             }
605             else if( !strcmp( sub->codecName(), "X-QT" ) || !strcmp( sub->codecName(), "X-QUICKTIME" ) )
606             {
607                 tk->b_quicktime = VLC_TRUE;
608             }
609             else if( !strcmp( sub->codecName(), "MP2T" ) )
610             {
611                 tk->b_muxed = VLC_TRUE;
612                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts2", p_demux->out );
613             }
614             else if( !strcmp( sub->codecName(), "MP2P" ) || !strcmp( sub->codecName(), "MP1S" ) )   /* FIXME check MP1S */
615             {
616                 tk->b_muxed = VLC_TRUE;
617                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps2", p_demux->out );
618             }
619         }
620
621         if( tk->fmt.i_codec != VLC_FOURCC( 'u', 'n', 'd', 'f' ) )
622         {
623             tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
624         }
625
626         if( tk->p_es || tk->b_quicktime || tk->b_muxed )
627         {
628             tk->readSource = sub->readSource();
629             tk->rtpSource  = sub->rtpSource();
630
631             /* Append */
632             p_sys->track = (live_track_t**)realloc( p_sys->track, sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
633             p_sys->track[p_sys->i_track++] = tk;
634         }
635         else
636         {
637             free( tk );
638         }
639     }
640
641     delete iter;
642
643     p_sys->i_length = (mtime_t)(p_sys->ms->playEndTime() * 1000000.0);
644     if( p_sys->i_length < 0 )
645     {
646         p_sys->i_length = 0;
647     }
648     else if( p_sys->i_length > 0 )
649     {
650         /* FIXME */
651         /* p_input->stream.p_selected_area->i_size = 1000;*/ /* needed for now */
652     }
653
654     if( p_sys->i_track <= 0 )
655     {
656         msg_Err( p_demux, "no codec supported, aborting" );
657         goto error;
658     }
659
660     return VLC_SUCCESS;
661
662 error:
663     if( p_sys->ms )
664     {
665         Medium::close( p_sys->ms );
666     }
667     if( p_sys->rtsp )
668     {
669         Medium::close( p_sys->rtsp );
670     }
671     if( p_sys->env )
672     {
673         delete p_sys->env;
674     }
675     if( p_sys->scheduler )
676     {
677         delete p_sys->scheduler;
678     }
679     if( p_sys->p_sdp )
680     {
681         free( p_sys->p_sdp );
682     }
683     free( p_sys );
684     return VLC_EGENERIC;
685 }
686
687
688
689 /*****************************************************************************
690  * DemuxClose:
691  *****************************************************************************/
692 static void DemuxClose( vlc_object_t *p_this )
693 {
694     demux_t *p_demux = (demux_t*)p_this;
695     demux_sys_t    *p_sys = p_demux->p_sys;
696     int            i;
697
698     for( i = 0; i < p_sys->i_track; i++ )
699     {
700         live_track_t *tk = p_sys->track[i];
701
702         if( tk->b_muxed )
703         {
704             stream_DemuxDelete( tk->p_out_muxed );
705         }
706
707         free( tk );
708     }
709     if( p_sys->i_track )
710     {
711         free( p_sys->track );
712     }
713
714     if( p_sys->rtsp && p_sys->ms )
715     {
716         /* TEARDOWN */
717         p_sys->rtsp->teardownMediaSession( *p_sys->ms );
718     }
719     Medium::close( p_sys->ms );
720     if( p_sys->rtsp )
721     {
722         Medium::close( p_sys->rtsp );
723     }
724
725     if( p_sys->env )
726     {
727         delete p_sys->env;
728     }
729     if( p_sys->scheduler )
730     {
731         delete p_sys->scheduler;
732     }
733     if( p_sys->p_sdp )
734     {
735         free( p_sys->p_sdp );
736     }
737     free( p_sys );
738 }
739
740
741 static void StreamRead( void *p_private, unsigned int i_size, struct timeval pts );
742 static void StreamClose( void *p_private );
743 static void TaskInterrupt( void *p_private );
744
745 /*****************************************************************************
746  * Demux:
747  *****************************************************************************/
748 static int Demux( demux_t *p_demux )
749 {
750     demux_sys_t    *p_sys = p_demux->p_sys;
751     TaskToken      task;
752
753     mtime_t         i_pcr = 0;
754     int             i;
755
756     for( i = 0; i < p_sys->i_track; i++ )
757     {
758         live_track_t *tk = p_sys->track[i];
759
760         if( i_pcr == 0 )
761         {
762             i_pcr = tk->i_pts;
763         }
764         else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
765         {
766             i_pcr = tk->i_pts ;
767         }
768     }
769     if( i_pcr != p_sys->i_pcr && i_pcr > 0 )
770     {
771         p_sys->i_pcr = i_pcr;
772
773         es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pcr );
774         if( p_sys->i_pcr_start <= 0 || p_sys->i_pcr_start > i_pcr )
775         {
776             p_sys->i_pcr_start = i_pcr;
777         }
778     }
779
780     /* First warm we want to read data */
781     p_sys->event = 0;
782     for( i = 0; i < p_sys->i_track; i++ )
783     {
784         live_track_t *tk = p_sys->track[i];
785
786         if( tk->waiting == 0 )
787         {
788             tk->waiting = 1;
789             tk->readSource->getNextFrame( tk->buffer, 65536,
790                                           StreamRead, tk,
791                                           StreamClose, tk );
792         }
793     }
794     /* Create a task that will be called if we wait more than 300ms */
795     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
796
797     /* Do the read */
798     p_sys->scheduler->doEventLoop( &p_sys->event );
799
800     /* remove the task */
801     p_sys->scheduler->unscheduleDelayedTask( task );
802
803     /* Check for gap in pts value */
804     for( i = 0; i < p_sys->i_track; i++ )
805     {
806         live_track_t *tk = p_sys->track[i];
807
808         if( !tk->b_muxed && !tk->b_rtcp_sync && tk->rtpSource->hasBeenSynchronizedUsingRTCP() )
809         {
810             msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
811
812             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
813             tk->b_rtcp_sync = VLC_TRUE;
814
815             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
816             tk->i_pts = 0;
817             p_sys->i_pcr_start = 0;
818             p_sys->i_pcr = 0;
819             i_pcr = 0;
820         }
821     }
822
823     return p_demux->b_error ? 0 : 1;
824 }
825
826 /*****************************************************************************
827  * Control:
828  *****************************************************************************/
829 static int Control( demux_t *p_demux, int i_query, va_list args )
830 {
831     demux_sys_t *p_sys = p_demux->p_sys;
832     int64_t *pi64;
833     double  *pf, f;
834
835     switch( i_query )
836     {
837         case DEMUX_GET_TIME:
838             pi64 = (int64_t*)va_arg( args, int64_t * );
839             *pi64 = p_sys->i_pcr - p_sys->i_pcr_start + p_sys->i_start;
840             return VLC_SUCCESS;
841
842         case DEMUX_GET_LENGTH:
843             pi64 = (int64_t*)va_arg( args, int64_t * );
844             *pi64 = p_sys->i_length;
845             return VLC_SUCCESS;
846
847         case DEMUX_GET_POSITION:
848             pf = (double*)va_arg( args, double* );
849             if( p_sys->i_length > 0 )
850             {
851                 *pf = (double)( p_sys->i_pcr - p_sys->i_pcr_start + p_sys->i_start)/
852                       (double)(p_sys->i_length);
853             }
854             else
855             {
856                 *pf = 0;
857             }
858             return VLC_SUCCESS;
859
860         case DEMUX_SET_POSITION:
861         {
862             float time;
863
864             f = (double)va_arg( args, double );
865             time = f * (double)p_sys->i_length / 1000000.0;   /* in second */
866
867             if( p_sys->rtsp && p_sys->i_length > 0 )
868             {
869                 MediaSubsessionIterator *iter = new MediaSubsessionIterator( *p_sys->ms );
870                 MediaSubsession         *sub;
871                 int i;
872
873                 while( ( sub = iter->next() ) != NULL )
874                 {
875                     p_sys->rtsp->playMediaSubsession( *sub, time );
876                 }
877                 delete iter;
878                 p_sys->i_start = (mtime_t)(f * (double)p_sys->i_length);
879                 p_sys->i_pcr_start = 0;
880                 p_sys->i_pcr       = 0;
881                 for( i = 0; i < p_sys->i_track; i++ )
882                 {
883                     p_sys->track[i]->i_pts = 0;
884                 }
885                 return VLC_SUCCESS;
886             }
887             return VLC_EGENERIC;
888         }
889
890         default:
891             return VLC_EGENERIC;
892     }
893 }
894
895 /*****************************************************************************
896  *
897  *****************************************************************************/
898 static void StreamRead( void *p_private, unsigned int i_size, struct timeval pts )
899 {
900     live_track_t   *tk = (live_track_t*)p_private;
901     demux_t        *p_demux = tk->p_demux;
902     demux_sys_t    *p_sys = p_demux->p_sys;
903     block_t        *p_block;
904
905     mtime_t i_pts = (uint64_t)pts.tv_sec * UI64C(1000000) + (uint64_t)pts.tv_usec;
906
907     /* XXX Beurk beurk beurk Avoid having negative value XXX */
908     i_pts &= UI64C(0x00ffffffffffffff);
909
910     if( tk->b_quicktime && tk->p_es == NULL )
911     {
912         QuickTimeGenericRTPSource *qtRTPSource = (QuickTimeGenericRTPSource*)tk->rtpSource;
913         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
914         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
915
916         if( qtState.sdAtomSize < 16 + 32 )
917         {
918             /* invalid */
919             p_sys->event = 0xff;
920             tk->waiting = 0;
921             return;
922         }
923         tk->fmt.i_codec = VLC_FOURCC( sdAtom[0], sdAtom[1], sdAtom[2], sdAtom[3] );
924         tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
925         tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
926
927         tk->fmt.i_extra        = qtState.sdAtomSize - 16;
928         tk->fmt.p_extra        = malloc( tk->fmt.i_extra );
929         memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
930
931         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
932     }
933
934 #if 0
935     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
936              i_size,
937              pts.tv_sec * 1000000LL + pts.tv_usec );
938 #endif
939     if( tk->fmt.i_codec == VLC_FOURCC('h','2','6','1') )
940     {
941         i_size += 4;        
942     }
943     
944     if( i_size > 65536 )
945     {
946         msg_Warn( p_demux, "buffer overflow" );
947     }
948     /* FIXME could i_size be > buffer size ? */
949     p_block = block_New( p_demux, i_size );
950     if( tk->fmt.i_codec == VLC_FOURCC('h','2','6','1') )
951     {
952         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->rtpSource;
953         uint32_t header = h261Source->lastSpecialHeader();
954         memcpy( p_block->p_buffer, &header, 4 );
955         memcpy( p_block->p_buffer + 4, tk->buffer, i_size );        
956     }
957     else
958     {
959         memcpy( p_block->p_buffer, tk->buffer, i_size );
960     }
961     if( tk->rtpSource->curPacketMarkerBit() )
962     {        
963         p_block->i_flags |= BLOCK_FLAG_HEADER;
964     }
965     //p_block->i_rate = p_input->stream.control.i_rate;
966
967     if( i_pts != tk->i_pts && !tk->b_muxed )
968     {
969         p_block->i_dts = i_pts;
970         p_block->i_pts = i_pts;
971     }
972     //fprintf( stderr, "tk -> dpts=%lld\n", i_pts - tk->i_pts );
973
974     if( tk->b_muxed )
975     {
976         stream_DemuxSend( tk->p_out_muxed, p_block );
977     }
978     else
979     {
980         es_out_Send( p_demux->out, tk->p_es, p_block );
981     }
982
983     /* warm that's ok */
984     p_sys->event = 0xff;
985
986     /* we have read data */
987     tk->waiting = 0;
988
989     if( i_pts > 0 && !tk->b_muxed )
990     {
991         tk->i_pts = i_pts;
992     }
993 }
994
995 /*****************************************************************************
996  *
997  *****************************************************************************/
998 static void StreamClose( void *p_private )
999 {
1000     live_track_t   *tk = (live_track_t*)p_private;
1001     demux_t        *p_demux = tk->p_demux;
1002     demux_sys_t    *p_sys = p_demux->p_sys;
1003
1004     fprintf( stderr, "StreamClose\n" );
1005
1006     p_sys->event = 0xff;
1007     p_demux->b_error = VLC_TRUE;
1008 }
1009
1010
1011 /*****************************************************************************
1012  *
1013  *****************************************************************************/
1014 static void TaskInterrupt( void *p_private )
1015 {
1016     demux_t *p_demux = (demux_t*)p_private;
1017
1018     fprintf( stderr, "TaskInterrupt\n" );
1019
1020     /* Avoid lock */
1021     p_demux->p_sys->event = 0xff;
1022 }
1023