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