]> git.sesse.net Git - vlc/blob - modules/demux/live555.cpp
live555.cpp: Add support for quicktime specific audio
[vlc] / modules / demux / live555.cpp
1 /*****************************************************************************
2  * live555.cpp : LIVE555 Streaming Media support.
3  *****************************************************************************
4  * Copyright (C) 2003-2006 the VideoLAN team
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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #include <vlc/vlc.h>
29 #include <stdlib.h>                                      /* malloc(), free() */
30 #include <string.h>
31
32 #include <vlc_demux.h>
33 #include <vlc_interface.h>
34 #include <vlc_network.h>
35
36 #include <iostream>
37
38 #if defined( WIN32 )
39 #   include <winsock2.h>
40 #endif
41
42 #include "BasicUsageEnvironment.hh"
43 #include "GroupsockHelper.hh"
44 #include "liveMedia.hh"
45
46 extern "C" {
47 #include "../access/mms/asf.h"  /* Who said ugly ? */
48 }
49
50 #if (LIVEMEDIA_LIBRARY_VERSION_INT < 1089936000)
51 #define RECLAIM_ENV(env) delete (env)
52 #else
53 #define RECLAIM_ENV(env) (env)->reclaim()
54 #endif
55
56 using namespace std;
57
58 /*****************************************************************************
59  * Module descriptor
60  *****************************************************************************/
61 static int  Open ( vlc_object_t * );
62 static void Close( vlc_object_t * );
63
64 #define CACHING_TEXT N_("Caching value (ms)")
65 #define CACHING_LONGTEXT N_( \
66     "Allows you to modify the default caching value for RTSP streams. This " \
67     "value should be set in millisecond units." )
68
69 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
70 #define KASENNA_LONGTEXT N_( "Kasenna servers use an old and unstandard " \
71     "dialect of RTSP. When you set this parameter, VLC will try this dialect "\
72     "for communication. In this mode you cannot connect to normal RTSP servers." )
73
74 #define USER_TEXT N_("RTSP user name")
75 #define USER_LONGTEXT N_("Allows you to modify the user name that will " \
76     "be used for authenticating the connection.")
77 #define PASS_TEXT N_("RTSP password")
78 #define PASS_LONGTEXT N_("Allows you to modify the password that will be " \
79     "used for the connection.")
80
81 vlc_module_begin();
82     set_description( _("RTP/RTSP/SDP demuxer (using Live555)" ) );
83     set_capability( "demux2", 50 );
84     set_shortname( "RTP/RTSP");
85     set_callbacks( Open, Close );
86     add_shortcut( "live" );
87     add_shortcut( "livedotcom" );
88     set_category( CAT_INPUT );
89     set_subcategory( SUBCAT_INPUT_DEMUX );
90
91     add_submodule();
92         set_description( _("RTSP/RTP access and demux") );
93         add_shortcut( "rtsp" );
94         add_shortcut( "sdp" );
95         set_capability( "access_demux", 0 );
96         set_callbacks( Open, Close );
97         add_bool( "rtsp-tcp", 0, NULL,
98                   N_("Use RTP over RTSP (TCP)"),
99                   N_("Use RTP over RTSP (TCP)"), VLC_TRUE );
100         add_integer( "rtp-client-port", -1, NULL,
101                   N_("Client port"),
102                   N_("Port to use for the RTP source of the session"), VLC_TRUE );
103 #if LIVEMEDIA_LIBRARY_VERSION_INT > 1130457500
104         add_bool( "rtsp-http", 0, NULL,
105                   N_("Tunnel RTSP and RTP over HTTP"),
106                   N_("Tunnel RTSP and RTP over HTTP"), VLC_TRUE );
107         add_integer( "rtsp-http-port", 80, NULL,
108                   N_("HTTP tunnel port"),
109                   N_("Port to use for tunneling the RTSP/RTP over HTTP."),
110                   VLC_TRUE );
111 #endif
112         add_integer("rtsp-caching", 4 * DEFAULT_PTS_DELAY / 1000, NULL,
113                     CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
114         add_bool(   "rtsp-kasenna", VLC_FALSE, NULL, KASENNA_TEXT,
115                     KASENNA_LONGTEXT, VLC_TRUE );
116         add_string( "rtsp-user", NULL, NULL, USER_TEXT,
117                     USER_LONGTEXT, VLC_TRUE );
118         add_string( "rtsp-pwd", NULL, NULL, PASS_TEXT,
119                     PASS_LONGTEXT, VLC_TRUE );
120 vlc_module_end();
121
122
123 /*****************************************************************************
124  * Local prototypes
125  *****************************************************************************/
126
127 typedef struct
128 {
129     demux_t     *p_demux;
130
131     vlc_bool_t   b_quicktime;
132     vlc_bool_t   b_muxed;
133     vlc_bool_t   b_asf;
134
135     es_format_t  fmt;
136     es_out_id_t  *p_es;
137
138     stream_t     *p_out_muxed;    /* for muxed stream */
139
140     RTPSource    *rtpSource;
141     FramedSource *readSource;
142     vlc_bool_t   b_rtcp_sync;
143
144     uint8_t      *p_buffer;
145     unsigned int  i_buffer;
146
147     char         waiting;
148
149     int64_t      i_pts;
150
151 } live_track_t;
152
153 struct timeout_thread_t
154 {
155     VLC_COMMON_MEMBERS
156
157     int64_t      i_remain;
158     demux_sys_t  *p_sys;
159 };
160
161 struct demux_sys_t
162 {
163     char            *p_sdp;    /* XXX mallocated */
164     char            *psz_path; /* URL-encoded path */
165
166     MediaSession     *ms;
167     TaskScheduler    *scheduler;
168     UsageEnvironment *env ;
169     RTSPClient       *rtsp;
170
171     /* */
172     int              i_track;
173     live_track_t     **track;   /* XXX mallocated */
174     int64_t          i_pcr;
175     int64_t          i_pcr_start;
176     int64_t          i_pcr_previous;
177     int64_t          i_pcr_repeatdate;
178     int              i_pcr_repeats;
179
180     /* Asf */
181     asf_header_t     asfh;
182     stream_t         *p_out_asf;
183
184     /* */
185     int64_t          i_length;
186     int64_t          i_start;
187
188     /* timeout thread information */
189     int              i_timeout;     /* session timeout value in seconds */
190     vlc_bool_t       b_timeout_call;/* mark to send an RTSP call to prevent server timeout */
191     timeout_thread_t *p_timeout;    /* the actual thread that makes sure we don't timeout */
192
193     /* */
194     vlc_bool_t       b_multicast;   /* true if one of the tracks is multicasted */
195     vlc_bool_t       b_no_data;     /* true if we never receive any data */
196     int              i_no_data_ti;  /* consecutive number of TaskInterrupt */
197
198     char             event;
199 };
200
201 static int Demux  ( demux_t * );
202 static int Control( demux_t *, int, va_list );
203
204 static int Connect      ( demux_t * );
205 static int SessionsSetup( demux_t * );
206 static int Play         ( demux_t *);
207 static int ParseASF     ( demux_t * );
208 static int RollOverTcp  ( demux_t * );
209
210 static void StreamRead  ( void *, unsigned int, unsigned int,
211                           struct timeval, unsigned int );
212 static void StreamClose ( void * );
213 static void TaskInterrupt( void * );
214
215 static void TimeoutPrevention( timeout_thread_t * );
216
217 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
218 static unsigned char* parseH264ConfigStr( char const* configStr,
219                                           unsigned int& configSize );
220 #endif
221
222 /*****************************************************************************
223  * DemuxOpen:
224  *****************************************************************************/
225 static int  Open ( vlc_object_t *p_this )
226 {
227     demux_t     *p_demux = (demux_t*)p_this;
228     demux_sys_t *p_sys = NULL;
229     
230     MediaSubsessionIterator *iter   = NULL;
231     MediaSubsession         *sub    = NULL;
232     int i_return;
233
234     if( p_demux->s )
235     {
236         /* See if it looks like a SDP
237            v, o, s fields are mandatory and in this order */
238         uint8_t *p_peek;
239         if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
240
241         if( memcmp( (char*)p_peek, "v=0\r\n", 5 ) &&
242             memcmp( (char*)p_peek, "v=0\n", 4 ) &&
243             ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
244         {
245             return VLC_EGENERIC;
246         }
247     }
248     else
249     {
250         var_Create( p_demux, "rtsp-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
251     }
252
253     p_demux->pf_demux  = Demux;
254     p_demux->pf_control= Control;
255     p_demux->p_sys     = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
256     if( !p_sys ) return VLC_ENOMEM;
257
258     p_sys->p_sdp = NULL;
259     p_sys->scheduler = NULL;
260     p_sys->env = NULL;
261     p_sys->ms = NULL;
262     p_sys->rtsp = NULL;
263     p_sys->i_track = 0;
264     p_sys->track   = NULL;
265     p_sys->i_pcr   = 0;
266     p_sys->i_pcr_start = 0;
267     p_sys->i_pcr_previous = 0;
268     p_sys->i_pcr_repeatdate = 0;
269     p_sys->i_pcr_repeats = 0;
270     p_sys->i_length = 0;
271     p_sys->i_start = 0;
272     p_sys->p_out_asf = NULL;
273     p_sys->b_no_data = VLC_TRUE;
274     p_sys->i_no_data_ti = 0;
275     p_sys->p_timeout = NULL;
276     p_sys->i_timeout = 0;
277     p_sys->b_timeout_call = VLC_FALSE;
278     p_sys->b_multicast = VLC_FALSE;
279     p_sys->psz_path = strdup( p_demux->psz_path );
280
281     if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
282     {
283         msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
284         goto error;
285     }
286     if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
287     {
288         msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
289         goto error;
290     }
291
292     if( strcasecmp( p_demux->psz_access, "sdp" ) )
293     {
294         char *p = p_sys->psz_path;
295         while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
296     }
297
298     if( p_demux->s != NULL )
299     {
300         /* Gather the complete sdp file */
301         int     i_sdp       = 0;
302         int     i_sdp_max   = 1000;
303         uint8_t *p_sdp      = (uint8_t*) malloc( i_sdp_max );
304         
305         for( ;; )
306         {
307             int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
308                                       i_sdp_max - i_sdp - 1 );
309
310             if( i_read < 0 )
311             {
312                 msg_Err( p_demux, "failed to read SDP" );
313                 free( p_sys );
314                 return VLC_EGENERIC;
315             }
316
317             i_sdp += i_read;
318
319             if( i_read < i_sdp_max - i_sdp - 1 )
320             {
321                 p_sdp[i_sdp] = '\0';
322                 break;
323             }
324
325             i_sdp_max += 1000;
326             p_sdp = (uint8_t*)realloc( p_sdp, i_sdp_max );
327         }
328         p_sys->p_sdp = (char*)p_sdp;
329     }
330     else if( p_demux->s == NULL && !strcasecmp( p_demux->psz_access, "sdp" ) )
331     {
332         /* sdp:// link from SAP */
333         p_sys->p_sdp = strdup( p_sys->psz_path );
334     }
335     else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
336     {
337         msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
338         goto error;
339     }
340     
341     if( p_sys->p_sdp == NULL )
342     {
343         msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
344         goto error;
345     }
346
347     /* Create the session from the SDP */
348     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
349     {
350         msg_Err( p_demux, "Could not create the RTSP Session: %s",
351             p_sys->env->getResultMsg() );
352         goto error;
353     }
354     
355     if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
356     {
357         msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
358         goto error;
359     }
360
361     /* Retrieve the duration if possible */
362     p_sys->i_length = (int64_t)( p_sys->ms->playEndTime() * 1000000.0 );
363     if( p_sys->i_length < 0 )
364         p_sys->i_length = -1;
365
366     if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
367         goto error;
368     
369     /* Create all es struct */
370     iter = new MediaSubsessionIterator( *p_sys->ms );
371     while( ( sub = iter->next() ) != NULL )
372     {
373         live_track_t *tk;
374
375         /* Check if we will receive data from this subsession for this track */
376         if( sub->readSource() == NULL ) continue;
377
378         tk = (live_track_t*)malloc( sizeof( live_track_t ) );
379         tk->p_demux = p_demux;
380         tk->waiting = 0;
381         tk->i_pts   = 0;
382         tk->b_quicktime = VLC_FALSE;
383         tk->b_muxed     = VLC_FALSE;
384         tk->b_asf       = VLC_FALSE;
385         tk->b_rtcp_sync = VLC_FALSE;
386         tk->p_out_muxed = NULL;
387         tk->p_es        = NULL;
388         tk->i_buffer    = 65536;
389         tk->p_buffer    = (uint8_t *)malloc( 65536 );
390
391         /* Value taken from mplayer */
392         if( !strcmp( sub->mediumName(), "audio" ) )
393         {
394             es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
395             tk->fmt.audio.i_channels = sub->numChannels();
396             tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
397
398             if( !strcmp( sub->codecName(), "MPA" ) ||
399                 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
400                 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
401             {
402                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
403                 tk->fmt.audio.i_rate = 0;
404             }
405             else if( !strcmp( sub->codecName(), "AC3" ) )
406             {
407                 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
408                 tk->fmt.audio.i_rate = 0;
409             }
410             else if( !strcmp( sub->codecName(), "L16" ) )
411             {
412                 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
413                 tk->fmt.audio.i_bitspersample = 16;
414             }
415             else if( !strcmp( sub->codecName(), "L8" ) )
416             {
417                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
418                 tk->fmt.audio.i_bitspersample = 8;
419             }
420             else if( !strcmp( sub->codecName(), "PCMU" ) )
421             {
422                 tk->fmt.i_codec = VLC_FOURCC( 'u', 'l', 'a', 'w' );
423             }
424             else if( !strcmp( sub->codecName(), "PCMA" ) )
425             {
426                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'l', 'a', 'w' );
427             }
428             else if( !strncmp( sub->codecName(), "G726", 4 ) )
429             {
430                 tk->fmt.i_codec = VLC_FOURCC( 'g', '7', '2', '6' ); 
431                 tk->fmt.audio.i_rate = 8000;
432                 tk->fmt.audio.i_channels = 1;
433                 if( !strcmp( sub->codecName()+5, "40" ) )
434                     tk->fmt.i_bitrate = 40000;
435                 else if( !strcmp( sub->codecName()+5, "32" ) )
436                     tk->fmt.i_bitrate = 32000;
437                 else if( !strcmp( sub->codecName()+5, "24" ) )
438                     tk->fmt.i_bitrate = 24000;
439                 else if( !strcmp( sub->codecName()+5, "16" ) )
440                     tk->fmt.i_bitrate = 16000;
441             }
442             else if( !strcmp( sub->codecName(), "AMR" ) )
443             {
444                 tk->fmt.i_codec = VLC_FOURCC( 's', 'a', 'm', 'r' );
445             }
446             else if( !strcmp( sub->codecName(), "AMR-WB" ) )
447             {
448                 tk->fmt.i_codec = VLC_FOURCC( 's', 'a', 'w', 'b' );
449             }
450             else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
451             {
452                 unsigned int i_extra;
453                 uint8_t      *p_extra;
454
455                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
456
457                 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
458                                                          i_extra ) ) )
459                 {
460                     tk->fmt.i_extra = i_extra;
461                     tk->fmt.p_extra = malloc( i_extra );
462                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
463                     delete[] p_extra;
464                 }
465
466 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1141257600
467                 /* Because the "faad" decoder does not handle the LATM data length field
468                    at the start of each returned LATM frame, tell the RTP source to omit it. */
469                 ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
470 #endif
471             }
472             else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
473             {
474                 unsigned int i_extra;
475                 uint8_t      *p_extra;
476
477                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
478
479                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
480                                                        i_extra ) ) )
481                 {
482                     tk->fmt.i_extra = i_extra;
483                     tk->fmt.p_extra = malloc( i_extra );
484                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
485                     delete[] p_extra;
486                 }
487             }
488             else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
489             {
490                 tk->b_asf = VLC_TRUE;
491                 if( p_sys->p_out_asf == NULL )
492                     p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
493                                                         p_demux->out );
494             }
495             else if( !strcmp( sub->codecName(), "X-QT" ) ||
496                      !strcmp( sub->codecName(), "X-QUICKTIME" ) )
497             {
498                 tk->b_quicktime = VLC_TRUE;
499             }
500         }
501         else if( !strcmp( sub->mediumName(), "video" ) )
502         {
503             es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
504             if( !strcmp( sub->codecName(), "MPV" ) )
505             {
506                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
507             }
508             else if( !strcmp( sub->codecName(), "H263" ) ||
509                      !strcmp( sub->codecName(), "H263-1998" ) ||
510                      !strcmp( sub->codecName(), "H263-2000" ) )
511             {
512                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '3' );
513             }
514             else if( !strcmp( sub->codecName(), "H261" ) )
515             {
516                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '1' );
517             }
518             else if( !strcmp( sub->codecName(), "H264" ) )
519             {
520 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
521                 unsigned int i_extra = 0;
522                 uint8_t      *p_extra = NULL;
523 #endif
524                 tk->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '4' );
525                 tk->fmt.b_packetized = VLC_FALSE;
526
527                 /* XXX not the right minimal version I fear */
528 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
529                 if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
530                                                 i_extra ) ) )
531                 {
532                     tk->fmt.i_extra = i_extra;
533                     tk->fmt.p_extra = malloc( i_extra );
534                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
535
536                     delete[] p_extra;
537                 }
538 #endif
539             }
540             else if( !strcmp( sub->codecName(), "JPEG" ) )
541             {
542                 tk->fmt.i_codec = VLC_FOURCC( 'M', 'J', 'P', 'G' );
543             }
544             else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
545             {
546                 unsigned int i_extra;
547                 uint8_t      *p_extra;
548
549                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
550
551                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
552                                                        i_extra ) ) )
553                 {
554                     tk->fmt.i_extra = i_extra;
555                     tk->fmt.p_extra = malloc( i_extra );
556                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
557                     delete[] p_extra;
558                 }
559             }
560             else if( !strcmp( sub->codecName(), "X-QT" ) ||
561                      !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
562                      !strcmp( sub->codecName(), "X-QDM" ) ||
563                      !strcmp( sub->codecName(), "X-SV3V-ES" )  ||
564                      !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
565             {
566                 tk->b_quicktime = VLC_TRUE;
567             }
568             else if( !strcmp( sub->codecName(), "MP2T" ) )
569             {
570                 tk->b_muxed = VLC_TRUE;
571                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
572             }
573             else if( !strcmp( sub->codecName(), "MP2P" ) ||
574                      !strcmp( sub->codecName(), "MP1S" ) )
575             {
576                 tk->b_muxed = VLC_TRUE;
577                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
578                                                    p_demux->out );
579             }
580             else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
581             {
582                 tk->b_asf = VLC_TRUE;
583                 if( p_sys->p_out_asf == NULL )
584                     p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
585                                                         p_demux->out );;
586             }
587         }
588
589         if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
590         {
591             tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
592         }
593
594         if( sub->rtcpInstance() != NULL )
595         {
596             sub->rtcpInstance()->setByeHandler( StreamClose, tk );
597         }
598
599         if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
600         {
601             tk->readSource = sub->readSource();
602             tk->rtpSource  = sub->rtpSource();
603             
604             /* Append */
605             p_sys->track = (live_track_t**)realloc( p_sys->track, sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
606             p_sys->track[p_sys->i_track++] = tk;
607         }
608         else
609         {
610             /* BUG ??? */
611             msg_Err( p_demux, "unusable RTSP track. this should not happen" );
612             free( tk );
613         }
614     }
615
616     delete iter;
617
618     if( p_sys->p_out_asf && ParseASF( p_demux ) )
619     {
620         msg_Err( p_demux, "cannot find a usable asf header" );
621         /* TODO Clean tracks */
622         goto error;
623     }
624
625     if( p_sys->i_track <= 0 )
626         goto error;
627
628     return VLC_SUCCESS;
629
630 error:
631     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
632     if( p_sys->ms ) Medium::close( p_sys->ms );
633     if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
634     if( p_sys->env ) RECLAIM_ENV(p_sys->env);
635     if( p_sys->p_timeout )
636     {
637         p_sys->p_timeout->b_die = VLC_TRUE;
638         vlc_thread_join( p_sys->p_timeout );
639         vlc_object_detach( p_sys->p_timeout );
640         vlc_object_destroy( p_sys->p_timeout );
641     }
642     if( p_sys->scheduler ) delete p_sys->scheduler;
643     if( p_sys->p_sdp ) free( p_sys->p_sdp );
644     if( p_sys->psz_path ) free( p_sys->psz_path );
645
646     free( p_sys );
647     return VLC_EGENERIC;
648 }
649
650 /*****************************************************************************
651  * DemuxClose:
652  *****************************************************************************/
653 static void Close( vlc_object_t *p_this )
654 {
655     demux_t *p_demux = (demux_t*)p_this;
656     demux_sys_t *p_sys = p_demux->p_sys;
657     int i;
658
659     for( i = 0; i < p_sys->i_track; i++ )
660     {
661         live_track_t *tk = p_sys->track[i];
662
663         if( tk->b_muxed ) stream_DemuxDelete( tk->p_out_muxed );
664         free( tk->p_buffer );
665         free( tk );
666     }
667
668     if( p_sys->i_track ) free( p_sys->track );
669     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
670
671     if( p_sys->rtsp && p_sys->ms )
672     {
673         /* TEARDOWN */
674         p_sys->rtsp->teardownMediaSession( *p_sys->ms );
675     }
676
677     Medium::close( p_sys->ms );
678
679     if( p_sys->p_timeout )
680     {
681         p_sys->p_timeout->b_die = VLC_TRUE;
682         vlc_thread_join( p_sys->p_timeout );
683         vlc_object_detach( p_sys->p_timeout );
684         vlc_object_destroy( p_sys->p_timeout );
685     }
686
687     if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
688     if( p_sys->env ) RECLAIM_ENV( p_sys->env );
689     if( p_sys->scheduler ) delete p_sys->scheduler;
690     if( p_sys->p_sdp ) free( p_sys->p_sdp );
691     if( p_sys->psz_path ) free( p_sys->psz_path );
692     free( p_sys );
693 }
694
695 /*****************************************************************************
696  * Connect: connects to the RTSP server to setup the session DESCRIBE
697  *****************************************************************************/
698 static int Connect( demux_t *p_demux )
699 {
700     demux_sys_t *p_sys = p_demux->p_sys;
701     Authenticator authenticator;
702
703     char *psz_user    = NULL;
704     char *psz_pwd     = NULL;
705     char *psz_url     = NULL;
706     char *psz_options = NULL;
707     char *p_sdp       = NULL;
708     int  i_http_port  = 0;
709     int  i_ret        = VLC_SUCCESS;
710
711 createnew:
712     if( var_CreateGetBool( p_demux, "rtsp-http" ) )
713         i_http_port = var_CreateGetInteger( p_demux, "rtsp-http-port" );
714
715 #if LIVEMEDIA_LIBRARY_VERSION_INT > 1130457500
716     if( ( p_sys->rtsp = RTSPClient::createNew(*p_sys->env, 1 /*verbose*/,
717           "VLC media player", i_http_port ) ) == NULL )
718 #else
719     if( ( p_sys->rtsp = RTSPClient::createNew(*p_sys->env, 1 /*verbose*/,
720           "VLC media player" ) ) == NULL )
721 #endif
722     {
723         msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
724                  p_sys->env->getResultMsg() );
725         return VLC_EGENERIC;
726     }
727     psz_url = (char*)malloc( strlen( p_sys->psz_path ) + 8 );
728     sprintf( psz_url, "rtsp://%s", p_sys->psz_path );
729
730     psz_options = p_sys->rtsp->sendOptionsCmd( psz_url );
731     if( psz_options ) delete [] psz_options;
732
733     psz_user = var_CreateGetString( p_demux, "rtsp-user" );
734     psz_pwd  = var_CreateGetString( p_demux, "rtsp-pwd" );
735
736 describe:
737     authenticator.setUsernameAndPassword( (const char*)psz_user, (const char*)psz_pwd );
738     p_sdp = p_sys->rtsp->describeURL( psz_url,
739                 &authenticator, var_CreateGetBool( p_demux, "rtsp-kasenna" ) );
740
741     if( psz_user ) free( psz_user );
742     if( psz_pwd ) free( psz_pwd );                
743     
744     if( p_sdp == NULL )
745     {
746         /* failure occurred */
747         int i_code = 0;
748         const char *psz_error = p_sys->env->getResultMsg();
749                 
750         msg_Dbg( p_demux, "DESCRIBE failed with %d: %s", i_code, psz_error );
751         sscanf( psz_error, "%*sRTSP/%*s%3u", &i_code );
752         
753         if( i_code == 401 )
754         {
755             char *psz_login = NULL; char *psz_password = NULL;
756             msg_Dbg( p_demux, "authentication failed" );
757
758             i_ret = intf_UserLoginPassword( p_demux, _("RTSP authentication"),
759                            _("Please enter a valid login name and a password."),
760                                                    &psz_login, &psz_password );
761             if( i_ret == DIALOG_OK_YES )
762             {
763                msg_Dbg( p_demux, "retrying with user=%s, pwd=%s",
764                            psz_login, psz_password );
765                
766                if( psz_login ) psz_user = psz_login;
767                if( psz_password ) psz_pwd = psz_password;
768                goto describe;
769             }
770             if( psz_login ) free( psz_login );
771             if( psz_password ) free( psz_password );
772         }
773         else if( !var_CreateGetBool( p_demux, "rtsp-http" ) )
774         {
775             /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
776             vlc_value_t val;
777             val.b_bool = VLC_TRUE;
778             msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
779             var_Set( p_demux, "rtsp-http", val );
780             if( psz_url ) free( psz_url );
781             if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
782             goto createnew;
783         }
784         i_ret = VLC_EGENERIC;
785     }
786     if( psz_url ) free( psz_url );
787
788     /* malloc-ated copy */
789     if( p_sys->p_sdp ) free( p_sys->p_sdp );
790     if( p_sdp ) p_sys->p_sdp = strdup( (char*)p_sdp );
791     delete[] p_sdp;
792
793     return i_ret;
794 }
795
796 /*****************************************************************************
797  * Connect: prepares the subsessions and does the SETUP
798  *****************************************************************************/
799 static int SessionsSetup( demux_t *p_demux )
800 {
801     demux_sys_t             *p_sys  = p_demux->p_sys;
802     MediaSubsessionIterator *iter   = NULL;
803     MediaSubsession         *sub    = NULL;
804
805     vlc_bool_t     b_rtsp_tcp = VLC_FALSE;
806     int            i_client_port;
807     int            i_active_sessions = 0;
808     int            i_return = VLC_SUCCESS;
809     unsigned int   i_buffer = 0;
810     unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
811
812     b_rtsp_tcp    = var_CreateGetBool( p_demux, "rtsp-tcp" );
813     i_client_port = var_CreateGetInteger( p_demux, "rtp-client-port" );
814
815     /* Initialise each media subsession */
816     iter = new MediaSubsessionIterator( *p_sys->ms );
817     while( ( sub = iter->next() ) != NULL )
818     {
819         Boolean bInit;
820
821         /* Value taken from mplayer */
822         if( !strcmp( sub->mediumName(), "audio" ) )
823             i_buffer = 100000;
824         else if( !strcmp( sub->mediumName(), "video" ) )
825             i_buffer = 2000000;
826         else continue;
827
828         if( i_client_port != -1 )
829         {
830             sub->setClientPortNum( i_client_port );
831             i_client_port += 2;
832         }
833
834         if( strcasestr( sub->codecName(), "REAL" ) )
835         {
836             msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
837             i_return = VLC_EGENERIC;
838             break;
839         }
840
841         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
842             bInit = sub->initiate( 4 ); /* Constant ? */
843         else
844             bInit = sub->initiate();
845         
846         if( !bInit )
847         {
848             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
849                       sub->mediumName(), sub->codecName(),
850                       p_sys->env->getResultMsg() );
851         }
852         else
853         {
854             if( sub->rtpSource() != NULL )
855             {
856                 int fd = sub->rtpSource()->RTPgs()->socketNum();
857           
858                 /* Increase the buffer size */
859                 if( i_buffer > 0 )
860                     increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
861                 
862                 /* Increase the RTP reorder timebuffer just a bit */
863                 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
864             }
865
866             msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
867                      sub->codecName() );
868
869             /* Issue the SETUP */
870             if( p_sys->rtsp )
871             {
872                 if( !( p_sys->rtsp->setupMediaSubsession( *sub, False,
873                                                    b_rtsp_tcp ? True : False ) ) )
874                 {
875                     msg_Err( p_demux, "SETUP of'%s/%s' failed %s", sub->mediumName(),
876                              sub->codecName(), p_sys->env->getResultMsg() );
877                 }
878                 else i_active_sessions++;
879             } else i_active_sessions++; /* we don't really know, let's just hope it's there */
880
881             if( !p_sys->b_multicast )
882             {
883                 /* Check, because we need diff. rollover behaviour for multicast */
884                 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
885             }
886         }
887     }
888     delete iter;
889     if( i_active_sessions <= 0 ) i_return = VLC_EGENERIC;
890     return i_return;
891 }
892
893 /*****************************************************************************
894  * Play: starts the actual playback of the stream
895  *****************************************************************************/
896 static int Play( demux_t *p_demux )
897 {
898     demux_sys_t *p_sys = p_demux->p_sys;
899     
900     if( p_sys->rtsp )
901     {
902         /* The PLAY */
903         if( !p_sys->rtsp->playMediaSession( *p_sys->ms ) )
904         {
905             msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
906             return VLC_EGENERIC;
907         }
908
909         /* Retrieve the timeout value and set up a timeout prevention thread */
910 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1138089600
911         p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
912 #endif
913         if( p_sys->i_timeout > 0 && !p_sys->p_timeout )
914         {
915             msg_Dbg( p_demux, "We have a timeout of %d seconds",  p_sys->i_timeout );
916             p_sys->p_timeout = (timeout_thread_t *)vlc_object_create( p_demux, sizeof(timeout_thread_t) );
917             p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
918             if( vlc_thread_create( p_sys->p_timeout, "liveMedia-timeout", TimeoutPrevention,
919                                    VLC_THREAD_PRIORITY_LOW, VLC_TRUE ) )
920             {
921                 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
922                 vlc_object_destroy( p_sys->p_timeout );
923             }
924             msg_Dbg( p_demux, "spawned timeout thread" );
925             vlc_object_attach( p_sys->p_timeout, p_demux );
926         }
927     }
928     return VLC_SUCCESS;
929 }
930
931
932 /*****************************************************************************
933  * Demux:
934  *****************************************************************************/
935 static int Demux( demux_t *p_demux )
936 {
937     demux_sys_t    *p_sys = p_demux->p_sys;
938     TaskToken      task;
939
940     vlc_bool_t      b_send_pcr = VLC_TRUE;
941     int64_t         i_pcr = 0;
942     int             i;
943
944     /* Check if we need to send the server a Keep-A-Live signal */
945     if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
946     {
947 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1138089600
948         char *psz_bye = NULL;
949         p_sys->rtsp->getMediaSessionParameter( *p_sys->ms, NULL, psz_bye );
950 #endif
951         p_sys->b_timeout_call = VLC_FALSE;
952     }
953
954     for( i = 0; i < p_sys->i_track; i++ )
955     {
956         live_track_t *tk = p_sys->track[i];
957
958         if( tk->b_asf || tk->b_muxed )
959             b_send_pcr = VLC_FALSE;
960
961         if( i_pcr == 0 )
962         {
963             i_pcr = tk->i_pts;
964         }
965         else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
966         {
967             i_pcr = tk->i_pts ;
968         }
969     }
970     if( i_pcr != p_sys->i_pcr && i_pcr > 0 )
971     {
972         p_sys->i_pcr = i_pcr;
973
974         if( b_send_pcr )
975             es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pcr );
976         if( p_sys->i_pcr_start <= 0 || p_sys->i_pcr_start > i_pcr ||
977             ( p_sys->i_length > 0 && i_pcr - p_sys->i_pcr_start > p_sys->i_length ) )
978         {
979             p_sys->i_pcr_start = i_pcr;
980         }
981     }
982
983 #if 0
984     /* Disabled because it's simply not reliable enough */
985
986     /* When a On Demand QT stream ends, the last frame keeps going with the same PCR/PTS value */
987     /* This tests for that, so we can later decide to end this session */
988     if( i_pcr > 0 && p_sys->i_pcr == p_sys->i_pcr_previous )
989     {
990         if( p_sys->i_pcr_repeats == 0 )
991             p_sys->i_pcr_repeatdate = mdate();
992         p_sys->i_pcr_repeats++;
993     }
994     else
995     {
996         p_sys->i_pcr_previous = p_sys->i_pcr;
997         p_sys->i_pcr_repeatdate = 0;
998         p_sys->i_pcr_repeats = 0;
999     }
1000
1001     if( p_sys->i_pcr_repeats > 5 && mdate() > p_sys->i_pcr_repeatdate + 1000000 )
1002     {
1003         /* We need at least 5 repeats over at least a second of time before we EOF */
1004         msg_Dbg( p_demux, "suspect EOF due to end of VoD session" );
1005         return 0;
1006     }
1007 #endif
1008
1009     /* First warn we want to read data */
1010     p_sys->event = 0;
1011     for( i = 0; i < p_sys->i_track; i++ )
1012     {
1013         live_track_t *tk = p_sys->track[i];
1014
1015         if( tk->waiting == 0 )
1016         {
1017             tk->waiting = 1;
1018             tk->readSource->getNextFrame( tk->p_buffer, tk->i_buffer,
1019                                           StreamRead, tk, StreamClose, tk );
1020         }
1021     }
1022     /* Create a task that will be called if we wait more than 300ms */
1023     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
1024
1025     /* Do the read */
1026     p_sys->scheduler->doEventLoop( &p_sys->event );
1027
1028     /* remove the task */
1029     p_sys->scheduler->unscheduleDelayedTask( task );
1030
1031     /* Check for gap in pts value */
1032     for( i = 0; i < p_sys->i_track; i++ )
1033     {
1034         live_track_t *tk = p_sys->track[i];
1035
1036         if( !tk->b_muxed && !tk->b_rtcp_sync &&
1037             tk->rtpSource && tk->rtpSource->hasBeenSynchronizedUsingRTCP() )
1038         {
1039             msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1040
1041             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1042             tk->b_rtcp_sync = VLC_TRUE;
1043
1044             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
1045             tk->i_pts = 0;
1046             p_sys->i_pcr_start = 0;
1047             p_sys->i_pcr = 0;
1048             i_pcr = 0;
1049         }
1050     }
1051
1052     if( p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 120 )
1053     {
1054         /* FIXME Make this configurable
1055         msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1056         return 0;
1057         */
1058     }
1059     else if( !p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 34 )
1060     {
1061         vlc_bool_t b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" );
1062
1063         if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1064         {
1065             msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1066             if( RollOverTcp( p_demux ) )
1067             {
1068                 msg_Err( p_demux, "TCP rollover failed, aborting" );
1069                 return 0;
1070             }
1071         }
1072         else if( p_sys->i_no_data_ti > 34 )
1073         {
1074             msg_Err( p_demux, "no data received in 10s, aborting" );
1075             return 0;
1076         }
1077     }
1078     else if( !p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 34 )
1079     {
1080         /* EOF ? */
1081         msg_Warn( p_demux, "no data received in 10s, eof ?" );
1082         return 0;
1083     }
1084
1085     return p_demux->b_error ? 0 : 1;
1086 }
1087
1088 /*****************************************************************************
1089  * Control:
1090  *****************************************************************************/
1091 static int Control( demux_t *p_demux, int i_query, va_list args )
1092 {
1093     demux_sys_t *p_sys = p_demux->p_sys;
1094     int64_t *pi64;
1095     double  *pf, f;
1096     vlc_bool_t *pb, b_bool;
1097
1098     switch( i_query )
1099     {
1100         case DEMUX_GET_TIME:
1101             pi64 = (int64_t*)va_arg( args, int64_t * );
1102             *pi64 = p_sys->i_pcr - p_sys->i_pcr_start + p_sys->i_start;
1103             return VLC_SUCCESS;
1104
1105         case DEMUX_GET_LENGTH:
1106             pi64 = (int64_t*)va_arg( args, int64_t * );
1107             *pi64 = p_sys->i_length;
1108             return VLC_SUCCESS;
1109
1110         case DEMUX_GET_POSITION:
1111             pf = (double*)va_arg( args, double* );
1112             if( p_sys->i_length > 0 )
1113             {
1114                 *pf = (double)( p_sys->i_pcr - p_sys->i_pcr_start +
1115                                 p_sys->i_start ) / (double)(p_sys->i_length);
1116             }
1117             else
1118             {
1119                 *pf = 0.0;
1120             }
1121             return VLC_SUCCESS;
1122
1123         case DEMUX_SET_POSITION:
1124             float time;
1125
1126             f = (double)va_arg( args, double );
1127             
1128             if( p_sys->rtsp && p_sys->i_length > 0 )
1129             {
1130                 time = f * (double)p_sys->i_length / 1000000.0;   /* in second */
1131                 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, time ) )
1132                 {
1133                     msg_Err( p_demux, "PLAY failed %s",
1134                         p_sys->env->getResultMsg() );
1135                     return VLC_EGENERIC;
1136                 }
1137                 p_sys->i_start = (int64_t)(f * (double)p_sys->i_length);
1138                 p_sys->i_pcr_start = 0;
1139                 p_sys->i_pcr       = 0;
1140
1141                 return VLC_SUCCESS;
1142             }
1143             return VLC_SUCCESS;
1144
1145         /* Special for access_demux */
1146         case DEMUX_CAN_PAUSE:
1147             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1148             if( p_sys->rtsp && p_sys->i_length )
1149                 /* Not always true, but will be handled in SET_PAUSE_STATE */
1150                 *pb = VLC_TRUE;
1151             else
1152                 *pb = VLC_FALSE;
1153             return VLC_SUCCESS;
1154
1155         case DEMUX_CAN_CONTROL_PACE:
1156             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1157
1158 #if 0       /* Disable for now until we have a clock synchro algo
1159              * which works with something else than MPEG over UDP */
1160             *pb = VLC_FALSE;
1161 #else
1162             *pb = VLC_TRUE;
1163 #endif
1164             return VLC_SUCCESS;
1165
1166         case DEMUX_SET_PAUSE_STATE:
1167             double d_npt;
1168
1169             d_npt = ( (double)( p_sys->i_pcr - p_sys->i_pcr_start +
1170                                 p_sys->i_start ) ) / 1000000.00;
1171
1172             b_bool = (vlc_bool_t)va_arg( args, vlc_bool_t );
1173             if( p_sys->rtsp == NULL )
1174                 return VLC_EGENERIC;
1175
1176             if( ( b_bool && !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) ) ||
1177                     ( !b_bool && !p_sys->rtsp->playMediaSession( *p_sys->ms,
1178                       d_npt > 0 ? d_npt : -1 ) ) )
1179             {
1180                     msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1181                     return VLC_EGENERIC;
1182             }
1183 #if 0
1184             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
1185             for( i = 0; i < p_sys->i_track; i++ )
1186             {
1187                 p_sys->track[i]->i_pts = 0;
1188             }
1189             p_sys->i_pcr_start = 0; /* FIXME Wrong */
1190             p_sys->i_pcr = 0;
1191 #endif
1192             return VLC_SUCCESS;
1193
1194         case DEMUX_GET_TITLE_INFO:
1195         case DEMUX_SET_TITLE:
1196         case DEMUX_SET_SEEKPOINT:
1197             return VLC_EGENERIC;
1198
1199         case DEMUX_GET_PTS_DELAY:
1200             pi64 = (int64_t*)va_arg( args, int64_t * );
1201             *pi64 = (int64_t)var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1202             return VLC_SUCCESS;
1203
1204         default:
1205             return VLC_EGENERIC;
1206     }
1207 }
1208
1209 /*****************************************************************************
1210  * RollOverTcp: reopen the rtsp into TCP mode
1211  * XXX: ugly, a lot of code are duplicated from Open()
1212  *****************************************************************************/
1213 static int RollOverTcp( demux_t *p_demux )
1214 {
1215     demux_sys_t *p_sys = p_demux->p_sys;
1216     MediaSubsessionIterator *iter = 0;
1217     MediaSubsession *sub;
1218     int i_tk;
1219     int i_return;
1220
1221     var_SetBool( p_demux, "rtsp-tcp", VLC_TRUE );
1222     
1223     /* We close the old RTSP session */
1224     p_sys->rtsp->teardownMediaSession( *p_sys->ms );
1225
1226     Medium::close( p_sys->ms );
1227     RTSPClient::close( p_sys->rtsp );
1228
1229     p_sys->ms = NULL;
1230     p_sys->rtsp = NULL;
1231
1232     /* Reopen rtsp client */
1233     if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1234     {
1235         msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
1236         goto error;
1237     }
1238     
1239     if( p_sys->p_sdp == NULL )
1240     {
1241         msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1242         goto error;
1243     }
1244
1245     /* Create the session from the SDP */
1246     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
1247     {
1248         msg_Err( p_demux, "Could not create the RTSP Session: %s",
1249             p_sys->env->getResultMsg() );
1250         goto error;
1251     }
1252
1253     if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1254     {
1255         msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1256         goto error;
1257     }
1258
1259     /* Retrieve the duration if possible */
1260     p_sys->i_length = (int64_t)( p_sys->ms->playEndTime() * 1000000.0 );
1261     if( p_sys->i_length < 0 )
1262         p_sys->i_length = -1;
1263
1264     if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1265         goto error;
1266
1267     /* Update all tracks */
1268     iter = new MediaSubsessionIterator( *p_sys->ms );
1269     i_tk = 0;
1270     while( ( sub = iter->next() ) != NULL )
1271     {
1272         live_track_t *tk;
1273
1274         if( sub->readSource() == NULL )
1275             continue;
1276         if( i_tk >= p_sys->i_track )
1277         {
1278             msg_Err( p_demux, "WTF !" );
1279             goto error;
1280         }
1281
1282         tk = p_sys->track[i_tk];
1283
1284         /* Reset state */
1285         tk->waiting = 0;
1286         tk->i_pts   = 0;
1287         tk->b_rtcp_sync = VLC_FALSE;
1288
1289         if( sub->rtcpInstance() != NULL )
1290             sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1291
1292         tk->readSource = sub->readSource();
1293         tk->rtpSource  = sub->rtpSource();
1294
1295         i_tk++;
1296     }
1297     delete iter;
1298
1299     return VLC_SUCCESS;
1300
1301 error:
1302     if( iter ) delete iter;
1303     return VLC_EGENERIC;
1304 }
1305
1306
1307 /*****************************************************************************
1308  *
1309  *****************************************************************************/
1310 static void StreamRead( void *p_private, unsigned int i_size,
1311                         unsigned int i_truncated_bytes, struct timeval pts,
1312                         unsigned int duration )
1313 {
1314     live_track_t   *tk = (live_track_t*)p_private;
1315     demux_t        *p_demux = tk->p_demux;
1316     demux_sys_t    *p_sys = p_demux->p_sys;
1317     block_t        *p_block;
1318
1319     int64_t i_pts = (uint64_t)pts.tv_sec * UI64C(1000000) +
1320         (uint64_t)pts.tv_usec;
1321
1322     /* XXX Beurk beurk beurk Avoid having negative value XXX */
1323     i_pts &= UI64C(0x00ffffffffffffff);
1324
1325     if( tk->b_quicktime && tk->p_es == NULL )
1326     {
1327         QuickTimeGenericRTPSource *qtRTPSource =
1328             (QuickTimeGenericRTPSource*)tk->rtpSource;
1329         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1330         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1331
1332         if( tk->fmt.i_cat == VIDEO_ES ) {
1333             if( qtState.sdAtomSize < 16 + 32 )
1334             {
1335                 /* invalid */
1336                 p_sys->event = 0xff;
1337                 tk->waiting = 0;
1338                 return;
1339             }
1340             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1341             tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
1342             tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1343
1344             tk->fmt.i_extra        = qtState.sdAtomSize - 16;
1345             tk->fmt.p_extra        = malloc( tk->fmt.i_extra );
1346             memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1347
1348         }
1349         else {
1350             if( qtState.sdAtomSize < 4 )
1351             {
1352                 /* invalid */
1353                 p_sys->event = 0xff;
1354                 tk->waiting = 0;
1355                 return;
1356             }
1357             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1358         }
1359         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1360     }
1361
1362 #if 0
1363     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1364              i_size,
1365              pts.tv_sec * 1000000LL + pts.tv_usec );
1366 #endif
1367
1368     /* grow buffer if it looks like buffer is too small, but don't eat
1369      * up all the memory on strange streams */
1370     if( i_truncated_bytes > 0 && tk->i_buffer < 2000000 )
1371     {
1372         void *p_tmp;
1373         msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1374         msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1375         tk->i_buffer *= 2;
1376         p_tmp = realloc( tk->p_buffer, tk->i_buffer );
1377         if (p_tmp == NULL)
1378         {
1379             msg_Warn( p_demux, "realloc failed" );
1380         }
1381         else
1382         {
1383             tk->p_buffer = (uint8_t*)p_tmp;
1384         }
1385     }
1386     if( i_size > tk->i_buffer )
1387     {
1388         msg_Warn( p_demux, "buffer overflow" );
1389     }
1390     /* FIXME could i_size be > buffer size ? */
1391     if( tk->fmt.i_codec == VLC_FOURCC('s','a','m','r') ||
1392         tk->fmt.i_codec == VLC_FOURCC('s','a','w','b') )
1393     {
1394         AMRAudioSource *amrSource = (AMRAudioSource*)tk->readSource;
1395
1396         p_block = block_New( p_demux, i_size + 1 );
1397         p_block->p_buffer[0] = amrSource->lastFrameHeader();
1398         memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1399     }
1400     else if( tk->fmt.i_codec == VLC_FOURCC('H','2','6','1') )
1401     {
1402 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1081468800
1403         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->rtpSource;
1404         uint32_t header = h261Source->lastSpecialHeader();
1405 #else
1406         uint32_t header = 0;
1407         msg_Warn( p_demux, "need livemedia library >= \"2004.04.09\"" );
1408 #endif
1409         p_block = block_New( p_demux, i_size + 4 );
1410         memcpy( p_block->p_buffer, &header, 4 );
1411         memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1412
1413         if( tk->rtpSource->curPacketMarkerBit() )
1414             p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1415     }
1416     else if( tk->fmt.i_codec == VLC_FOURCC('h','2','6','4') )
1417     {
1418         if( (tk->p_buffer[0] & 0x1f) >= 24 )
1419             msg_Warn( p_demux, "unsupported NAL type for H264" );
1420
1421         /* Normal NAL type */
1422         p_block = block_New( p_demux, i_size + 4 );
1423         p_block->p_buffer[0] = 0x00;
1424         p_block->p_buffer[1] = 0x00;
1425         p_block->p_buffer[2] = 0x00;
1426         p_block->p_buffer[3] = 0x01;
1427         memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1428     }
1429     else if( tk->b_asf )
1430     {
1431         int i_copy = __MIN( p_sys->asfh.i_min_data_packet_size, (int)i_size );
1432         p_block = block_New( p_demux, p_sys->asfh.i_min_data_packet_size );
1433
1434         memcpy( p_block->p_buffer, tk->p_buffer, i_copy );
1435     }
1436     else
1437     {
1438         p_block = block_New( p_demux, i_size );
1439         memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1440     }
1441
1442     if( i_pts != tk->i_pts && !tk->b_muxed )
1443     {
1444         p_block->i_dts = ( tk->fmt.i_cat == VIDEO_ES ) ? 0 : i_pts;
1445         p_block->i_pts = i_pts;
1446     }
1447
1448     if( tk->b_muxed )
1449     {
1450         stream_DemuxSend( tk->p_out_muxed, p_block );
1451     }
1452     else if( tk->b_asf )
1453     {
1454         stream_DemuxSend( p_sys->p_out_asf, p_block );
1455     }
1456     else
1457     {
1458         es_out_Send( p_demux->out, tk->p_es, p_block );
1459     }
1460
1461     /* warn that's ok */
1462     p_sys->event = 0xff;
1463
1464     /* we have read data */
1465     tk->waiting = 0;
1466     p_demux->p_sys->b_no_data = VLC_FALSE;
1467     p_demux->p_sys->i_no_data_ti = 0;
1468
1469     if( i_pts > 0 && !tk->b_muxed )
1470     {
1471         tk->i_pts = i_pts;
1472     }
1473 }
1474
1475 /*****************************************************************************
1476  *
1477  *****************************************************************************/
1478 static void StreamClose( void *p_private )
1479 {
1480     live_track_t   *tk = (live_track_t*)p_private;
1481     demux_t        *p_demux = tk->p_demux;
1482     demux_sys_t    *p_sys = p_demux->p_sys;
1483
1484     msg_Dbg( p_demux, "StreamClose" );
1485
1486     p_sys->event = 0xff;
1487     p_demux->b_error = VLC_TRUE;
1488 }
1489
1490
1491 /*****************************************************************************
1492  *
1493  *****************************************************************************/
1494 static void TaskInterrupt( void *p_private )
1495 {
1496     demux_t *p_demux = (demux_t*)p_private;
1497
1498     p_demux->p_sys->i_no_data_ti++;
1499
1500     /* Avoid lock */
1501     p_demux->p_sys->event = 0xff;
1502 }
1503
1504 /*****************************************************************************
1505  *  
1506  *****************************************************************************/
1507 static void TimeoutPrevention( timeout_thread_t *p_timeout )
1508 {
1509     p_timeout->b_die = VLC_FALSE;
1510     p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1511     p_timeout->i_remain *= 1000000;
1512
1513     vlc_thread_ready( p_timeout );
1514     
1515     /* Avoid lock */
1516     while( !p_timeout->b_die )
1517     {
1518         if( p_timeout->i_remain <= 0 )
1519         {
1520             p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1521             p_timeout->i_remain *= 1000000;
1522             p_timeout->p_sys->b_timeout_call = VLC_TRUE;
1523             msg_Dbg( p_timeout, "reset the timeout timer" );
1524         }
1525         p_timeout->i_remain -= 200000;
1526         msleep( 200000 ); /* 200 ms */
1527     }
1528 }
1529
1530 /*****************************************************************************
1531  *
1532  *****************************************************************************/
1533 static int b64_decode( char *dest, char *src );
1534
1535 static int ParseASF( demux_t *p_demux )
1536 {
1537     demux_sys_t    *p_sys = p_demux->p_sys;
1538
1539     const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1540     char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1541     char *psz_end;
1542     block_t *p_header;
1543
1544     /* Parse the asf header */
1545     if( psz_asf == NULL )
1546         return VLC_EGENERIC;
1547
1548     psz_asf += strlen( psz_marker );
1549     psz_asf = strdup( psz_asf );    /* Duplicate it */
1550     psz_end = strchr( psz_asf, '\n' );
1551
1552     while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1553         *psz_end-- = '\0';
1554
1555     if( psz_asf >= psz_end )
1556     {
1557         free( psz_asf );
1558         return VLC_EGENERIC;
1559     }
1560
1561     /* Always smaller */
1562     p_header = block_New( p_demux, psz_end - psz_asf );
1563     p_header->i_buffer = b64_decode( (char*)p_header->p_buffer, psz_asf );
1564     //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
1565     if( p_header->i_buffer <= 0 )
1566     {
1567         free( psz_asf );
1568         return VLC_EGENERIC;
1569     }
1570
1571     /* Parse it to get packet size */
1572     E_(asf_HeaderParse)( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
1573
1574     /* Send it to demuxer */
1575     stream_DemuxSend( p_sys->p_out_asf, p_header );
1576
1577     free( psz_asf );
1578     return VLC_SUCCESS;
1579 }
1580
1581 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1117756800
1582 static unsigned char* parseH264ConfigStr( char const* configStr,
1583                                           unsigned int& configSize )
1584 {
1585     char *dup, *psz;
1586     int i, i_records = 1;
1587
1588     if( configSize )
1589     configSize = 0;
1590
1591     if( configStr == NULL || *configStr == '\0' )
1592         return NULL;
1593
1594     psz = dup = strdup( configStr );
1595
1596     /* Count the number of comma's */
1597     for( psz = dup; *psz != '\0'; ++psz )
1598     {
1599         if( *psz == ',')
1600         {
1601             ++i_records;
1602             *psz = '\0';
1603         }
1604     }
1605
1606     unsigned char *cfg = new unsigned char[5 * strlen(dup)];
1607     psz = dup;
1608     for( i = 0; i < i_records; i++ )
1609     {
1610         cfg[configSize++] = 0x00;
1611         cfg[configSize++] = 0x00;
1612         cfg[configSize++] = 0x00;
1613         cfg[configSize++] = 0x01;
1614
1615         configSize += b64_decode( (char*)&cfg[configSize], psz );
1616         psz += strlen(psz)+1;
1617     }
1618
1619     if( dup ) free( dup );
1620     return cfg;
1621 }
1622 #endif
1623
1624 /*char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";*/
1625 static int b64_decode( char *dest, char *src )
1626 {
1627     const char *dest_start = dest;
1628     int  i_level;
1629     int  last = 0;
1630     int  b64[256] = {
1631         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
1632         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
1633         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
1634         52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
1635         -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
1636         15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
1637         -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
1638         41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
1639         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
1640         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
1641         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
1642         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
1643         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
1644         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
1645         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
1646         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
1647         };
1648
1649     for( i_level = 0; *src != '\0'; src++ )
1650     {
1651         int  c;
1652
1653         c = b64[(unsigned int)*src];
1654         if( c == -1 )
1655         {
1656             continue;
1657         }
1658
1659         switch( i_level )
1660         {
1661             case 0:
1662                 i_level++;
1663                 break;
1664             case 1:
1665                 *dest++ = ( last << 2 ) | ( ( c >> 4)&0x03 );
1666                 i_level++;
1667                 break;
1668             case 2:
1669                 *dest++ = ( ( last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
1670                 i_level++;
1671                 break;
1672             case 3:
1673                 *dest++ = ( ( last &0x03 ) << 6 ) | c;
1674                 i_level = 0;
1675         }
1676         last = c;
1677     }
1678
1679     *dest = '\0';
1680
1681     return dest - dest_start;
1682 }