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