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