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