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