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