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