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