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