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