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