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