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