]> git.sesse.net Git - vlc/blob - modules/demux/live555.cpp
ts: Fix audio type description parsing
[vlc] / modules / demux / live555.cpp
1 /*****************************************************************************
2  * live555.cpp : LIVE555 Streaming Media support.
3  *****************************************************************************
4  * Copyright (C) 2003-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Derk-Jan Hartman <hartman at videolan. org>
9  *          Derk-Jan Hartman <djhartman at m2x .dot. nl> for M2X
10  *          Sébastien Escudier <sebastien-devel celeos eu>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along
23  * with this program; if not, write to the Free Software Foundation, Inc.,
24  * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30
31 /* For inttypes.h
32  * Note: config.h may include inttypes.h, so make sure we define this option
33  * early enough. */
34 #define __STDC_CONSTANT_MACROS 1
35 #define __STDC_LIMIT_MACROS 1
36
37 #ifdef HAVE_CONFIG_H
38 # include "config.h"
39 #endif
40
41 #include <inttypes.h>
42
43 #include <vlc_common.h>
44 #include <vlc_plugin.h>
45 #include <vlc_input.h>
46 #include <vlc_demux.h>
47 #include <vlc_dialog.h>
48 #include <vlc_url.h>
49 #include <vlc_strings.h>
50
51 #include <limits.h>
52 #include <assert.h>
53
54
55 #if defined( WIN32 )
56 #   include <winsock2.h>
57 #endif
58
59 #include <UsageEnvironment.hh>
60 #include <BasicUsageEnvironment.hh>
61 #include <GroupsockHelper.hh>
62 #include <liveMedia.hh>
63 #include <liveMedia_version.hh>
64
65 extern "C" {
66 #include "../access/mms/asf.h"  /* Who said ugly ? */
67 }
68
69 using namespace std;
70
71 /*****************************************************************************
72  * Module descriptor
73  *****************************************************************************/
74 static int  Open ( vlc_object_t * );
75 static void Close( vlc_object_t * );
76
77 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
78 #define KASENNA_LONGTEXT N_( "Kasenna servers use an old and nonstandard " \
79     "dialect of RTSP. With this parameter VLC will try this dialect, but "\
80     "then it cannot connect to normal RTSP servers." )
81
82 #define WMSERVER_TEXT N_("WMServer RTSP dialect")
83 #define WMSERVER_LONGTEXT N_("WMServer uses a nonstandard dialect " \
84     "of RTSP. Selecting this parameter will tell VLC to assume some " \
85     "options contrary to RFC 2326 guidelines.")
86
87 #define USER_TEXT N_("RTSP user name")
88 #define USER_LONGTEXT N_("Sets the username for the connection, " \
89     "if no username or password are set in the url.")
90 #define PASS_TEXT N_("RTSP password")
91 #define PASS_LONGTEXT N_("Sets the password for the connection, " \
92     "if no username or password are set in the url.")
93
94 vlc_module_begin ()
95     set_description( N_("RTP/RTSP/SDP demuxer (using Live555)" ) )
96     set_capability( "demux", 50 )
97     set_shortname( "RTP/RTSP")
98     set_callbacks( Open, Close )
99     add_shortcut( "live", "livedotcom" )
100     set_category( CAT_INPUT )
101     set_subcategory( SUBCAT_INPUT_DEMUX )
102
103     add_submodule ()
104         set_description( N_("RTSP/RTP access and demux") )
105         add_shortcut( "rtsp", "pnm", "live", "livedotcom" )
106         set_capability( "access_demux", 0 )
107         set_callbacks( Open, Close )
108         add_bool( "rtsp-tcp", false,
109                   N_("Use RTP over RTSP (TCP)"),
110                   N_("Use RTP over RTSP (TCP)"), true )
111             change_safe()
112         add_integer( "rtp-client-port", -1,
113                   N_("Client port"),
114                   N_("Port to use for the RTP source of the session"), true )
115         add_bool( "rtsp-mcast", false,
116                   N_("Force multicast RTP via RTSP"),
117                   N_("Force multicast RTP via RTSP"), true )
118             change_safe()
119         add_bool( "rtsp-http", false,
120                   N_("Tunnel RTSP and RTP over HTTP"),
121                   N_("Tunnel RTSP and RTP over HTTP"), true )
122             change_safe()
123         add_integer( "rtsp-http-port", 80,
124                   N_("HTTP tunnel port"),
125                   N_("Port to use for tunneling the RTSP/RTP over HTTP."),
126                   true )
127         add_bool(   "rtsp-kasenna", false, KASENNA_TEXT,
128                     KASENNA_LONGTEXT, true )
129             change_safe()
130         add_bool(   "rtsp-wmserver", false, WMSERVER_TEXT,
131                     WMSERVER_LONGTEXT, true)
132             change_safe()
133         add_string( "rtsp-user", NULL, USER_TEXT,
134                     USER_LONGTEXT, true )
135             change_safe()
136         add_password( "rtsp-pwd", NULL, PASS_TEXT,
137                       PASS_LONGTEXT, true )
138             change_safe()
139 vlc_module_end ()
140
141
142 /*****************************************************************************
143  * Local prototypes
144  *****************************************************************************/
145
146 typedef struct
147 {
148     demux_t         *p_demux;
149     MediaSubsession *sub;
150
151     es_format_t     fmt;
152     es_out_id_t     *p_es;
153
154     bool            b_muxed;
155     bool            b_quicktime;
156     bool            b_asf;
157     block_t         *p_asf_block;
158     bool            b_discard_trunc;
159     stream_t        *p_out_muxed;    /* for muxed stream */
160
161     uint8_t         *p_buffer;
162     unsigned int    i_buffer;
163
164     bool            b_rtcp_sync;
165     char            waiting;
166     int64_t         i_pts;
167     double          f_npt;
168
169     bool            b_selected;
170
171 } live_track_t;
172
173 struct timeout_thread_t
174 {
175     demux_sys_t  *p_sys;
176     vlc_thread_t handle;
177     bool         b_handle_keep_alive;
178 };
179
180 class RTSPClientVlc;
181
182 struct demux_sys_t
183 {
184     char            *p_sdp;    /* XXX mallocated */
185     char            *psz_path; /* URL-encoded path */
186     vlc_url_t       url;
187
188     MediaSession     *ms;
189     TaskScheduler    *scheduler;
190     UsageEnvironment *env ;
191     RTSPClientVlc    *rtsp;
192
193     /* */
194     int              i_track;
195     live_track_t     **track;
196
197     /* Weird formats */
198     asf_header_t     asfh;
199     stream_t         *p_out_asf;
200     bool             b_real;
201
202     /* */
203     int64_t          i_pcr; /* The clock */
204     double           f_npt;
205     double           f_npt_length;
206     double           f_npt_start;
207
208     /* timeout thread information */
209     int              i_timeout;     /* session timeout value in seconds */
210     bool             b_timeout_call;/* mark to send an RTSP call to prevent server timeout */
211     timeout_thread_t *p_timeout;    /* the actual thread that makes sure we don't timeout */
212
213     /* */
214     bool             b_force_mcast;
215     bool             b_multicast;   /* if one of the tracks is multicasted */
216     bool             b_no_data;     /* if we never received any data */
217     int              i_no_data_ti;  /* consecutive number of TaskInterrupt */
218
219     char             event_rtsp;
220     char             event_data;
221
222     bool             b_get_param;   /* Does the server support GET_PARAMETER */
223     bool             b_paused;      /* Are we paused? */
224     bool             b_error;
225     int              i_live555_ret; /* live555 callback return code */
226
227     float            f_seek_request;/* In case we receive a seek request while paused*/
228 };
229
230
231 class RTSPClientVlc : public RTSPClient
232 {
233 public:
234     RTSPClientVlc( UsageEnvironment& env, char const* rtspURL, int verbosityLevel,
235                    char const* applicationName, portNumBits tunnelOverHTTPPortNum,
236                    demux_sys_t *p_sys) :
237                    RTSPClient( env, rtspURL, verbosityLevel, applicationName,
238                    tunnelOverHTTPPortNum )
239     {
240         this->p_sys = p_sys;
241     }
242     demux_sys_t *p_sys;
243 };
244
245 static int Demux  ( demux_t * );
246 static int Control( demux_t *, int, va_list );
247
248 static int Connect      ( demux_t * );
249 static int SessionsSetup( demux_t * );
250 static int Play         ( demux_t *);
251 static int ParseASF     ( demux_t * );
252 static int RollOverTcp  ( demux_t * );
253
254 static void StreamRead  ( void *, unsigned int, unsigned int,
255                           struct timeval, unsigned int );
256 static void StreamClose ( void * );
257 static void TaskInterruptData( void * );
258 static void TaskInterruptRTSP( void * );
259
260 static void* TimeoutPrevention( void * );
261
262 static unsigned char* parseH264ConfigStr( char const* configStr,
263                                           unsigned int& configSize );
264
265 /*****************************************************************************
266  * DemuxOpen:
267  *****************************************************************************/
268 static int  Open ( vlc_object_t *p_this )
269 {
270     demux_t     *p_demux = (demux_t*)p_this;
271     demux_sys_t *p_sys = NULL;
272
273     int i_return;
274     int i_error = VLC_EGENERIC;
275
276     if( p_demux->s )
277     {
278         /* See if it looks like a SDP
279            v, o, s fields are mandatory and in this order */
280         const uint8_t *p_peek;
281         if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
282
283         if( memcmp( p_peek, "v=0\r\n", 5 ) &&
284             memcmp( p_peek, "v=0\n", 4 ) &&
285             ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
286         {
287             return VLC_EGENERIC;
288         }
289     }
290
291     p_demux->pf_demux  = Demux;
292     p_demux->pf_control= Control;
293     p_demux->p_sys     = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
294     if( !p_sys ) return VLC_ENOMEM;
295
296     msg_Dbg( p_demux, "version "LIVEMEDIA_LIBRARY_VERSION_STRING );
297
298     p_sys->p_sdp = NULL;
299     p_sys->scheduler = NULL;
300     p_sys->env = NULL;
301     p_sys->ms = NULL;
302     p_sys->rtsp = NULL;
303     TAB_INIT( p_sys->i_track, p_sys->track );
304     p_sys->i_pcr = 0;
305     p_sys->f_npt = 0.;
306     p_sys->f_npt_start = 0.;
307     p_sys->f_npt_length = 0.;
308     p_sys->p_out_asf = NULL;
309     p_sys->b_no_data = true;
310     p_sys->i_no_data_ti = 0;
311     p_sys->p_timeout = NULL;
312     p_sys->i_timeout = 0;
313     p_sys->b_timeout_call = false;
314     p_sys->b_multicast = false;
315     p_sys->b_real = false;
316     p_sys->psz_path = strdup( p_demux->psz_location );
317     p_sys->b_force_mcast = var_InheritBool( p_demux, "rtsp-mcast" );
318     p_sys->b_get_param = false;
319     p_sys->b_paused = false;
320     p_sys->f_seek_request = -1;
321     p_sys->b_error = false;
322     p_sys->i_live555_ret = 0;
323
324     /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
325     vlc_UrlParse( &p_sys->url, p_sys->psz_path, 0 );
326
327     if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
328     {
329         msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
330         goto error;
331     }
332     if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
333     {
334         msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
335         goto error;
336     }
337
338     if( strcasecmp( p_demux->psz_access, "sdp" ) )
339     {
340         char *p = p_sys->psz_path;
341         while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
342     }
343
344     if( p_demux->s != NULL )
345     {
346         /* Gather the complete sdp file */
347         int     i_sdp       = 0;
348         int     i_sdp_max   = 1000;
349         uint8_t *p_sdp      = (uint8_t*) malloc( i_sdp_max );
350
351         if( !p_sdp )
352         {
353             i_error = VLC_ENOMEM;
354             goto error;
355         }
356
357         for( ;; )
358         {
359             int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
360                                       i_sdp_max - i_sdp - 1 );
361
362             if( !vlc_object_alive (p_demux) )
363             {
364                 free( p_sdp );
365                 goto error;
366             }
367
368             if( i_read < 0 )
369             {
370                 msg_Err( p_demux, "failed to read SDP" );
371                 free( p_sdp );
372                 goto error;
373             }
374
375             i_sdp += i_read;
376
377             if( i_read < i_sdp_max - i_sdp - 1 )
378             {
379                 p_sdp[i_sdp] = '\0';
380                 break;
381             }
382
383             i_sdp_max += 1000;
384             p_sdp = (uint8_t*)xrealloc( p_sdp, i_sdp_max );
385         }
386         p_sys->p_sdp = (char*)p_sdp;
387     }
388     else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
389     {
390         msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
391         goto error;
392     }
393
394     if( p_sys->p_sdp == NULL )
395     {
396         msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
397         i_error = VLC_ENOMEM;
398         goto error;
399     }
400
401     if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
402     {
403         msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
404         goto error;
405     }
406
407     if( p_sys->b_real ) goto error;
408
409     if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
410         goto error;
411
412     if( p_sys->p_out_asf && ParseASF( p_demux ) )
413     {
414         msg_Err( p_demux, "cannot find a usable asf header" );
415         /* TODO Clean tracks */
416         goto error;
417     }
418
419     if( p_sys->i_track <= 0 )
420         goto error;
421
422     return VLC_SUCCESS;
423
424 error:
425     Close( p_this );
426     return i_error;
427 }
428
429 /*****************************************************************************
430  * DemuxClose:
431  *****************************************************************************/
432 static void Close( vlc_object_t *p_this )
433 {
434     demux_t *p_demux = (demux_t*)p_this;
435     demux_sys_t *p_sys = p_demux->p_sys;
436
437     if( p_sys->p_timeout )
438     {
439         vlc_cancel( p_sys->p_timeout->handle );
440         vlc_join( p_sys->p_timeout->handle, NULL );
441         free( p_sys->p_timeout );
442     }
443
444     if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
445     if( p_sys->ms ) Medium::close( p_sys->ms );
446     if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
447     if( p_sys->env ) p_sys->env->reclaim();
448
449     for( int i = 0; i < p_sys->i_track; i++ )
450     {
451         live_track_t *tk = p_sys->track[i];
452
453         if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
454         es_format_Clean( &tk->fmt );
455         free( tk->p_buffer );
456         free( tk );
457     }
458     TAB_CLEAN( p_sys->i_track, p_sys->track );
459     if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
460     delete p_sys->scheduler;
461     free( p_sys->p_sdp );
462     free( p_sys->psz_path );
463
464     vlc_UrlClean( &p_sys->url );
465
466     free( p_sys );
467 }
468
469 static inline const char *strempty( const char *s ) { return s?s:""; }
470 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
471
472 static void default_live555_callback( RTSPClient* client, int result_code, char* result_string )
473 {
474     RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
475     demux_sys_t *p_sys = client_vlc->p_sys;
476     delete []result_string;
477     p_sys->i_live555_ret = result_code;
478     p_sys->b_error = p_sys->i_live555_ret != 0;
479     p_sys->event_rtsp = 1;
480 }
481
482 /* return true if the RTSP command succeeded */
483 static bool wait_Live555_response( demux_t *p_demux, int i_timeout = 0 /* ms */ )
484 {
485     TaskToken task;
486     demux_sys_t * p_sys = p_demux->p_sys;
487     p_sys->event_rtsp = 0;
488     if( i_timeout > 0 )
489     {
490         /* Create a task that will be called if we wait more than timeout ms */
491         task = p_sys->scheduler->scheduleDelayedTask( i_timeout*1000,
492                                                       TaskInterruptRTSP,
493                                                       p_demux );
494     }
495     p_sys->event_rtsp = 0;
496     p_sys->b_error = true;
497     p_sys->i_live555_ret = 0;
498     p_sys->scheduler->doEventLoop( &p_sys->event_rtsp );
499     //here, if b_error is true and i_live555_ret = 0 we didn't receive a response
500     if( i_timeout > 0 )
501     {
502         /* remove the task */
503         p_sys->scheduler->unscheduleDelayedTask( task );
504     }
505     return !p_sys->b_error;
506 }
507
508 static void continueAfterDESCRIBE( RTSPClient* client, int result_code,
509                                    char* result_string )
510 {
511     RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> ( client );
512     demux_sys_t *p_sys = client_vlc->p_sys;
513     p_sys->i_live555_ret = result_code;
514     if ( result_code == 0 )
515     {
516         char* sdpDescription = result_string;
517         free( p_sys->p_sdp );
518         p_sys->p_sdp = NULL;
519         if( sdpDescription )
520         {
521             p_sys->p_sdp = strdup( sdpDescription );
522             p_sys->b_error = false;
523         }
524     }
525     else
526         p_sys->b_error = true;
527     delete[] result_string;
528     p_sys->event_rtsp = 1;
529 }
530
531 static void continueAfterOPTIONS( RTSPClient* client, int result_code,
532                                   char* result_string )
533 {
534     RTSPClientVlc *client_vlc = static_cast<RTSPClientVlc *> (client);
535     demux_sys_t *p_sys = client_vlc->p_sys;
536     p_sys->i_live555_ret = result_code;
537     if ( result_code != 0 )
538     {
539         p_sys->b_error = true;
540         p_sys->event_rtsp = 1;
541     }
542     else
543     {
544         p_sys->b_get_param = result_string != NULL && strstr( result_string, "GET_PARAMETER" ) != NULL;
545         client->sendDescribeCommand( continueAfterDESCRIBE );
546     }
547     delete[] result_string;
548 }
549
550 /*****************************************************************************
551  * Connect: connects to the RTSP server to setup the session DESCRIBE
552  *****************************************************************************/
553 static int Connect( demux_t *p_demux )
554 {
555     demux_sys_t *p_sys = p_demux->p_sys;
556     Authenticator authenticator;
557     char *psz_user    = NULL;
558     char *psz_pwd     = NULL;
559     char *psz_url     = NULL;
560     int  i_http_port  = 0;
561     int  i_ret        = VLC_SUCCESS;
562     const int i_timeout = var_InheritInteger( p_demux, "ipv4-timeout" );
563
564     /* Get the user name and password */
565     if( p_sys->url.psz_username || p_sys->url.psz_password )
566     {
567         /* Create the URL by stripping away the username/password part */
568         if( p_sys->url.i_port == 0 )
569             p_sys->url.i_port = 554;
570         if( asprintf( &psz_url, "rtsp://%s:%d%s",
571                       strempty( p_sys->url.psz_host ),
572                       p_sys->url.i_port,
573                       strempty( p_sys->url.psz_path ) ) == -1 )
574             return VLC_ENOMEM;
575
576         psz_user = strdup( strempty( p_sys->url.psz_username ) );
577         psz_pwd  = strdup( strempty( p_sys->url.psz_password ) );
578     }
579     else
580     {
581         if( asprintf( &psz_url, "rtsp://%s", p_sys->psz_path ) == -1 )
582             return VLC_ENOMEM;
583
584         psz_user = var_InheritString( p_demux, "rtsp-user" );
585         psz_pwd  = var_InheritString( p_demux, "rtsp-pwd" );
586     }
587
588 createnew:
589     if( !vlc_object_alive (p_demux) )
590     {
591         i_ret = VLC_EGENERIC;
592         goto bailout;
593     }
594
595     if( var_CreateGetBool( p_demux, "rtsp-http" ) )
596         i_http_port = var_InheritInteger( p_demux, "rtsp-http-port" );
597
598     p_sys->rtsp = new RTSPClientVlc( *p_sys->env, psz_url,
599                                      var_InheritInteger( p_demux, "verbose" ) > 1 ? 1 : 0,
600                                      "LibVLC/"VERSION, i_http_port, p_sys );
601     if( !p_sys->rtsp )
602     {
603         msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
604                  p_sys->env->getResultMsg() );
605         i_ret = VLC_EGENERIC;
606         goto bailout;
607     }
608
609     /* Kasenna enables KeepAlive by analysing the User-Agent string.
610      * Appending _KA to the string should be enough to enable this feature,
611      * however, there is a bug where the _KA doesn't get parsed from the
612      * default User-Agent as created by VLC/Live555 code. This is probably due
613      * to spaces in the string or the string being too long. Here we override
614      * the default string with a more compact version.
615      */
616     if( var_InheritBool( p_demux, "rtsp-kasenna" ))
617     {
618         p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
619     }
620
621 describe:
622     authenticator.setUsernameAndPassword( psz_user, psz_pwd );
623
624     p_sys->rtsp->sendOptionsCommand( &continueAfterOPTIONS, &authenticator );
625
626     if( !wait_Live555_response( p_demux, i_timeout ) )
627     {
628         int i_code = p_sys->i_live555_ret;
629         if( i_code == 401 )
630         {
631             msg_Dbg( p_demux, "authentication failed" );
632
633             free( psz_user );
634             free( psz_pwd );
635             dialog_Login( p_demux, &psz_user, &psz_pwd,
636                           _("RTSP authentication"), "%s",
637                         _("Please enter a valid login name and a password.") );
638             if( psz_user != NULL && psz_pwd != NULL )
639             {
640                 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
641                 goto describe;
642             }
643         }
644         else if( i_code > 0 && i_code != 404 && !var_GetBool( p_demux, "rtsp-http" ) )
645         {
646             /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
647             msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
648             var_SetBool( p_demux, "rtsp-http", true );
649             if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
650             p_sys->rtsp = NULL;
651             goto createnew;
652         }
653         else
654         {
655             if( i_code == 0 )
656                 msg_Dbg( p_demux, "connection timeout" );
657             else
658             {
659                 msg_Dbg( p_demux, "connection error %d", i_code );
660                 if( i_code == 403 )
661                     dialog_Fatal( p_demux, _("RTSP connection failed"),
662                                   _("Access to the stream is denied by the server configuration.") );
663             }
664             if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
665             p_sys->rtsp = NULL;
666         }
667         i_ret = VLC_EGENERIC;
668     }
669
670 bailout:
671     /* malloc-ated copy */
672     free( psz_url );
673     free( psz_user );
674     free( psz_pwd );
675
676     return i_ret;
677 }
678
679 /*****************************************************************************
680  * SessionsSetup: prepares the subsessions and does the SETUP
681  *****************************************************************************/
682 static int SessionsSetup( demux_t *p_demux )
683 {
684     demux_sys_t             *p_sys  = p_demux->p_sys;
685     MediaSubsessionIterator *iter   = NULL;
686     MediaSubsession         *sub    = NULL;
687
688     bool           b_rtsp_tcp;
689     int            i_client_port;
690     int            i_return = VLC_SUCCESS;
691     unsigned int   i_buffer = 0;
692     unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
693
694     b_rtsp_tcp    = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
695                     var_GetBool( p_demux, "rtsp-http" );
696     i_client_port = var_InheritInteger( p_demux, "rtp-client-port" );
697
698     /* Create the session from the SDP */
699     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
700     {
701         msg_Err( p_demux, "Could not create the RTSP Session: %s",
702             p_sys->env->getResultMsg() );
703         return VLC_EGENERIC;
704     }
705
706     /* Initialise each media subsession */
707     iter = new MediaSubsessionIterator( *p_sys->ms );
708     while( ( sub = iter->next() ) != NULL )
709     {
710         Boolean bInit;
711         live_track_t *tk;
712
713         if( !vlc_object_alive (p_demux) )
714         {
715             delete iter;
716             return VLC_EGENERIC;
717         }
718
719         /* Value taken from mplayer */
720         if( !strcmp( sub->mediumName(), "audio" ) )
721             i_buffer = 100000;
722         else if( !strcmp( sub->mediumName(), "video" ) )
723             i_buffer = 2000000;
724         else if( !strcmp( sub->mediumName(), "text" ) )
725             ;
726         else continue;
727
728         if( i_client_port != -1 )
729         {
730             sub->setClientPortNum( i_client_port );
731             i_client_port += 2;
732         }
733
734         if( strcasestr( sub->codecName(), "REAL" ) )
735         {
736             msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
737             p_sys->b_real = true; /* This is a problem, we'll handle it later */
738             continue;
739         }
740
741         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
742             bInit = sub->initiate( 0 );
743         else
744             bInit = sub->initiate();
745
746         if( !bInit )
747         {
748             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
749                       sub->mediumName(), sub->codecName(),
750                       p_sys->env->getResultMsg() );
751         }
752         else
753         {
754             if( sub->rtpSource() != NULL )
755             {
756                 int fd = sub->rtpSource()->RTPgs()->socketNum();
757
758                 /* Increase the buffer size */
759                 if( i_buffer > 0 )
760                     increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
761
762                 /* Increase the RTP reorder timebuffer just a bit */
763                 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
764             }
765             msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
766                      sub->codecName() );
767
768             /* Issue the SETUP */
769             if( p_sys->rtsp )
770             {
771                 p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
772                                                toBool( b_rtsp_tcp ),
773                                                toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
774                 if( !wait_Live555_response( p_demux ) )
775                 {
776                     /* if we get an unsupported transport error, toggle TCP
777                      * use and try again */
778                     if( p_sys->i_live555_ret == 461 )
779                         p_sys->rtsp->sendSetupCommand( *sub, default_live555_callback, False,
780                                                        !toBool( b_rtsp_tcp ), False );
781                     if( p_sys->i_live555_ret != 461 || !wait_Live555_response( p_demux ) )
782                     {
783                         msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
784                                  sub->mediumName(), sub->codecName(),
785                                  p_sys->env->getResultMsg() );
786                         continue;
787                     }
788                     else
789                     {
790                         var_SetBool( p_demux, "rtsp-tcp", true );
791                         b_rtsp_tcp = true;
792                     }
793                 }
794             }
795
796             /* Check if we will receive data from this subsession for
797              * this track */
798             if( sub->readSource() == NULL ) continue;
799             if( !p_sys->b_multicast )
800             {
801                 /* We need different rollover behaviour for multicast */
802                 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
803             }
804
805             tk = (live_track_t*)malloc( sizeof( live_track_t ) );
806             if( !tk )
807             {
808                 delete iter;
809                 return VLC_ENOMEM;
810             }
811             tk->p_demux     = p_demux;
812             tk->sub         = sub;
813             tk->p_es        = NULL;
814             tk->b_quicktime = false;
815             tk->b_asf       = false;
816             tk->p_asf_block = NULL;
817             tk->b_muxed     = false;
818             tk->b_discard_trunc = false;
819             tk->p_out_muxed = NULL;
820             tk->waiting     = 0;
821             tk->b_rtcp_sync = false;
822             tk->i_pts       = VLC_TS_INVALID;
823             tk->f_npt       = 0.;
824             tk->b_selected  = true;
825             tk->i_buffer    = 65536;
826             tk->p_buffer    = (uint8_t *)malloc( 65536 );
827             if( !tk->p_buffer )
828             {
829                 free( tk );
830                 delete iter;
831                 return VLC_ENOMEM;
832             }
833
834             /* Value taken from mplayer */
835             if( !strcmp( sub->mediumName(), "audio" ) )
836             {
837                 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
838                 tk->fmt.audio.i_channels = sub->numChannels();
839                 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
840
841                 if( !strcmp( sub->codecName(), "MPA" ) ||
842                     !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
843                     !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
844                 {
845                     tk->fmt.i_codec = VLC_CODEC_MPGA;
846                     tk->fmt.audio.i_rate = 0;
847                 }
848                 else if( !strcmp( sub->codecName(), "AC3" ) )
849                 {
850                     tk->fmt.i_codec = VLC_CODEC_A52;
851                     tk->fmt.audio.i_rate = 0;
852                 }
853                 else if( !strcmp( sub->codecName(), "L16" ) )
854                 {
855                     tk->fmt.i_codec = VLC_CODEC_S16B;
856                     tk->fmt.audio.i_bitspersample = 16;
857                 }
858                 else if( !strcmp( sub->codecName(), "L20" ) )
859                 {
860                     tk->fmt.i_codec = VLC_CODEC_S20B;
861                     tk->fmt.audio.i_bitspersample = 20;
862                 }
863                 else if( !strcmp( sub->codecName(), "L24" ) )
864                 {
865                     tk->fmt.i_codec = VLC_CODEC_S24B;
866                     tk->fmt.audio.i_bitspersample = 24;
867                 }
868                 else if( !strcmp( sub->codecName(), "L8" ) )
869                 {
870                     tk->fmt.i_codec = VLC_CODEC_U8;
871                     tk->fmt.audio.i_bitspersample = 8;
872                 }
873                 else if( !strcmp( sub->codecName(), "DAT12" ) )
874                 {
875                     tk->fmt.i_codec = VLC_CODEC_DAT12;
876                     tk->fmt.audio.i_bitspersample = 12;
877                 }
878                 else if( !strcmp( sub->codecName(), "PCMU" ) )
879                 {
880                     tk->fmt.i_codec = VLC_CODEC_MULAW;
881                     tk->fmt.audio.i_bitspersample = 8;
882                 }
883                 else if( !strcmp( sub->codecName(), "PCMA" ) )
884                 {
885                     tk->fmt.i_codec = VLC_CODEC_ALAW;
886                     tk->fmt.audio.i_bitspersample = 8;
887                 }
888                 else if( !strncmp( sub->codecName(), "G726", 4 ) )
889                 {
890                     tk->fmt.i_codec = VLC_CODEC_ADPCM_G726;
891                     tk->fmt.audio.i_rate = 8000;
892                     tk->fmt.audio.i_channels = 1;
893                     if( !strcmp( sub->codecName()+5, "40" ) )
894                         tk->fmt.i_bitrate = 40000;
895                     else if( !strcmp( sub->codecName()+5, "32" ) )
896                         tk->fmt.i_bitrate = 32000;
897                     else if( !strcmp( sub->codecName()+5, "24" ) )
898                         tk->fmt.i_bitrate = 24000;
899                     else if( !strcmp( sub->codecName()+5, "16" ) )
900                         tk->fmt.i_bitrate = 16000;
901                 }
902                 else if( !strcmp( sub->codecName(), "AMR" ) )
903                 {
904                     tk->fmt.i_codec = VLC_CODEC_AMR_NB;
905                 }
906                 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
907                 {
908                     tk->fmt.i_codec = VLC_CODEC_AMR_WB;
909                 }
910                 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
911                 {
912                     unsigned int i_extra;
913                     uint8_t      *p_extra;
914
915                     tk->fmt.i_codec = VLC_CODEC_MP4A;
916
917                     if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
918                                                              i_extra ) ) )
919                     {
920                         tk->fmt.i_extra = i_extra;
921                         tk->fmt.p_extra = xmalloc( i_extra );
922                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
923                         delete[] p_extra;
924                     }
925                     /* Because the "faad" decoder does not handle the LATM
926                      * data length field at the start of each returned LATM
927                      * frame, tell the RTP source to omit it. */
928                     ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
929                 }
930                 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
931                 {
932                     unsigned int i_extra;
933                     uint8_t      *p_extra;
934
935                     tk->fmt.i_codec = VLC_CODEC_MP4A;
936
937                     if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
938                                                            i_extra ) ) )
939                     {
940                         tk->fmt.i_extra = i_extra;
941                         tk->fmt.p_extra = xmalloc( i_extra );
942                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
943                         delete[] p_extra;
944                     }
945                 }
946                 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
947                 {
948                     tk->b_asf = true;
949                     if( p_sys->p_out_asf == NULL )
950                         p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
951                                                             p_demux->out );
952                 }
953                 else if( !strcmp( sub->codecName(), "X-QT" ) ||
954                          !strcmp( sub->codecName(), "X-QUICKTIME" ) )
955                 {
956                     tk->b_quicktime = true;
957                 }
958                 else if( !strcmp( sub->codecName(), "SPEEX" ) )
959                 {
960                     tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
961                     if ( sub->rtpTimestampFrequency() )
962                         tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
963                     else
964                     {
965                         msg_Warn( p_demux,"Using 8kHz as default sample rate." );
966                         tk->fmt.audio.i_rate = 8000;
967                     }
968                 }
969             }
970             else if( !strcmp( sub->mediumName(), "video" ) )
971             {
972                 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
973                 if( !strcmp( sub->codecName(), "MPV" ) )
974                 {
975                     tk->fmt.i_codec = VLC_CODEC_MPGV;
976                     tk->fmt.b_packetized = false;
977                 }
978                 else if( !strcmp( sub->codecName(), "H263" ) ||
979                          !strcmp( sub->codecName(), "H263-1998" ) ||
980                          !strcmp( sub->codecName(), "H263-2000" ) )
981                 {
982                     tk->fmt.i_codec = VLC_CODEC_H263;
983                 }
984                 else if( !strcmp( sub->codecName(), "H261" ) )
985                 {
986                     tk->fmt.i_codec = VLC_CODEC_H261;
987                 }
988                 else if( !strcmp( sub->codecName(), "H264" ) )
989                 {
990                     unsigned int i_extra = 0;
991                     uint8_t      *p_extra = NULL;
992
993                     tk->fmt.i_codec = VLC_CODEC_H264;
994                     tk->fmt.b_packetized = false;
995
996                     if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
997                                                     i_extra ) ) )
998                     {
999                         tk->fmt.i_extra = i_extra;
1000                         tk->fmt.p_extra = xmalloc( i_extra );
1001                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
1002
1003                         delete[] p_extra;
1004                     }
1005                 }
1006                 else if( !strcmp( sub->codecName(), "JPEG" ) )
1007                 {
1008                     tk->fmt.i_codec = VLC_CODEC_MJPG;
1009                 }
1010                 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
1011                 {
1012                     unsigned int i_extra;
1013                     uint8_t      *p_extra;
1014
1015                     tk->fmt.i_codec = VLC_CODEC_MP4V;
1016
1017                     if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
1018                                                            i_extra ) ) )
1019                     {
1020                         tk->fmt.i_extra = i_extra;
1021                         tk->fmt.p_extra = xmalloc( i_extra );
1022                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
1023                         delete[] p_extra;
1024                     }
1025                 }
1026                 else if( !strcmp( sub->codecName(), "X-QT" ) ||
1027                          !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
1028                          !strcmp( sub->codecName(), "X-QDM" ) ||
1029                          !strcmp( sub->codecName(), "X-SV3V-ES" )  ||
1030                          !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
1031                 {
1032                     tk->b_quicktime = true;
1033                 }
1034                 else if( !strcmp( sub->codecName(), "MP2T" ) )
1035                 {
1036                     tk->b_muxed = true;
1037                     tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
1038                 }
1039                 else if( !strcmp( sub->codecName(), "MP2P" ) ||
1040                          !strcmp( sub->codecName(), "MP1S" ) )
1041                 {
1042                     tk->b_muxed = true;
1043                     tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
1044                                                        p_demux->out );
1045                 }
1046                 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1047                 {
1048                     tk->b_asf = true;
1049                     if( p_sys->p_out_asf == NULL )
1050                         p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
1051                                                             p_demux->out );;
1052                 }
1053                 else if( !strcmp( sub->codecName(), "DV" ) )
1054                 {
1055                     tk->b_muxed = true;
1056                     tk->b_discard_trunc = true;
1057                     tk->p_out_muxed = stream_DemuxNew( p_demux, "rawdv",
1058                                                        p_demux->out );
1059                 }
1060             }
1061             else if( !strcmp( sub->mediumName(), "text" ) )
1062             {
1063                 es_format_Init( &tk->fmt, SPU_ES, VLC_FOURCC('u','n','d','f') );
1064
1065                 if( !strcmp( sub->codecName(), "T140" ) )
1066                 {
1067                     tk->fmt.i_codec = VLC_CODEC_ITU_T140;
1068                 }
1069             }
1070
1071             if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
1072             {
1073                 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1074             }
1075
1076             if( sub->rtcpInstance() != NULL )
1077             {
1078                 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1079             }
1080
1081             if( tk->p_es || tk->b_quicktime || ( tk->b_muxed && tk->p_out_muxed ) ||
1082                 ( tk->b_asf && p_sys->p_out_asf ) )
1083             {
1084                 TAB_APPEND_CAST( (live_track_t **), p_sys->i_track, p_sys->track, tk );
1085             }
1086             else
1087             {
1088                 /* BUG ??? */
1089                 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1090                 es_format_Clean( &tk->fmt );
1091                 free( tk );
1092             }
1093         }
1094     }
1095     delete iter;
1096     if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1097
1098     /* Retrieve the starttime if possible */
1099     p_sys->f_npt_start = p_sys->ms->playStartTime();
1100
1101     /* Retrieve the duration if possible */
1102     p_sys->f_npt_length = p_sys->ms->playEndTime();
1103
1104     /* */
1105     msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1106
1107     /* */
1108     p_sys->b_no_data = true;
1109     p_sys->i_no_data_ti = 0;
1110
1111     return i_return;
1112 }
1113
1114 /*****************************************************************************
1115  * Play: starts the actual playback of the stream
1116  *****************************************************************************/
1117 static int Play( demux_t *p_demux )
1118 {
1119     demux_sys_t *p_sys = p_demux->p_sys;
1120
1121     if( p_sys->rtsp )
1122     {
1123         /* The PLAY */
1124         p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_npt_start, -1, 1 );
1125
1126         if( !wait_Live555_response(p_demux) )
1127         {
1128             msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1129             return VLC_EGENERIC;
1130         }
1131
1132         /* Retrieve the timeout value and set up a timeout prevention thread */
1133         p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
1134         if( p_sys->i_timeout <= 0 )
1135             p_sys->i_timeout = 60; /* default value from RFC2326 */
1136
1137         /* start timeout-thread only if GET_PARAMETER is supported by the server */
1138         if( !p_sys->p_timeout && p_sys->b_get_param )
1139         {
1140             msg_Dbg( p_demux, "We have a timeout of %d seconds",  p_sys->i_timeout );
1141             p_sys->p_timeout = (timeout_thread_t *)malloc( sizeof(timeout_thread_t) );
1142             if( p_sys->p_timeout )
1143             {
1144                 memset( p_sys->p_timeout, 0, sizeof(timeout_thread_t) );
1145                 p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
1146                 if( vlc_clone( &p_sys->p_timeout->handle,  TimeoutPrevention,
1147                                p_sys->p_timeout, VLC_THREAD_PRIORITY_LOW ) )
1148                 {
1149                     msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1150                     free( p_sys->p_timeout );
1151                     p_sys->p_timeout = NULL;
1152                 }
1153                 else
1154                     msg_Dbg( p_demux, "spawned timeout thread" );
1155             }
1156             else
1157                 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1158         }
1159     }
1160     p_sys->i_pcr = 0;
1161
1162     /* Retrieve the starttime if possible */
1163     p_sys->f_npt_start = p_sys->ms->playStartTime();
1164     if( p_sys->ms->playEndTime() > 0 )
1165         p_sys->f_npt_length = p_sys->ms->playEndTime();
1166
1167     msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1168     return VLC_SUCCESS;
1169 }
1170
1171
1172 /*****************************************************************************
1173  * Demux:
1174  *****************************************************************************/
1175 static int Demux( demux_t *p_demux )
1176 {
1177     demux_sys_t    *p_sys = p_demux->p_sys;
1178     TaskToken      task;
1179
1180     bool            b_send_pcr = true;
1181     int64_t         i_pcr = 0;
1182     int             i;
1183
1184     /* Check if we need to send the server a Keep-A-Live signal */
1185     if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
1186     {
1187         char *psz_bye = NULL;
1188         p_sys->rtsp->sendGetParameterCommand( *p_sys->ms, NULL, psz_bye );
1189         p_sys->b_timeout_call = false;
1190     }
1191
1192     for( i = 0; i < p_sys->i_track; i++ )
1193     {
1194         live_track_t *tk = p_sys->track[i];
1195
1196         if( tk->p_es )
1197         {
1198             bool b;
1199             es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1200             if( !b && tk->b_selected )
1201             {
1202                 tk->b_selected = false;
1203                 p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1204             }
1205             else if( b && !tk->b_selected)
1206             {
1207                 bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1208                                   var_GetBool( p_demux, "rtsp-http" );
1209                 p_sys->rtsp->sendSetupCommand( *tk->sub, default_live555_callback, False,
1210                                                toBool( b_rtsp_tcp ),
1211                                                toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) );
1212                 if( !wait_Live555_response( p_demux ) )
1213                 {
1214                     msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
1215                              tk->sub->mediumName(), tk->sub->codecName(),
1216                              p_sys->env->getResultMsg() );
1217                 }
1218                 else
1219                 {
1220                     p_sys->rtsp->sendPlayCommand( *tk->sub, default_live555_callback, -1, -1, p_sys->ms->scale() );
1221                     if( !wait_Live555_response(p_demux) )
1222                     {
1223                         msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1224                         p_sys->rtsp->sendTeardownCommand( *tk->sub, NULL );
1225                     }
1226                     else
1227                         tk->b_selected = true;
1228                 }
1229                 if( !tk->b_selected )
1230                     es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1231             }
1232         }
1233
1234         if( tk->b_asf || tk->b_muxed )
1235             b_send_pcr = false;
1236 #if 0
1237         if( i_pcr == 0 )
1238         {
1239             i_pcr = tk->i_pts;
1240         }
1241         else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
1242         {
1243             i_pcr = tk->i_pts ;
1244         }
1245 #endif
1246     }
1247     if( p_sys->i_pcr > 0 )
1248     {
1249         if( b_send_pcr )
1250             es_out_Control( p_demux->out, ES_OUT_SET_PCR, 1 + p_sys->i_pcr );
1251     }
1252
1253     /* First warn we want to read data */
1254     p_sys->event_data = 0;
1255     for( i = 0; i < p_sys->i_track; i++ )
1256     {
1257         live_track_t *tk = p_sys->track[i];
1258
1259         if( tk->waiting == 0 )
1260         {
1261             tk->waiting = 1;
1262             tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1263                                           StreamRead, tk, StreamClose, tk );
1264         }
1265     }
1266     /* Create a task that will be called if we wait more than 300ms */
1267     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterruptData, p_demux );
1268
1269     /* Do the read */
1270     p_sys->scheduler->doEventLoop( &p_sys->event_data );
1271
1272     /* remove the task */
1273     p_sys->scheduler->unscheduleDelayedTask( task );
1274
1275     /* Check for gap in pts value */
1276     for( i = 0; i < p_sys->i_track; i++ )
1277     {
1278         live_track_t *tk = p_sys->track[i];
1279
1280         if( !tk->b_muxed && !tk->b_rtcp_sync &&
1281             tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1282         {
1283             msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1284
1285             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1286             tk->b_rtcp_sync = true;
1287             /* reset PCR */
1288             tk->i_pts = VLC_TS_INVALID;
1289             tk->f_npt = 0.;
1290             p_sys->i_pcr = 0;
1291             p_sys->f_npt = 0.;
1292             i_pcr = 0;
1293         }
1294     }
1295
1296     if( p_sys->b_multicast && p_sys->b_no_data &&
1297         ( p_sys->i_no_data_ti > 120 ) )
1298     {
1299         /* FIXME Make this configurable
1300         msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1301         return 0;
1302         */
1303     }
1304     else if( !p_sys->b_multicast && !p_sys->b_paused &&
1305               p_sys->b_no_data && ( p_sys->i_no_data_ti > 34 ) )
1306     {
1307         bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1308                                 var_GetBool( p_demux, "rtsp-http" );
1309
1310         if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1311         {
1312             msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1313             if( RollOverTcp( p_demux ) )
1314             {
1315                 msg_Err( p_demux, "TCP rollover failed, aborting" );
1316                 return 0;
1317             }
1318             return 1;
1319         }
1320         msg_Err( p_demux, "no data received in 10s, aborting" );
1321         return 0;
1322     }
1323     else if( !p_sys->b_multicast && !p_sys->b_paused &&
1324              ( p_sys->i_no_data_ti > 34 ) )
1325     {
1326         /* EOF ? */
1327         msg_Warn( p_demux, "no data received in 10s, eof ?" );
1328         return 0;
1329     }
1330     return p_sys->b_error ? 0 : 1;
1331 }
1332
1333 /*****************************************************************************
1334  * Control:
1335  *****************************************************************************/
1336 static int Control( demux_t *p_demux, int i_query, va_list args )
1337 {
1338     demux_sys_t *p_sys = p_demux->p_sys;
1339     int64_t *pi64, i64;
1340     double  *pf, f;
1341     bool *pb, *pb2;
1342     int *pi_int;
1343
1344     switch( i_query )
1345     {
1346         case DEMUX_GET_TIME:
1347             pi64 = (int64_t*)va_arg( args, int64_t * );
1348             if( p_sys->f_npt > 0 )
1349             {
1350                 *pi64 = (int64_t)(p_sys->f_npt * 1000000.);
1351                 return VLC_SUCCESS;
1352             }
1353             return VLC_EGENERIC;
1354
1355         case DEMUX_GET_LENGTH:
1356             pi64 = (int64_t*)va_arg( args, int64_t * );
1357             if( p_sys->f_npt_length > 0 )
1358             {
1359                 double d_length = p_sys->f_npt_length * 1000000.0;
1360                 if( d_length >= INT64_MAX )
1361                     *pi64 = INT64_MAX;
1362                 else
1363                     *pi64 = (int64_t)d_length;
1364                 return VLC_SUCCESS;
1365             }
1366             return VLC_EGENERIC;
1367
1368         case DEMUX_GET_POSITION:
1369             pf = (double*)va_arg( args, double* );
1370             if( (p_sys->f_npt_length > 0) && (p_sys->f_npt > 0) )
1371             {
1372                 *pf = p_sys->f_npt / p_sys->f_npt_length;
1373                 return VLC_SUCCESS;
1374             }
1375             return VLC_EGENERIC;
1376
1377         case DEMUX_SET_POSITION:
1378         case DEMUX_SET_TIME:
1379             if( p_sys->rtsp && (p_sys->f_npt_length > 0) )
1380             {
1381                 int i;
1382                 float time;
1383
1384                 if( (i_query == DEMUX_SET_TIME) && (p_sys->f_npt > 0) )
1385                 {
1386                     i64 = (int64_t)va_arg( args, int64_t );
1387                     time = (float)(i64 / 1000000.0); /* in second */
1388                 }
1389                 else if( i_query == DEMUX_SET_TIME )
1390                     return VLC_EGENERIC;
1391                 else
1392                 {
1393                     f = (double)va_arg( args, double );
1394                     time = f * p_sys->f_npt_length;   /* in second */
1395                 }
1396
1397                 if( p_sys->b_paused )
1398                 {
1399                     p_sys->f_seek_request = time;
1400                     return VLC_SUCCESS;
1401                 }
1402
1403                 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1404
1405                 if( !wait_Live555_response( p_demux ) )
1406                 {
1407                     msg_Err( p_demux, "PAUSE before seek failed %s",
1408                         p_sys->env->getResultMsg() );
1409                     return VLC_EGENERIC;
1410                 }
1411
1412                 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, time, -1, 1 );
1413
1414                 if( !wait_Live555_response( p_demux ) )
1415                 {
1416                     msg_Err( p_demux, "seek PLAY failed %s",
1417                         p_sys->env->getResultMsg() );
1418                     return VLC_EGENERIC;
1419                 }
1420                 p_sys->i_pcr = 0;
1421
1422                 /* Retrieve RTP-Info values */
1423                 for( i = 0; i < p_sys->i_track; i++ )
1424                 {
1425                     p_sys->track[i]->b_rtcp_sync = false;
1426                     p_sys->track[i]->i_pts = VLC_TS_INVALID;
1427                 }
1428
1429                 /* Retrieve the starttime if possible */
1430                 p_sys->f_npt = p_sys->f_npt_start = p_sys->ms->playStartTime();
1431
1432                 /* Retrieve the duration if possible */
1433                 if( p_sys->ms->playEndTime() > 0 )
1434                     p_sys->f_npt_length = p_sys->ms->playEndTime();
1435
1436                 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1437                 return VLC_SUCCESS;
1438             }
1439             return VLC_EGENERIC;
1440
1441         /* Special for access_demux */
1442         case DEMUX_CAN_PAUSE:
1443         case DEMUX_CAN_SEEK:
1444             pb = (bool*)va_arg( args, bool * );
1445             if( p_sys->rtsp && p_sys->f_npt_length > 0 )
1446                 /* Not always true, but will be handled in SET_PAUSE_STATE */
1447                 *pb = true;
1448             else
1449                 *pb = false;
1450             return VLC_SUCCESS;
1451
1452         case DEMUX_CAN_CONTROL_PACE:
1453             pb = (bool*)va_arg( args, bool * );
1454
1455 #if 1       /* Disable for now until we have a clock synchro algo
1456              * which works with something else than MPEG over UDP */
1457             *pb = false;
1458 #else
1459             *pb = true;
1460 #endif
1461             return VLC_SUCCESS;
1462
1463         case DEMUX_CAN_CONTROL_RATE:
1464             pb = (bool*)va_arg( args, bool * );
1465             pb2 = (bool*)va_arg( args, bool * );
1466
1467             *pb = (p_sys->rtsp != NULL) &&
1468                     (p_sys->f_npt_length > 0) &&
1469                     ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1470                       !var_GetBool( p_demux, "rtsp-wmserver" ) );
1471             *pb2 = false;
1472             return VLC_SUCCESS;
1473
1474         case DEMUX_SET_RATE:
1475         {
1476             double f_scale, f_old_scale;
1477
1478             if( !p_sys->rtsp || (p_sys->f_npt_length <= 0) ||
1479                 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1480                 var_GetBool( p_demux, "rtsp-wmserver" ) )
1481                 return VLC_EGENERIC;
1482
1483             /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1484              * supports Scale:
1485              *
1486              * "[...] should try to approximate the viewing rate, but
1487              *  may restrict the range of scale values that it supports.
1488              *  The response MUST contain the actual scale value chosen
1489              *  by the server."
1490              *
1491              * Scale = 1 indicates normal play
1492              * Scale > 1 indicates fast forward
1493              * Scale < 1 && Scale > 0 indicates slow motion
1494              * Scale < 0 value indicates rewind
1495              */
1496
1497             pi_int = (int*)va_arg( args, int * );
1498             f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1499             f_old_scale = p_sys->ms->scale();
1500
1501             /* Passing -1 for the start and end time will mean liveMedia won't
1502              * create a Range: section for the RTSP message. The server should
1503              * pick up from the current position */
1504             p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, -1, -1, f_scale );
1505
1506             if( !wait_Live555_response( p_demux ) )
1507             {
1508                 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1509                         p_sys->env->getResultMsg() );
1510                 return VLC_EGENERIC;
1511             }
1512
1513             if( p_sys->ms->scale() == f_old_scale )
1514             {
1515                 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1516                           p_sys->ms->scale() );
1517                 return VLC_EGENERIC;
1518             }
1519
1520             /* ReSync the stream */
1521             p_sys->f_npt_start = 0;
1522             p_sys->i_pcr = 0;
1523             p_sys->f_npt = 0.0;
1524
1525             *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1526             msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1527             return VLC_SUCCESS;
1528         }
1529
1530         case DEMUX_SET_PAUSE_STATE:
1531         {
1532             bool b_pause = (bool)va_arg( args, int );
1533             if( p_sys->rtsp == NULL )
1534                 return VLC_EGENERIC;
1535
1536             if( b_pause == p_sys->b_paused )
1537                 return VLC_SUCCESS;
1538             if( b_pause )
1539                 p_sys->rtsp->sendPauseCommand( *p_sys->ms, default_live555_callback );
1540             else
1541                 p_sys->rtsp->sendPlayCommand( *p_sys->ms, default_live555_callback, p_sys->f_seek_request,
1542                                               -1.0f, p_sys->ms->scale() );
1543
1544             if( !wait_Live555_response( p_demux ) )
1545             {
1546                 msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1547                 return VLC_EGENERIC;
1548             }
1549             p_sys->f_seek_request = -1;
1550             p_sys->b_paused = b_pause;
1551
1552             /* When we Pause, we'll need the TimeoutPrevention thread to
1553              * handle sending the "Keep Alive" message to the server.
1554              * Unfortunately Live555 isn't thread safe and so can't
1555              * do this normally while the main Demux thread is handling
1556              * a live stream. We end up with the Timeout thread blocking
1557              * waiting for a response from the server. So when we PAUSE
1558              * we set a flag that the TimeoutPrevention function will check
1559              * and if it's set, it will trigger the GET_PARAMETER message */
1560             if( p_sys->b_paused && p_sys->p_timeout != NULL )
1561                 p_sys->p_timeout->b_handle_keep_alive = true;
1562             else if( !p_sys->b_paused && p_sys->p_timeout != NULL )
1563                 p_sys->p_timeout->b_handle_keep_alive = false;
1564
1565             if( !p_sys->b_paused )
1566             {
1567                 for( int i = 0; i < p_sys->i_track; i++ )
1568                 {
1569                     live_track_t *tk = p_sys->track[i];
1570                     tk->b_rtcp_sync = false;
1571                     tk->i_pts = VLC_TS_INVALID;
1572                     p_sys->i_pcr = 0;
1573                     es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1574                 }
1575             }
1576
1577             /* Reset data received counter */
1578             p_sys->i_no_data_ti = 0;
1579
1580             /* Retrieve the starttime if possible */
1581             p_sys->f_npt_start = p_sys->ms->playStartTime();
1582
1583             /* Retrieve the duration if possible */
1584             if( p_sys->ms->playEndTime() )
1585                 p_sys->f_npt_length = p_sys->ms->playEndTime();
1586
1587             msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->f_npt_start, p_sys->f_npt_length );
1588             return VLC_SUCCESS;
1589         }
1590         case DEMUX_GET_TITLE_INFO:
1591         case DEMUX_SET_TITLE:
1592         case DEMUX_SET_SEEKPOINT:
1593             return VLC_EGENERIC;
1594
1595         case DEMUX_GET_PTS_DELAY:
1596             pi64 = (int64_t*)va_arg( args, int64_t * );
1597             *pi64 = INT64_C(1000)
1598                   * var_InheritInteger( p_demux, "network-caching" );
1599             return VLC_SUCCESS;
1600
1601         default:
1602             return VLC_EGENERIC;
1603     }
1604 }
1605
1606 /*****************************************************************************
1607  * RollOverTcp: reopen the rtsp into TCP mode
1608  * XXX: ugly, a lot of code are duplicated from Open()
1609  * This should REALLY be fixed
1610  *****************************************************************************/
1611 static int RollOverTcp( demux_t *p_demux )
1612 {
1613     demux_sys_t *p_sys = p_demux->p_sys;
1614     int i, i_return;
1615
1616     var_SetBool( p_demux, "rtsp-tcp", true );
1617
1618     /* We close the old RTSP session */
1619     p_sys->rtsp->sendTeardownCommand( *p_sys->ms, NULL );
1620     Medium::close( p_sys->ms );
1621     RTSPClient::close( p_sys->rtsp );
1622
1623     for( i = 0; i < p_sys->i_track; i++ )
1624     {
1625         live_track_t *tk = p_sys->track[i];
1626
1627         if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
1628         if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1629         if( tk->p_asf_block ) block_Release( tk->p_asf_block );
1630         es_format_Clean( &tk->fmt );
1631         free( tk->p_buffer );
1632         free( tk );
1633     }
1634     TAB_CLEAN( p_sys->i_track, p_sys->track );
1635     if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
1636
1637     p_sys->ms = NULL;
1638     p_sys->rtsp = NULL;
1639     p_sys->b_no_data = true;
1640     p_sys->i_no_data_ti = 0;
1641     p_sys->p_out_asf = NULL;
1642
1643     /* Reopen rtsp client */
1644     if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1645     {
1646         msg_Err( p_demux, "Failed to connect with rtsp://%s",
1647                  p_sys->psz_path );
1648         goto error;
1649     }
1650
1651     if( p_sys->p_sdp == NULL )
1652     {
1653         msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1654         goto error;
1655     }
1656
1657     if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1658     {
1659         msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1660         goto error;
1661     }
1662
1663     if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1664         goto error;
1665
1666     return VLC_SUCCESS;
1667
1668 error:
1669     return VLC_EGENERIC;
1670 }
1671
1672
1673 /*****************************************************************************
1674  *
1675  *****************************************************************************/
1676 static block_t *StreamParseAsf( demux_t *p_demux, live_track_t *tk,
1677                                 bool b_marker,
1678                                 const uint8_t *p_data, unsigned i_size )
1679 {
1680     const unsigned i_packet_size = p_demux->p_sys->asfh.i_min_data_packet_size;
1681     block_t *p_list = NULL;
1682
1683     while( i_size >= 4 )
1684     {
1685         unsigned i_flags = p_data[0];
1686         unsigned i_length_offset = (p_data[1] << 16) |
1687                                    (p_data[2] <<  8) |
1688                                    (p_data[3]      );
1689         bool b_length = i_flags & 0x40;
1690         bool b_relative_ts = i_flags & 0x20;
1691         bool b_duration = i_flags & 0x10;
1692         bool b_location_id = i_flags & 0x08;
1693
1694         //msg_Dbg( p_demux, "ASF: marker=%d size=%d : %c=%d id=%d",
1695         //         b_marker, i_size, b_length ? 'L' : 'O', i_length_offset );
1696         unsigned i_header_size = 4;
1697         if( b_relative_ts )
1698             i_header_size += 4;
1699         if( b_duration )
1700             i_header_size += 4;
1701         if( b_location_id )
1702             i_header_size += 4;
1703
1704         if( i_header_size > i_size )
1705         {
1706             msg_Warn( p_demux, "Invalid header size" );
1707             break;
1708         }
1709
1710         /* XXX
1711          * When b_length is true, the streams I found do not seems to respect
1712          * the documentation.
1713          * From them, I have failed to find which choice between '__MIN()' or
1714          * 'i_length_offset - i_header_size' is the right one.
1715          */
1716         unsigned i_payload;
1717         if( b_length )
1718             i_payload = __MIN( i_length_offset, i_size - i_header_size);
1719         else
1720             i_payload = i_size - i_header_size;
1721
1722         if( !tk->p_asf_block )
1723         {
1724             tk->p_asf_block = block_New( p_demux, i_packet_size );
1725             if( !tk->p_asf_block )
1726                 break;
1727             tk->p_asf_block->i_buffer = 0;
1728         }
1729         unsigned i_offset  = b_length ? 0 : i_length_offset;
1730         if( i_offset == tk->p_asf_block->i_buffer && i_offset + i_payload <= i_packet_size )
1731         {
1732             memcpy( &tk->p_asf_block->p_buffer[i_offset], &p_data[i_header_size], i_payload );
1733             tk->p_asf_block->i_buffer += i_payload;
1734             if( b_marker )
1735             {
1736                 /* We have a complete packet */
1737                 tk->p_asf_block->i_buffer = i_packet_size;
1738                 block_ChainAppend( &p_list, tk->p_asf_block );
1739                 tk->p_asf_block = NULL;
1740             }
1741         }
1742         else
1743         {
1744             /* Reset on broken stream */
1745             msg_Err( p_demux, "Broken packet detected (%d vs %zu or %d + %d vs %d)",
1746                      i_offset, tk->p_asf_block->i_buffer, i_offset, i_payload, i_packet_size);
1747             tk->p_asf_block->i_buffer = 0;
1748         }
1749
1750         /* */
1751         p_data += i_header_size + i_payload;
1752         i_size -= i_header_size + i_payload;
1753     }
1754     return p_list;
1755 }
1756
1757 /*****************************************************************************
1758  *
1759  *****************************************************************************/
1760 static void StreamRead( void *p_private, unsigned int i_size,
1761                         unsigned int i_truncated_bytes, struct timeval pts,
1762                         unsigned int duration )
1763 {
1764     VLC_UNUSED( duration );
1765
1766     live_track_t   *tk = (live_track_t*)p_private;
1767     demux_t        *p_demux = tk->p_demux;
1768     demux_sys_t    *p_sys = p_demux->p_sys;
1769     block_t        *p_block;
1770
1771     //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1772
1773     int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1774         (int64_t)pts.tv_usec;
1775
1776     /* XXX Beurk beurk beurk Avoid having negative value XXX */
1777     i_pts &= INT64_C(0x00ffffffffffffff);
1778
1779     /* Retrieve NPT for this pts */
1780     tk->f_npt = tk->sub->getNormalPlayTime(pts);
1781
1782     if( tk->b_quicktime && tk->p_es == NULL )
1783     {
1784         QuickTimeGenericRTPSource *qtRTPSource =
1785             (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1786         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1787         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1788
1789         /* Get codec informations from the quicktime atoms :
1790          * http://developer.apple.com/quicktime/icefloe/dispatch026.html */
1791         if( tk->fmt.i_cat == VIDEO_ES ) {
1792             if( qtState.sdAtomSize < 16 + 32 )
1793             {
1794                 /* invalid */
1795                 p_sys->event_data = 0xff;
1796                 tk->waiting = 0;
1797                 return;
1798             }
1799             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1800             tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
1801             tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1802
1803             if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1804             {
1805                 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1806                 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1807                                   + qtRTPSource->qtState.sdAtomSize;
1808                 while (pos+8 < endpos) {
1809                     unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1810                     if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1811                     if( memcmp(pos+4, "avcC", 4) == 0 &&
1812                         atomLength > 8 &&
1813                         atomLength <= INT_MAX )
1814                     {
1815                         tk->fmt.i_extra = atomLength-8;
1816                         tk->fmt.p_extra = xmalloc( tk->fmt.i_extra );
1817                         memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1818                         break;
1819                     }
1820                     pos += atomLength;
1821                 }
1822             }
1823             else
1824             {
1825                 tk->fmt.i_extra        = qtState.sdAtomSize - 16;
1826                 tk->fmt.p_extra        = xmalloc( tk->fmt.i_extra );
1827                 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1828             }
1829         }
1830         else {
1831             if( qtState.sdAtomSize < 24 )
1832             {
1833                 /* invalid */
1834                 p_sys->event_data = 0xff;
1835                 tk->waiting = 0;
1836                 return;
1837             }
1838             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1839             tk->fmt.audio.i_bitspersample = (sdAtom[22] << 8) | sdAtom[23];
1840         }
1841         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1842     }
1843
1844 #if 0
1845     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1846              i_size,
1847              pts.tv_sec * 1000000LL + pts.tv_usec );
1848 #endif
1849
1850     /* grow buffer if it looks like buffer is too small, but don't eat
1851      * up all the memory on strange streams */
1852     if( i_truncated_bytes > 0 )
1853     {
1854         if( tk->i_buffer < 2000000 )
1855         {
1856             void *p_tmp;
1857             msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1858             msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1859             p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1860             if( p_tmp == NULL )
1861             {
1862                 msg_Warn( p_demux, "realloc failed" );
1863             }
1864             else
1865             {
1866                 tk->p_buffer = (uint8_t*)p_tmp;
1867                 tk->i_buffer *= 2;
1868             }
1869         }
1870
1871         if( tk->b_discard_trunc )
1872         {
1873             p_sys->event_data = 0xff;
1874             tk->waiting = 0;
1875             return;
1876         }
1877     }
1878
1879     assert( i_size <= tk->i_buffer );
1880
1881     if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1882         tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1883     {
1884         AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1885
1886         p_block = block_New( p_demux, i_size + 1 );
1887         p_block->p_buffer[0] = amrSource->lastFrameHeader();
1888         memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1889     }
1890     else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1891     {
1892         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1893         uint32_t header = h261Source->lastSpecialHeader();
1894         p_block = block_New( p_demux, i_size + 4 );
1895         memcpy( p_block->p_buffer, &header, 4 );
1896         memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1897
1898         if( tk->sub->rtpSource()->curPacketMarkerBit() )
1899             p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1900     }
1901     else if( tk->fmt.i_codec == VLC_CODEC_H264 )
1902     {
1903         if( (tk->p_buffer[0] & 0x1f) >= 24 )
1904             msg_Warn( p_demux, "unsupported NAL type for H264" );
1905
1906         /* Normal NAL type */
1907         p_block = block_New( p_demux, i_size + 4 );
1908         p_block->p_buffer[0] = 0x00;
1909         p_block->p_buffer[1] = 0x00;
1910         p_block->p_buffer[2] = 0x00;
1911         p_block->p_buffer[3] = 0x01;
1912         memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1913     }
1914     else if( tk->b_asf )
1915     {
1916         p_block = StreamParseAsf( p_demux, tk,
1917                                   tk->sub->rtpSource()->curPacketMarkerBit(),
1918                                   tk->p_buffer, i_size );
1919     }
1920     else
1921     {
1922         p_block = block_New( p_demux, i_size );
1923         memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1924     }
1925
1926     if( p_sys->i_pcr < i_pts )
1927     {
1928         p_sys->i_pcr = i_pts;
1929     }
1930
1931     /* Update our global npt value */
1932     if( tk->f_npt > 0 && tk->f_npt > p_sys->f_npt &&
1933         ( tk->f_npt < p_sys->f_npt_length || p_sys->f_npt_length <= 0 ) )
1934         p_sys->f_npt = tk->f_npt;
1935
1936     if( p_block )
1937     {
1938         if( !tk->b_muxed && !tk->b_asf )
1939         {
1940             if( i_pts != tk->i_pts )
1941                 p_block->i_pts = VLC_TS_0 + i_pts;
1942             /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
1943             p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? VLC_TS_INVALID : (VLC_TS_0 + i_pts);
1944         }
1945
1946         if( tk->b_muxed )
1947             stream_DemuxSend( tk->p_out_muxed, p_block );
1948         else if( tk->b_asf )
1949             stream_DemuxSend( p_sys->p_out_asf, p_block );
1950         else
1951             es_out_Send( p_demux->out, tk->p_es, p_block );
1952     }
1953
1954     /* warn that's ok */
1955     p_sys->event_data = 0xff;
1956
1957     /* we have read data */
1958     tk->waiting = 0;
1959     p_demux->p_sys->b_no_data = false;
1960     p_demux->p_sys->i_no_data_ti = 0;
1961
1962     if( i_pts > 0 && !tk->b_muxed )
1963     {
1964         tk->i_pts = i_pts;
1965     }
1966 }
1967
1968 /*****************************************************************************
1969  *
1970  *****************************************************************************/
1971 static void StreamClose( void *p_private )
1972 {
1973     live_track_t   *tk = (live_track_t*)p_private;
1974     demux_t        *p_demux = tk->p_demux;
1975     demux_sys_t    *p_sys = p_demux->p_sys;
1976     tk->b_selected = false;
1977     p_sys->event_rtsp = 0xff;
1978     p_sys->event_data = 0xff;
1979
1980     if( tk->p_es )
1981         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
1982
1983     int nb_tracks = 0;
1984     for( int i = 0; i < p_sys->i_track; i++ )
1985     {
1986         if( p_sys->track[i]->b_selected )
1987             nb_tracks++;
1988     }
1989     msg_Dbg( p_demux, "RTSP track Close, %d track remaining", nb_tracks );
1990     if( !nb_tracks )
1991         p_sys->b_error = true;
1992 }
1993
1994
1995 /*****************************************************************************
1996  *
1997  *****************************************************************************/
1998 static void TaskInterruptRTSP( void *p_private )
1999 {
2000     demux_t *p_demux = (demux_t*)p_private;
2001
2002     /* Avoid lock */
2003     p_demux->p_sys->event_rtsp = 0xff;
2004 }
2005
2006 static void TaskInterruptData( void *p_private )
2007 {
2008     demux_t *p_demux = (demux_t*)p_private;
2009
2010     p_demux->p_sys->i_no_data_ti++;
2011
2012     /* Avoid lock */
2013     p_demux->p_sys->event_data = 0xff;
2014 }
2015
2016 /*****************************************************************************
2017  *
2018  *****************************************************************************/
2019 VLC_NORETURN
2020 static void* TimeoutPrevention( void *p_data )
2021 {
2022     timeout_thread_t *p_timeout = (timeout_thread_t *)p_data;
2023
2024     for( ;; )
2025     {
2026         /* Voodoo (= no) thread safety here! *Ahem* */
2027         if( p_timeout->b_handle_keep_alive )
2028         {
2029             char *psz_bye = NULL;
2030             int canc = vlc_savecancel ();
2031
2032             p_timeout->p_sys->rtsp->sendGetParameterCommand( *p_timeout->p_sys->ms, NULL, psz_bye );
2033             vlc_restorecancel (canc);
2034         }
2035         p_timeout->p_sys->b_timeout_call = !p_timeout->b_handle_keep_alive;
2036
2037         msleep (((int64_t)p_timeout->p_sys->i_timeout - 2) * CLOCK_FREQ);
2038     }
2039     assert(0); /* dead code */
2040 }
2041
2042 /*****************************************************************************
2043  *
2044  *****************************************************************************/
2045 static int ParseASF( demux_t *p_demux )
2046 {
2047     demux_sys_t    *p_sys = p_demux->p_sys;
2048
2049     const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
2050     char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
2051     char *psz_end;
2052     block_t *p_header;
2053
2054     /* Parse the asf header */
2055     if( psz_asf == NULL )
2056         return VLC_EGENERIC;
2057
2058     psz_asf += strlen( psz_marker );
2059     psz_asf = strdup( psz_asf );    /* Duplicate it */
2060     psz_end = strchr( psz_asf, '\n' );
2061
2062     while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
2063         *psz_end-- = '\0';
2064
2065     if( psz_asf >= psz_end )
2066     {
2067         free( psz_asf );
2068         return VLC_EGENERIC;
2069     }
2070
2071     /* Always smaller */
2072     p_header = block_New( p_demux, psz_end - psz_asf );
2073     p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
2074                                                p_header->i_buffer, psz_asf );
2075     //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
2076     if( p_header->i_buffer <= 0 )
2077     {
2078         free( psz_asf );
2079         return VLC_EGENERIC;
2080     }
2081
2082     /* Parse it to get packet size */
2083     asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
2084
2085     /* Send it to demuxer */
2086     stream_DemuxSend( p_sys->p_out_asf, p_header );
2087
2088     free( psz_asf );
2089     return VLC_SUCCESS;
2090 }
2091
2092
2093 static unsigned char* parseH264ConfigStr( char const* configStr,
2094                                           unsigned int& configSize )
2095 {
2096     char *dup, *psz;
2097     size_t i_records = 1;
2098
2099     configSize = 0;
2100
2101     if( configStr == NULL || *configStr == '\0' )
2102         return NULL;
2103
2104     psz = dup = strdup( configStr );
2105
2106     /* Count the number of commas */
2107     for( psz = dup; *psz != '\0'; ++psz )
2108     {
2109         if( *psz == ',')
2110         {
2111             ++i_records;
2112             *psz = '\0';
2113         }
2114     }
2115
2116     size_t configMax = 5*strlen(dup);
2117     unsigned char *cfg = new unsigned char[configMax];
2118     psz = dup;
2119     for( size_t i = 0; i < i_records; ++i )
2120     {
2121         cfg[configSize++] = 0x00;
2122         cfg[configSize++] = 0x00;
2123         cfg[configSize++] = 0x00;
2124         cfg[configSize++] = 0x01;
2125
2126         configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
2127                                           configMax-configSize, psz );
2128         psz += strlen(psz)+1;
2129     }
2130
2131     free( dup );
2132     return cfg;
2133 }