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