]> git.sesse.net Git - vlc/blob - modules/demux/live555.cpp
live555: handle WMServer as a special case
[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( "sdp" )
111         add_shortcut( "live" )
112         add_shortcut( "livedotcom" )
113         set_capability( "access_demux", 0 )
114         set_callbacks( Open, Close )
115         add_bool( "rtsp-tcp", 0, NULL,
116                   N_("Use RTP over RTSP (TCP)"),
117                   N_("Use RTP over RTSP (TCP)"), true )
118             change_safe()
119         add_integer( "rtp-client-port", -1, NULL,
120                   N_("Client port"),
121                   N_("Port to use for the RTP source of the session"), true )
122         add_bool( "rtsp-mcast", false, NULL,
123                   N_("Force multicast RTP via RTSP"),
124                   N_("Force multicast RTP via RTSP"), true )
125             change_safe()
126         add_bool( "rtsp-http", 0, NULL,
127                   N_("Tunnel RTSP and RTP over HTTP"),
128                   N_("Tunnel RTSP and RTP over HTTP"), true )
129             change_safe()
130         add_integer( "rtsp-http-port", 80, NULL,
131                   N_("HTTP tunnel port"),
132                   N_("Port to use for tunneling the RTSP/RTP over HTTP."),
133                   true )
134         add_integer("rtsp-caching", 4 * DEFAULT_PTS_DELAY / 1000, NULL,
135                     CACHING_TEXT, CACHING_LONGTEXT, true )
136             change_safe()
137         add_bool(   "rtsp-kasenna", false, NULL, KASENNA_TEXT,
138                     KASENNA_LONGTEXT, true )
139         add_bool(   "rtsp-wmserver", false, NULL, WMSERVER_TEXT,
140                     WMSERVER_LONGTEXT, true)
141             change_safe()
142         add_string( "rtsp-user", NULL, NULL, USER_TEXT,
143                     USER_LONGTEXT, true )
144         add_password( "rtsp-pwd", NULL, NULL, PASS_TEXT,
145                       PASS_LONGTEXT, true )
146 vlc_module_end ()
147
148
149 /*****************************************************************************
150  * Local prototypes
151  *****************************************************************************/
152
153 typedef struct
154 {
155     demux_t         *p_demux;
156     MediaSubsession *sub;
157
158     es_format_t     fmt;
159     es_out_id_t     *p_es;
160
161     bool            b_muxed;
162     bool            b_quicktime;
163     bool            b_asf;
164     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 };
225
226 static int Demux  ( demux_t * );
227 static int Control( demux_t *, int, va_list );
228
229 static int Connect      ( demux_t * );
230 static int SessionsSetup( demux_t * );
231 static int Play         ( demux_t *);
232 static int ParseASF     ( demux_t * );
233 static int RollOverTcp  ( demux_t * );
234
235 static void StreamRead  ( void *, unsigned int, unsigned int,
236                           struct timeval, unsigned int );
237 static void StreamClose ( void * );
238 static void TaskInterrupt( void * );
239
240 static void* TimeoutPrevention( void * );
241
242 static unsigned char* parseH264ConfigStr( char const* configStr,
243                                           unsigned int& configSize );
244
245 /*****************************************************************************
246  * DemuxOpen:
247  *****************************************************************************/
248 static int  Open ( vlc_object_t *p_this )
249 {
250     demux_t     *p_demux = (demux_t*)p_this;
251     demux_sys_t *p_sys = NULL;
252
253     int i_return;
254     int i_error = VLC_EGENERIC;
255
256     if( p_demux->s )
257     {
258         /* See if it looks like a SDP
259            v, o, s fields are mandatory and in this order */
260         const uint8_t *p_peek;
261         if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
262
263         if( memcmp( p_peek, "v=0\r\n", 5 ) &&
264             memcmp( p_peek, "v=0\n", 4 ) &&
265             ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
266         {
267             return VLC_EGENERIC;
268         }
269     }
270     else
271     {
272         var_Create( p_demux, "rtsp-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
273     }
274
275     p_demux->pf_demux  = Demux;
276     p_demux->pf_control= Control;
277     p_demux->p_sys     = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
278     if( !p_sys ) return VLC_ENOMEM;
279
280     p_sys->p_sdp = NULL;
281     p_sys->scheduler = NULL;
282     p_sys->env = NULL;
283     p_sys->ms = NULL;
284     p_sys->rtsp = NULL;
285     p_sys->i_track = 0;
286     p_sys->track   = NULL;
287     p_sys->i_pcr = 0;
288     p_sys->i_npt = 0.;
289     p_sys->i_npt_start = 0.;
290     p_sys->i_npt_length = 0.;
291     p_sys->p_out_asf = NULL;
292     p_sys->b_no_data = true;
293     p_sys->i_no_data_ti = 0;
294     p_sys->p_timeout = NULL;
295     p_sys->i_timeout = 0;
296     p_sys->b_timeout_call = false;
297     p_sys->b_multicast = false;
298     p_sys->b_real = false;
299     p_sys->psz_path = strdup( p_demux->psz_path );
300     p_sys->b_force_mcast = var_CreateGetBool( p_demux, "rtsp-mcast" );
301     p_sys->b_get_param = false;
302
303     /* parse URL for rtsp://[user:[passwd]@]serverip:port/options */
304     vlc_UrlParse( &p_sys->url, p_sys->psz_path, 0 );
305
306     if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
307     {
308         msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
309         goto error;
310     }
311     if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
312     {
313         msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
314         goto error;
315     }
316
317     if( strcasecmp( p_demux->psz_access, "sdp" ) )
318     {
319         char *p = p_sys->psz_path;
320         while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
321     }
322
323     if( p_demux->s != NULL )
324     {
325         /* Gather the complete sdp file */
326         int     i_sdp       = 0;
327         int     i_sdp_max   = 1000;
328         uint8_t *p_sdp      = (uint8_t*) malloc( i_sdp_max );
329
330         if( !p_sdp )
331         {
332             i_error = VLC_ENOMEM;
333             goto error;
334         }
335
336         for( ;; )
337         {
338             int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
339                                       i_sdp_max - i_sdp - 1 );
340
341             if( !vlc_object_alive (p_demux) || p_demux->b_error )
342             {
343                 free( p_sdp );
344                 goto error;
345             }
346
347             if( i_read < 0 )
348             {
349                 msg_Err( p_demux, "failed to read SDP" );
350                 free( p_sdp );
351                 goto error;
352             }
353
354             i_sdp += i_read;
355
356             if( i_read < i_sdp_max - i_sdp - 1 )
357             {
358                 p_sdp[i_sdp] = '\0';
359                 break;
360             }
361
362             i_sdp_max += 1000;
363             p_sdp = (uint8_t*)realloc( p_sdp, i_sdp_max );
364         }
365         p_sys->p_sdp = (char*)p_sdp;
366     }
367     else if( ( p_demux->s == NULL ) &&
368              !strcasecmp( p_demux->psz_access, "sdp" ) )
369     {
370         /* sdp:// link from SAP */
371         p_sys->p_sdp = strdup( p_sys->psz_path );
372     }
373     else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
374     {
375         msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
376         goto error;
377     }
378
379     if( p_sys->p_sdp == NULL )
380     {
381         msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
382         i_error = VLC_ENOMEM;
383         goto error;
384     }
385
386     if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
387     {
388         msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
389         goto error;
390     }
391
392     if( p_sys->b_real ) goto error;
393
394     if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
395         goto error;
396
397     if( p_sys->p_out_asf && ParseASF( p_demux ) )
398     {
399         msg_Err( p_demux, "cannot find a usable asf header" );
400         /* TODO Clean tracks */
401         goto error;
402     }
403
404     if( p_sys->i_track <= 0 )
405         goto error;
406
407     return VLC_SUCCESS;
408
409 error:
410     Close( p_this );
411     return i_error;
412 }
413
414 /*****************************************************************************
415  * DemuxClose:
416  *****************************************************************************/
417 static void Close( vlc_object_t *p_this )
418 {
419     demux_t *p_demux = (demux_t*)p_this;
420     demux_sys_t *p_sys = p_demux->p_sys;
421     int i;
422
423     for( i = 0; i < p_sys->i_track; i++ )
424     {
425         live_track_t *tk = p_sys->track[i];
426
427         if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
428         es_format_Clean( &tk->fmt );
429         free( tk->p_buffer );
430         free( tk );
431     }
432
433     if( p_sys->i_track ) free( p_sys->track );
434     if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
435     if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->teardownMediaSession( *p_sys->ms );
436     if( p_sys->p_timeout )
437     {
438         vlc_cancel( p_sys->p_timeout->handle );
439         vlc_join( p_sys->p_timeout->handle, NULL );
440         free( p_sys->p_timeout );
441     }
442     if( p_sys->ms ) Medium::close( p_sys->ms );
443     if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
444     if( p_sys->env ) p_sys->env->reclaim();
445     delete p_sys->scheduler;
446     free( p_sys->p_sdp );
447     free( p_sys->psz_path );
448
449     vlc_UrlClean( &p_sys->url );
450
451     free( p_sys );
452 }
453
454 static inline const char *strempty( const char *s ) { return s?s:""; }
455 static inline Boolean toBool( bool b ) { return b?True:False; } // silly, no?
456
457 /*****************************************************************************
458  * Connect: connects to the RTSP server to setup the session DESCRIBE
459  *****************************************************************************/
460 static int Connect( demux_t *p_demux )
461 {
462     demux_sys_t *p_sys = p_demux->p_sys;
463     Authenticator authenticator;
464     bool b_firstpass  = true;
465     char *psz_user    = NULL;
466     char *psz_pwd     = NULL;
467     char *psz_url     = NULL;
468     char *psz_options = NULL;
469     char *p_sdp       = NULL;
470     int  i_http_port  = 0;
471     int  i_ret        = VLC_SUCCESS;
472
473     /* Create the url using the port number if available */
474     if( p_sys->url.i_port == 0 )
475     {
476         p_sys->url.i_port = 554;
477         if( asprintf( &psz_url, "rtsp://%s", p_sys->psz_path ) == -1 )
478             return VLC_ENOMEM;
479     }
480     else
481     {
482         if( asprintf( &psz_url, "rtsp://%s:%d%s", p_sys->url.psz_host,
483                       p_sys->url.i_port, p_sys->url.psz_path ) == -1 )
484             return VLC_ENOMEM;
485     }
486
487     /* Get the user name and password */
488     if( p_sys->url.psz_username || p_sys->url.psz_password )
489     {
490         psz_user = strdup( strempty( p_sys->url.psz_username ) );
491         psz_pwd  = strdup( strempty( p_sys->url.psz_password ) );
492     }
493     else
494     {
495         psz_user = var_CreateGetString( p_demux, "rtsp-user" );
496         psz_pwd  = var_CreateGetString( p_demux, "rtsp-pwd" );
497     }
498
499 createnew:
500     if( !vlc_object_alive (p_demux) || p_demux->b_error )
501     {
502         i_ret = VLC_EGENERIC;
503         goto bailout;
504     }
505
506     if( var_CreateGetBool( p_demux, "rtsp-http" ) )
507         i_http_port = var_CreateGetInteger( p_demux, "rtsp-http-port" );
508
509     if( ( p_sys->rtsp = RTSPClient::createNew( *p_sys->env,
510           var_CreateGetInteger( p_demux, "verbose" ) > 1,
511           "VLC media player", i_http_port ) ) == NULL )
512     {
513         msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
514                  p_sys->env->getResultMsg() );
515         i_ret = VLC_EGENERIC;
516         goto bailout;
517     }
518
519     /* Kasenna enables KeepAlive by analysing the User-Agent string.
520      * Appending _KA to the string should be enough to enable this feature,
521      * however, there is a bug where the _KA doesn't get parsed from the
522      * default User-Agent as created by VLC/Live555 code. This is probably due
523      * to spaces in the string or the string being too long. Here we override
524      * the default string with a more compact version.
525      */
526     if( var_CreateGetBool( p_demux, "rtsp-kasenna" ))
527     {
528         p_sys->rtsp->setUserAgentString( "VLC_MEDIA_PLAYER_KA" );
529     }
530
531 describe:
532     authenticator.setUsernameAndPassword( psz_user, psz_pwd );
533
534     /* */
535     { /* i_timeout hack scope */
536 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1223337600
537     const int i_timeout = var_CreateGetInteger(p_demux, "ipv4-timeout") / 1000;
538     psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
539                                                &authenticator, i_timeout );
540 #else
541     psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
542                                                &authenticator );
543 #endif
544     if( psz_options == NULL && authenticator.realm() != NULL )
545     {
546         // try again, with the realm set this time
547 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1223337600
548         psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
549                                                &authenticator, i_timeout );
550 #else
551         psz_options = p_sys->rtsp->sendOptionsCmd( psz_url, psz_user, psz_pwd,
552                                                &authenticator );
553 #endif
554     }
555     if( psz_options )
556         p_sys->b_get_param = (bool)strstr( psz_options, "GET_PARAMETER" );
557     delete [] psz_options;
558
559     if( var_CreateGetBool( p_demux, "rtsp-wmserver" ) )
560        p_sys->b_get_param = true;
561
562 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1223337600
563     p_sdp = p_sys->rtsp->describeWithPassword( psz_url, psz_user, psz_pwd,
564                           var_GetBool( p_demux, "rtsp-kasenna" ), i_timeout );
565 #else
566     p_sdp = p_sys->rtsp->describeWithPassword( psz_url, psz_user, psz_pwd,
567                                      var_GetBool( p_demux, "rtsp-kasenna" ) );
568 #endif
569     } /* i_timeout scope end */
570
571     if( p_sdp == NULL )
572     {
573         /* failure occurred */
574         int i_code = 0;
575         const char *psz_error = p_sys->env->getResultMsg();
576
577         if( var_GetBool( p_demux, "rtsp-http" ) )
578             sscanf( psz_error, "%*s %*s HTTP GET %*s HTTP/%*u.%*u %3u %*s",
579                     &i_code );
580         else
581         {
582             const char *psz_tmp = strstr( psz_error, "RTSP" );
583             if( psz_tmp )
584                 sscanf( psz_tmp, "RTSP/%*s%3u", &i_code );
585             else
586                 i_code = 0;
587         }
588         msg_Dbg( p_demux, "DESCRIBE failed with %d: %s", i_code, psz_error );
589
590         if( b_firstpass )
591         {   /* describeURL always returns an "RTSP/1.0 401 Unauthorized" the
592              * first time. This is a workaround to avoid asking for a
593              * user/passwd the first time the code passess here. */
594             i_code = 0;
595             b_firstpass = false;
596         }
597
598         if( i_code == 401 )
599         {
600             msg_Dbg( p_demux, "authentication failed" );
601
602             free( psz_user );
603             free( psz_pwd );
604             dialog_Login( p_demux, &psz_user, &psz_pwd,
605                           _("RTSP authentication"), "%s",
606                         _("Please enter a valid login name and a password.") );
607             if( psz_user != NULL && psz_pwd != NULL )
608             {
609                 msg_Dbg( p_demux, "retrying with user=%s", psz_user );
610                 goto describe;
611             }
612         }
613         else if( (i_code != 0) && !var_GetBool( p_demux, "rtsp-http" ) )
614         {
615             /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
616             msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
617             var_SetBool( p_demux, "rtsp-http", true );
618             if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
619             p_sys->rtsp = NULL;
620             goto createnew;
621         }
622         else
623         {
624             msg_Dbg( p_demux, "connection timeout" );
625             if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
626             p_sys->rtsp = NULL;
627         }
628         i_ret = VLC_EGENERIC;
629     }
630
631     free( p_sys->p_sdp );
632     p_sys->p_sdp = NULL;
633     if( p_sdp ) p_sys->p_sdp = strdup( (char*)p_sdp );
634     delete[] p_sdp;
635
636 bailout:
637     /* malloc-ated copy */
638     free( psz_url );
639     free( psz_user );
640     free( psz_pwd );
641
642     return i_ret;
643 }
644
645 /*****************************************************************************
646  * SessionsSetup: prepares the subsessions and does the SETUP
647  *****************************************************************************/
648 static int SessionsSetup( demux_t *p_demux )
649 {
650     demux_sys_t             *p_sys  = p_demux->p_sys;
651     MediaSubsessionIterator *iter   = NULL;
652     MediaSubsession         *sub    = NULL;
653
654     bool           b_rtsp_tcp = false;
655     int            i_client_port;
656     int            i_return = VLC_SUCCESS;
657     unsigned int   i_buffer = 0;
658     unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
659
660     b_rtsp_tcp    = var_CreateGetBool( p_demux, "rtsp-tcp" ) ||
661                     var_GetBool( p_demux, "rtsp-http" );
662     i_client_port = var_CreateGetInteger( p_demux, "rtp-client-port" );
663
664     /* Create the session from the SDP */
665     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
666     {
667         msg_Err( p_demux, "Could not create the RTSP Session: %s",
668             p_sys->env->getResultMsg() );
669         return VLC_EGENERIC;
670     }
671
672     /* Initialise each media subsession */
673     iter = new MediaSubsessionIterator( *p_sys->ms );
674     while( ( sub = iter->next() ) != NULL )
675     {
676         Boolean bInit;
677         live_track_t *tk;
678
679         if( !vlc_object_alive (p_demux) || p_demux->b_error )
680         {
681             delete iter;
682             return VLC_EGENERIC;
683         }
684
685         /* Value taken from mplayer */
686         if( !strcmp( sub->mediumName(), "audio" ) )
687             i_buffer = 100000;
688         else if( !strcmp( sub->mediumName(), "video" ) )
689             i_buffer = 2000000;
690         else continue;
691
692         if( i_client_port != -1 )
693         {
694             sub->setClientPortNum( i_client_port );
695             i_client_port += 2;
696         }
697
698         if( strcasestr( sub->codecName(), "REAL" ) )
699         {
700             msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
701             p_sys->b_real = true; /* This is a problem, we'll handle it later */
702             continue;
703         }
704
705         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
706             bInit = sub->initiate( 4 ); /* Constant ? */
707         else
708             bInit = sub->initiate();
709
710         if( !bInit )
711         {
712             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
713                       sub->mediumName(), sub->codecName(),
714                       p_sys->env->getResultMsg() );
715         }
716         else
717         {
718             if( sub->rtpSource() != NULL )
719             {
720                 int fd = sub->rtpSource()->RTPgs()->socketNum();
721
722                 /* Increase the buffer size */
723                 if( i_buffer > 0 )
724                     increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
725
726                 /* Increase the RTP reorder timebuffer just a bit */
727                 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
728             }
729             msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
730                      sub->codecName() );
731
732             /* Issue the SETUP */
733             if( p_sys->rtsp )
734             {
735                 if( !p_sys->rtsp->setupMediaSubsession( *sub, False,
736                                                         toBool( b_rtsp_tcp ),
737                              toBool( p_sys->b_force_mcast && !b_rtsp_tcp ) ) )
738                 {
739                     /* if we get an unsupported transport error, toggle TCP
740                      * use and try again */
741                     if( !strstr(p_sys->env->getResultMsg(),
742                                 "461 Unsupported Transport")
743                         || !p_sys->rtsp->setupMediaSubsession( *sub, False,
744                                                toBool( b_rtsp_tcp ), False ) )
745                     {
746                         msg_Err( p_demux, "SETUP of'%s/%s' failed %s",
747                                  sub->mediumName(), sub->codecName(),
748                                  p_sys->env->getResultMsg() );
749                         continue;
750                     }
751                 }
752             }
753
754             /* Check if we will receive data from this subsession for
755              * this track */
756             if( sub->readSource() == NULL ) continue;
757             if( !p_sys->b_multicast )
758             {
759                 /* We need different rollover behaviour for multicast */
760                 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
761             }
762
763             tk = (live_track_t*)malloc( sizeof( live_track_t ) );
764             if( !tk )
765             {
766                 delete iter;
767                 return VLC_ENOMEM;
768             }
769             tk->p_demux     = p_demux;
770             tk->sub         = sub;
771             tk->p_es        = NULL;
772             tk->b_quicktime = false;
773             tk->b_asf       = false;
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       = 0;
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 = malloc( 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 = malloc( 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 = malloc( 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 = malloc( 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
1000             if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
1001             {
1002                 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1003             }
1004
1005             if( sub->rtcpInstance() != NULL )
1006             {
1007                 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1008             }
1009
1010             if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
1011             {
1012                 /* Append */
1013                 p_sys->track = (live_track_t**)realloc( p_sys->track, sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
1014                 p_sys->track[p_sys->i_track++] = tk;
1015             }
1016             else
1017             {
1018                 /* BUG ??? */
1019                 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
1020                 es_format_Clean( &tk->fmt );
1021                 free( tk );
1022             }
1023         }
1024     }
1025     delete iter;
1026     if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
1027
1028     /* Retrieve the starttime if possible */
1029     p_sys->i_npt_start = p_sys->ms->playStartTime();
1030
1031     /* Retrieve the duration if possible */
1032     p_sys->i_npt_length = p_sys->ms->playEndTime();
1033
1034     /* */
1035     msg_Dbg( p_demux, "setup start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1036
1037     /* */
1038     p_sys->b_no_data = true;
1039     p_sys->i_no_data_ti = 0;
1040
1041     return i_return;
1042 }
1043
1044 /*****************************************************************************
1045  * Play: starts the actual playback of the stream
1046  *****************************************************************************/
1047 static int Play( demux_t *p_demux )
1048 {
1049     demux_sys_t *p_sys = p_demux->p_sys;
1050
1051     if( p_sys->rtsp )
1052     {
1053         /* The PLAY */
1054         if( !p_sys->rtsp->playMediaSession( *p_sys->ms, p_sys->i_npt_start, -1, 1 ) )
1055         {
1056             msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
1057             return VLC_EGENERIC;
1058         }
1059
1060         /* Retrieve the timeout value and set up a timeout prevention thread */
1061         p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
1062         if( p_sys->i_timeout <= 0 )
1063             p_sys->i_timeout = 60; /* default value from RFC2326 */
1064
1065         /* start timeout-thread only if GET_PARAMETER is supported by the server */
1066         if( !p_sys->p_timeout && p_sys->b_get_param )
1067         {
1068             msg_Dbg( p_demux, "We have a timeout of %d seconds",  p_sys->i_timeout );
1069             p_sys->p_timeout = (timeout_thread_t *)malloc( sizeof(timeout_thread_t) );
1070             if( p_sys->p_timeout )
1071             {
1072                 memset( p_sys->p_timeout, 0, sizeof(timeout_thread_t) );
1073                 p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
1074                 if( vlc_clone( &p_sys->p_timeout->handle,  TimeoutPrevention,
1075                                p_sys->p_timeout, VLC_THREAD_PRIORITY_LOW ) )
1076                 {
1077                     msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1078                     free( p_sys->p_timeout );
1079                     p_sys->p_timeout = NULL;
1080                 }
1081                 else
1082                     msg_Dbg( p_demux, "spawned timeout thread" );
1083             }
1084             else
1085                 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
1086         }
1087     }
1088     p_sys->i_pcr = 0;
1089
1090     /* Retrieve the starttime if possible */
1091     p_sys->i_npt_start = p_sys->ms->playStartTime();
1092     if( p_sys->ms->playEndTime() > 0 )
1093         p_sys->i_npt_length = p_sys->ms->playEndTime();
1094
1095     msg_Dbg( p_demux, "play start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1096     return VLC_SUCCESS;
1097 }
1098
1099
1100 /*****************************************************************************
1101  * Demux:
1102  *****************************************************************************/
1103 static int Demux( demux_t *p_demux )
1104 {
1105     demux_sys_t    *p_sys = p_demux->p_sys;
1106     TaskToken      task;
1107
1108     bool            b_send_pcr = true;
1109     int64_t         i_pcr = 0;
1110     int             i;
1111
1112     /* Check if we need to send the server a Keep-A-Live signal */
1113     if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
1114     {
1115         char *psz_bye = NULL;
1116         p_sys->rtsp->getMediaSessionParameter( *p_sys->ms, NULL, psz_bye );
1117         p_sys->b_timeout_call = false;
1118     }
1119
1120     for( i = 0; i < p_sys->i_track; i++ )
1121     {
1122         live_track_t *tk = p_sys->track[i];
1123
1124         if( tk->b_asf || tk->b_muxed )
1125             b_send_pcr = false;
1126 #if 0
1127         if( i_pcr == 0 )
1128         {
1129             i_pcr = tk->i_pts;
1130         }
1131         else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
1132         {
1133             i_pcr = tk->i_pts ;
1134         }
1135 #endif
1136     }
1137     if( p_sys->i_pcr > 0 )
1138     {
1139         if( b_send_pcr )
1140             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
1141     }
1142
1143     /* First warn we want to read data */
1144     p_sys->event = 0;
1145     for( i = 0; i < p_sys->i_track; i++ )
1146     {
1147         live_track_t *tk = p_sys->track[i];
1148
1149         if( tk->waiting == 0 )
1150         {
1151             tk->waiting = 1;
1152             tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1153                                           StreamRead, tk, StreamClose, tk );
1154         }
1155     }
1156     /* Create a task that will be called if we wait more than 300ms */
1157     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
1158
1159     /* Do the read */
1160     p_sys->scheduler->doEventLoop( &p_sys->event );
1161
1162     /* remove the task */
1163     p_sys->scheduler->unscheduleDelayedTask( task );
1164
1165     /* Check for gap in pts value */
1166     for( i = 0; i < p_sys->i_track; i++ )
1167     {
1168         live_track_t *tk = p_sys->track[i];
1169
1170         if( !tk->b_muxed && !tk->b_rtcp_sync &&
1171             tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1172         {
1173             msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1174
1175             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1176             tk->b_rtcp_sync = true;
1177             /* reset PCR */
1178             tk->i_pts = 0;
1179             tk->i_npt = 0.;
1180             p_sys->i_pcr = 0;
1181             p_sys->i_npt = 0.;
1182             i_pcr = 0;
1183         }
1184     }
1185
1186     if( p_sys->b_multicast && p_sys->b_no_data &&
1187         ( p_sys->i_no_data_ti > 120 ) )
1188     {
1189         /* FIXME Make this configurable
1190         msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1191         return 0;
1192         */
1193     }
1194     else if( !p_sys->b_multicast && p_sys->b_no_data &&
1195              ( p_sys->i_no_data_ti > 34 ) )
1196     {
1197         bool b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" ) ||
1198                                 var_GetBool( p_demux, "rtsp-http" );
1199
1200         if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1201         {
1202             msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1203             if( RollOverTcp( p_demux ) )
1204             {
1205                 msg_Err( p_demux, "TCP rollover failed, aborting" );
1206                 return 0;
1207             }
1208             return 1;
1209         }
1210         msg_Err( p_demux, "no data received in 10s, aborting" );
1211         return 0;
1212     }
1213     else if( !p_sys->b_multicast && p_sys->i_no_data_ti > 34 )
1214     {
1215         /* EOF ? */
1216         msg_Warn( p_demux, "no data received in 10s, eof ?" );
1217         return 0;
1218     }
1219     return p_demux->b_error ? 0 : 1;
1220 }
1221
1222 /*****************************************************************************
1223  * Control:
1224  *****************************************************************************/
1225 static int Control( demux_t *p_demux, int i_query, va_list args )
1226 {
1227     demux_sys_t *p_sys = p_demux->p_sys;
1228     int64_t *pi64, i64;
1229     double  *pf, f;
1230     bool *pb, *pb2, b_bool;
1231     int *pi_int;
1232
1233     switch( i_query )
1234     {
1235         case DEMUX_GET_TIME:
1236             pi64 = (int64_t*)va_arg( args, int64_t * );
1237             if( p_sys->i_npt > 0 )
1238             {
1239                 *pi64 = (int64_t)(p_sys->i_npt * 1000000.);
1240                 return VLC_SUCCESS;
1241             }
1242             return VLC_EGENERIC;
1243
1244         case DEMUX_GET_LENGTH:
1245             pi64 = (int64_t*)va_arg( args, int64_t * );
1246             if( p_sys->i_npt_length > 0 )
1247             {
1248                 *pi64 = (int64_t)((double)p_sys->i_npt_length * 1000000.0);
1249                 return VLC_SUCCESS;
1250             }
1251             return VLC_EGENERIC;
1252
1253         case DEMUX_GET_POSITION:
1254             pf = (double*)va_arg( args, double* );
1255             if( (p_sys->i_npt_length > 0) && (p_sys->i_npt > 0) )
1256             {
1257                 *pf = ( (double)p_sys->i_npt / (double)p_sys->i_npt_length );
1258                 return VLC_SUCCESS;
1259             }
1260             return VLC_EGENERIC;
1261
1262         case DEMUX_SET_POSITION:
1263         case DEMUX_SET_TIME:
1264             if( p_sys->rtsp && (p_sys->i_npt_length > 0) )
1265             {
1266                 int i;
1267                 float time;
1268
1269                 if( (i_query == DEMUX_SET_TIME) && (p_sys->i_npt > 0) )
1270                 {
1271                     i64 = (int64_t)va_arg( args, int64_t );
1272                     time = (float)((double)i64 / (double)1000000.0); /* in second */
1273                 }
1274                 else if( i_query == DEMUX_SET_TIME )
1275                     return VLC_EGENERIC;
1276                 else
1277                 {
1278                     f = (double)va_arg( args, double );
1279                     time = f * (double)p_sys->i_npt_length;   /* in second */
1280                 }
1281
1282                 if( !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) ||
1283                     !p_sys->rtsp->playMediaSession( *p_sys->ms, time, -1, 1 ) )
1284                 {
1285                     msg_Err( p_demux, "PLAY failed %s",
1286                         p_sys->env->getResultMsg() );
1287                     return VLC_EGENERIC;
1288                 }
1289                 p_sys->i_pcr = 0;
1290
1291                 /* Retrieve RTP-Info values */
1292                 for( i = 0; i < p_sys->i_track; i++ )
1293                 {
1294                     p_sys->track[i]->b_rtcp_sync = false;
1295                     p_sys->track[i]->i_pts = 0;
1296                 }
1297
1298                 /* Retrieve the starttime if possible */
1299                 p_sys->i_npt = p_sys->i_npt_start = p_sys->ms->playStartTime();
1300
1301                 /* Retrieve the duration if possible */
1302                 if( p_sys->ms->playEndTime() > 0 )
1303                     p_sys->i_npt_length = p_sys->ms->playEndTime();
1304
1305                 msg_Dbg( p_demux, "seek start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1306                 return VLC_SUCCESS;
1307             }
1308             return VLC_EGENERIC;
1309
1310         /* Special for access_demux */
1311         case DEMUX_CAN_PAUSE:
1312         case DEMUX_CAN_SEEK:
1313             pb = (bool*)va_arg( args, bool * );
1314             if( p_sys->rtsp && p_sys->i_npt_length > 0 )
1315                 /* Not always true, but will be handled in SET_PAUSE_STATE */
1316                 *pb = true;
1317             else
1318                 *pb = false;
1319             return VLC_SUCCESS;
1320
1321         case DEMUX_CAN_CONTROL_PACE:
1322             pb = (bool*)va_arg( args, bool * );
1323
1324 #if 1       /* Disable for now until we have a clock synchro algo
1325              * which works with something else than MPEG over UDP */
1326             *pb = false;
1327 #else
1328             *pb = true;
1329 #endif
1330             return VLC_SUCCESS;
1331
1332         case DEMUX_CAN_CONTROL_RATE:
1333             pb = (bool*)va_arg( args, bool * );
1334             pb2 = (bool*)va_arg( args, bool * );
1335
1336             *pb = (p_sys->rtsp != NULL) &&
1337                     (p_sys->i_npt_length > 0) &&
1338                     ( !var_GetBool( p_demux, "rtsp-kasenna" ) ||
1339                       !var_GetBool( p_demux, "rtsp-wmserver" ) );
1340             *pb2 = false;
1341             return VLC_SUCCESS;
1342
1343         case DEMUX_SET_RATE:
1344         {
1345             double f_scale, f_old_scale;
1346
1347             if( !p_sys->rtsp || (p_sys->i_npt_length <= 0) ||
1348                 var_GetBool( p_demux, "rtsp-kasenna" ) ||
1349                 var_GetBool( p_demux, "rtsp-wmserver" ) )
1350                 return VLC_EGENERIC;
1351
1352             /* According to RFC 2326 p56 chapter 12.35 a RTSP server that
1353              * supports Scale:
1354              *
1355              * "[...] should try to approximate the viewing rate, but
1356              *  may restrict the range of scale values that it supports.
1357              *  The response MUST contain the actual scale value chosen
1358              *  by the server."
1359              *
1360              * Scale = 1 indicates normal play
1361              * Scale > 1 indicates fast forward
1362              * Scale < 1 && Scale > 0 indicates slow motion
1363              * Scale < 0 value indicates rewind
1364              */
1365
1366             pi_int = (int*)va_arg( args, int * );
1367             f_scale = (double)INPUT_RATE_DEFAULT / (*pi_int);
1368             f_old_scale = p_sys->ms->scale();
1369
1370             /* Passing -1 for the start and end time will mean liveMedia won't
1371              * create a Range: section for the RTSP message. The server should
1372              * pick up from the current position */
1373             if( !p_sys->rtsp->playMediaSession( *p_sys->ms, -1, -1, f_scale ) )
1374             {
1375                 msg_Err( p_demux, "PLAY with Scale %0.2f failed %s", f_scale,
1376                         p_sys->env->getResultMsg() );
1377                 return VLC_EGENERIC;
1378             }
1379
1380             if( p_sys->ms->scale() == f_old_scale )
1381             {
1382                 msg_Err( p_demux, "no scale change using old Scale %0.2f",
1383                           p_sys->ms->scale() );
1384                 return VLC_EGENERIC;
1385             }
1386
1387             /* ReSync the stream */
1388             p_sys->i_npt_start = 0;
1389             p_sys->i_pcr = 0;
1390             p_sys->i_npt = 0.0;
1391
1392             *pi_int = (int)( INPUT_RATE_DEFAULT / p_sys->ms->scale() );
1393             msg_Dbg( p_demux, "PLAY with new Scale %0.2f (%d)", p_sys->ms->scale(), (*pi_int) );
1394             return VLC_SUCCESS;
1395         }
1396
1397         case DEMUX_SET_PAUSE_STATE:
1398         {
1399             int i;
1400
1401             b_bool = (bool)va_arg( args, int );
1402             if( p_sys->rtsp == NULL )
1403                 return VLC_EGENERIC;
1404
1405             /* FIXME */
1406             if( ( b_bool && !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) ) ||
1407                     ( !b_bool && !p_sys->rtsp->playMediaSession( *p_sys->ms,
1408                        -1 ) ) )
1409             {
1410                     msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1411                     return VLC_EGENERIC;
1412             }
1413
1414             /* When we Pause, we'll need the TimeoutPrevention thread to
1415              * handle sending the "Keep Alive" message to the server.
1416              * Unfortunately Live555 isn't thread safe and so can't
1417              * do this normally while the main Demux thread is handling
1418              * a live stream. We end up with the Timeout thread blocking
1419              * waiting for a response from the server. So when we PAUSE
1420              * we set a flag that the TimeoutPrevention function will check
1421              * and if it's set, it will trigger the GET_PARAMETER message */
1422             if( b_bool && p_sys->p_timeout != NULL )
1423                 p_sys->p_timeout->b_handle_keep_alive = true;
1424             else if( !b_bool && p_sys->p_timeout != NULL )
1425                 p_sys->p_timeout->b_handle_keep_alive = false;
1426
1427             for( i = 0; !b_bool && i < p_sys->i_track; i++ )
1428             {
1429                 live_track_t *tk = p_sys->track[i];
1430                 tk->b_rtcp_sync = false;
1431                 tk->i_pts = 0;
1432                 p_sys->i_pcr = 0;
1433                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1434             }
1435
1436             /* Retrieve the starttime if possible */
1437             p_sys->i_npt_start = p_sys->ms->playStartTime();
1438
1439             /* Retrieve the duration if possible */
1440             if( p_sys->ms->playEndTime() )
1441                 p_sys->i_npt_length = p_sys->ms->playEndTime();
1442
1443             msg_Dbg( p_demux, "pause start: %f stop:%f", p_sys->i_npt_start, p_sys->i_npt_length );
1444             return VLC_SUCCESS;
1445         }
1446         case DEMUX_GET_TITLE_INFO:
1447         case DEMUX_SET_TITLE:
1448         case DEMUX_SET_SEEKPOINT:
1449             return VLC_EGENERIC;
1450
1451         case DEMUX_GET_PTS_DELAY:
1452             pi64 = (int64_t*)va_arg( args, int64_t * );
1453             *pi64 = (int64_t)var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1454             return VLC_SUCCESS;
1455
1456         default:
1457             return VLC_EGENERIC;
1458     }
1459 }
1460
1461 /*****************************************************************************
1462  * RollOverTcp: reopen the rtsp into TCP mode
1463  * XXX: ugly, a lot of code are duplicated from Open()
1464  * This should REALLY be fixed
1465  *****************************************************************************/
1466 static int RollOverTcp( demux_t *p_demux )
1467 {
1468     demux_sys_t *p_sys = p_demux->p_sys;
1469     int i, i_return;
1470
1471     var_SetBool( p_demux, "rtsp-tcp", true );
1472
1473     /* We close the old RTSP session */
1474     for( i = 0; i < p_sys->i_track; i++ )
1475     {
1476         live_track_t *tk = p_sys->track[i];
1477
1478         if( tk->b_muxed ) stream_Delete( tk->p_out_muxed );
1479         if( tk->p_es ) es_out_Del( p_demux->out, tk->p_es );
1480         es_format_Clean( &tk->fmt );
1481         free( tk->p_buffer );
1482         free( tk );
1483     }
1484     if( p_sys->i_track ) free( p_sys->track );
1485     if( p_sys->p_out_asf ) stream_Delete( p_sys->p_out_asf );
1486
1487     p_sys->rtsp->teardownMediaSession( *p_sys->ms );
1488     Medium::close( p_sys->ms );
1489     RTSPClient::close( p_sys->rtsp );
1490
1491     p_sys->ms = NULL;
1492     p_sys->rtsp = NULL;
1493     p_sys->track = NULL;
1494     p_sys->i_track = 0;
1495     p_sys->b_no_data = true;
1496     p_sys->i_no_data_ti = 0;
1497
1498     /* Reopen rtsp client */
1499     if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1500     {
1501         msg_Err( p_demux, "Failed to connect with rtsp://%s",
1502                  p_sys->psz_path );
1503         goto error;
1504     }
1505
1506     if( p_sys->p_sdp == NULL )
1507     {
1508         msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1509         goto error;
1510     }
1511
1512     if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1513     {
1514         msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1515         goto error;
1516     }
1517
1518     if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1519         goto error;
1520
1521     return VLC_SUCCESS;
1522
1523 error:
1524     return VLC_EGENERIC;
1525 }
1526
1527
1528 /*****************************************************************************
1529  *
1530  *****************************************************************************/
1531 static void StreamRead( void *p_private, unsigned int i_size,
1532                         unsigned int i_truncated_bytes, struct timeval pts,
1533                         unsigned int duration )
1534 {
1535     live_track_t   *tk = (live_track_t*)p_private;
1536     demux_t        *p_demux = tk->p_demux;
1537     demux_sys_t    *p_sys = p_demux->p_sys;
1538     block_t        *p_block;
1539
1540     //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1541
1542     int64_t i_pts = (int64_t)pts.tv_sec * INT64_C(1000000) +
1543         (int64_t)pts.tv_usec;
1544
1545     /* XXX Beurk beurk beurk Avoid having negative value XXX */
1546     i_pts &= INT64_C(0x00ffffffffffffff);
1547
1548     /* Retrieve NPT for this pts */
1549     tk->i_npt = tk->sub->getNormalPlayTime(pts);
1550
1551     if( tk->b_quicktime && tk->p_es == NULL )
1552     {
1553         QuickTimeGenericRTPSource *qtRTPSource =
1554             (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1555         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1556         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1557
1558         if( tk->fmt.i_cat == VIDEO_ES ) {
1559             if( qtState.sdAtomSize < 16 + 32 )
1560             {
1561                 /* invalid */
1562                 p_sys->event = 0xff;
1563                 tk->waiting = 0;
1564                 return;
1565             }
1566             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1567             tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
1568             tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1569
1570             if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1571             {
1572                 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1573                 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1574                                   + qtRTPSource->qtState.sdAtomSize;
1575                 while (pos+8 < endpos) {
1576                     unsigned int atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1577                     if( atomLength == 0 || atomLength > (unsigned int)(endpos-pos)) break;
1578                     if( memcmp(pos+4, "avcC", 4) == 0 &&
1579                         atomLength > 8 &&
1580                         atomLength <= INT_MAX )
1581                     {
1582                         tk->fmt.i_extra = atomLength-8;
1583                         tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1584                         memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1585                         break;
1586                     }
1587                     pos += atomLength;
1588                 }
1589             }
1590             else
1591             {
1592                 tk->fmt.i_extra        = qtState.sdAtomSize - 16;
1593                 tk->fmt.p_extra        = malloc( tk->fmt.i_extra );
1594                 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1595             }
1596         }
1597         else {
1598             if( qtState.sdAtomSize < 4 )
1599             {
1600                 /* invalid */
1601                 p_sys->event = 0xff;
1602                 tk->waiting = 0;
1603                 return;
1604             }
1605             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1606         }
1607         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1608     }
1609
1610 #if 0
1611     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1612              i_size,
1613              pts.tv_sec * 1000000LL + pts.tv_usec );
1614 #endif
1615
1616     /* grow buffer if it looks like buffer is too small, but don't eat
1617      * up all the memory on strange streams */
1618     if( i_truncated_bytes > 0 )
1619     {
1620         if( tk->i_buffer < 2000000 )
1621         {
1622             void *p_tmp;
1623             msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1624             msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1625             p_tmp = realloc( tk->p_buffer, tk->i_buffer * 2 );
1626             if( p_tmp == NULL )
1627             {
1628                 msg_Warn( p_demux, "realloc failed" );
1629             }
1630             else
1631             {
1632                 tk->p_buffer = (uint8_t*)p_tmp;
1633                 tk->i_buffer *= 2;
1634             }
1635         }
1636
1637         if( tk->b_discard_trunc )
1638         {
1639             p_sys->event = 0xff;
1640             tk->waiting = 0;
1641             return;
1642         }
1643     }
1644
1645     assert( i_size <= tk->i_buffer );
1646
1647     if( tk->fmt.i_codec == VLC_CODEC_AMR_NB ||
1648         tk->fmt.i_codec == VLC_CODEC_AMR_WB )
1649     {
1650         AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1651
1652         p_block = block_New( p_demux, i_size + 1 );
1653         p_block->p_buffer[0] = amrSource->lastFrameHeader();
1654         memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1655     }
1656     else if( tk->fmt.i_codec == VLC_CODEC_H261 )
1657     {
1658         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1659         uint32_t header = h261Source->lastSpecialHeader();
1660         p_block = block_New( p_demux, i_size + 4 );
1661         memcpy( p_block->p_buffer, &header, 4 );
1662         memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1663
1664         if( tk->sub->rtpSource()->curPacketMarkerBit() )
1665             p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1666     }
1667     else if( tk->fmt.i_codec == VLC_CODEC_H264 )
1668     {
1669         if( (tk->p_buffer[0] & 0x1f) >= 24 )
1670             msg_Warn( p_demux, "unsupported NAL type for H264" );
1671
1672         /* Normal NAL type */
1673         p_block = block_New( p_demux, i_size + 4 );
1674         p_block->p_buffer[0] = 0x00;
1675         p_block->p_buffer[1] = 0x00;
1676         p_block->p_buffer[2] = 0x00;
1677         p_block->p_buffer[3] = 0x01;
1678         memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1679     }
1680     else if( tk->b_asf )
1681     {
1682         int i_copy = __MIN( p_sys->asfh.i_min_data_packet_size, (int)i_size );
1683         p_block = block_New( p_demux, p_sys->asfh.i_min_data_packet_size );
1684
1685         memcpy( p_block->p_buffer, tk->p_buffer, i_copy );
1686     }
1687     else
1688     {
1689         p_block = block_New( p_demux, i_size );
1690         memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1691     }
1692
1693     if( p_sys->i_pcr < i_pts )
1694     {
1695         p_sys->i_pcr = i_pts;
1696     }
1697
1698     if( (i_pts != tk->i_pts) && (!tk->b_muxed) )
1699     {
1700         p_block->i_pts = i_pts;
1701     }
1702
1703     /* Update our global npt value */
1704     if( tk->i_npt > 0 && tk->i_npt > p_sys->i_npt && tk->i_npt < p_sys->i_npt_length)
1705         p_sys->i_npt = tk->i_npt;
1706
1707     if( !tk->b_muxed )
1708     {
1709         /*FIXME: for h264 you should check that packetization-mode=1 in sdp-file */
1710         p_block->i_dts = ( tk->fmt.i_codec == VLC_CODEC_MPGV ) ? 0 : i_pts;
1711     }
1712
1713     if( tk->b_muxed )
1714     {
1715         stream_DemuxSend( tk->p_out_muxed, p_block );
1716     }
1717     else if( tk->b_asf )
1718     {
1719         stream_DemuxSend( p_sys->p_out_asf, p_block );
1720     }
1721     else
1722     {
1723         es_out_Send( p_demux->out, tk->p_es, p_block );
1724     }
1725
1726     /* warn that's ok */
1727     p_sys->event = 0xff;
1728
1729     /* we have read data */
1730     tk->waiting = 0;
1731     p_demux->p_sys->b_no_data = false;
1732     p_demux->p_sys->i_no_data_ti = 0;
1733
1734     if( i_pts > 0 && !tk->b_muxed )
1735     {
1736         tk->i_pts = i_pts;
1737     }
1738 }
1739
1740 /*****************************************************************************
1741  *
1742  *****************************************************************************/
1743 static void StreamClose( void *p_private )
1744 {
1745     live_track_t   *tk = (live_track_t*)p_private;
1746     demux_t        *p_demux = tk->p_demux;
1747     demux_sys_t    *p_sys = p_demux->p_sys;
1748
1749     msg_Dbg( p_demux, "StreamClose" );
1750
1751     p_sys->event = 0xff;
1752     p_demux->b_error = true;
1753 }
1754
1755
1756 /*****************************************************************************
1757  *
1758  *****************************************************************************/
1759 static void TaskInterrupt( void *p_private )
1760 {
1761     demux_t *p_demux = (demux_t*)p_private;
1762
1763     p_demux->p_sys->i_no_data_ti++;
1764
1765     /* Avoid lock */
1766     p_demux->p_sys->event = 0xff;
1767 }
1768
1769 /*****************************************************************************
1770  *
1771  *****************************************************************************/
1772 static void* TimeoutPrevention( void *p_data )
1773 {
1774     timeout_thread_t *p_timeout = (timeout_thread_t *)p_data;
1775
1776     for( ;; )
1777     {
1778         /* Voodoo (= no) thread safety here! *Ahem* */
1779         if( p_timeout->b_handle_keep_alive )
1780         {
1781             char *psz_bye = NULL;
1782             int canc = vlc_savecancel ();
1783
1784             p_timeout->p_sys->rtsp->getMediaSessionParameter( *p_timeout->p_sys->ms, NULL, psz_bye );
1785             vlc_restorecancel (canc);
1786         }
1787         p_timeout->p_sys->b_timeout_call = !p_timeout->b_handle_keep_alive;
1788
1789         msleep (((int64_t)p_timeout->p_sys->i_timeout - 2) * CLOCK_FREQ);
1790     }
1791     assert(0); /* dead code */
1792 }
1793
1794 /*****************************************************************************
1795  *
1796  *****************************************************************************/
1797 static int ParseASF( demux_t *p_demux )
1798 {
1799     demux_sys_t    *p_sys = p_demux->p_sys;
1800
1801     const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1802     char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1803     char *psz_end;
1804     block_t *p_header;
1805
1806     /* Parse the asf header */
1807     if( psz_asf == NULL )
1808         return VLC_EGENERIC;
1809
1810     psz_asf += strlen( psz_marker );
1811     psz_asf = strdup( psz_asf );    /* Duplicate it */
1812     psz_end = strchr( psz_asf, '\n' );
1813
1814     while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1815         *psz_end-- = '\0';
1816
1817     if( psz_asf >= psz_end )
1818     {
1819         free( psz_asf );
1820         return VLC_EGENERIC;
1821     }
1822
1823     /* Always smaller */
1824     p_header = block_New( p_demux, psz_end - psz_asf );
1825     p_header->i_buffer = vlc_b64_decode_binary_to_buffer( p_header->p_buffer,
1826                                                p_header->i_buffer, psz_asf );
1827     //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
1828     if( p_header->i_buffer <= 0 )
1829     {
1830         free( psz_asf );
1831         return VLC_EGENERIC;
1832     }
1833
1834     /* Parse it to get packet size */
1835     asf_HeaderParse( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
1836
1837     /* Send it to demuxer */
1838     stream_DemuxSend( p_sys->p_out_asf, p_header );
1839
1840     free( psz_asf );
1841     return VLC_SUCCESS;
1842 }
1843
1844
1845 static unsigned char* parseH264ConfigStr( char const* configStr,
1846                                           unsigned int& configSize )
1847 {
1848     char *dup, *psz;
1849     size_t i_records = 1;
1850
1851     configSize = 0;
1852
1853     if( configStr == NULL || *configStr == '\0' )
1854         return NULL;
1855
1856     psz = dup = strdup( configStr );
1857
1858     /* Count the number of commas */
1859     for( psz = dup; *psz != '\0'; ++psz )
1860     {
1861         if( *psz == ',')
1862         {
1863             ++i_records;
1864             *psz = '\0';
1865         }
1866     }
1867
1868     size_t configMax = 5*strlen(dup);
1869     unsigned char *cfg = new unsigned char[configMax];
1870     psz = dup;
1871     for( size_t i = 0; i < i_records; ++i )
1872     {
1873         cfg[configSize++] = 0x00;
1874         cfg[configSize++] = 0x00;
1875         cfg[configSize++] = 0x00;
1876         cfg[configSize++] = 0x01;
1877
1878         configSize += vlc_b64_decode_binary_to_buffer( cfg+configSize,
1879                                           configMax-configSize, psz );
1880         psz += strlen(psz)+1;
1881     }
1882
1883     free( dup );
1884     return cfg;
1885 }