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