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