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