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