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