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