]> git.sesse.net Git - vlc/blob - modules/demux/livedotcom.cpp
* backport of [11500] [11501] and [11502]
[vlc] / modules / demux / livedotcom.cpp
1 /*****************************************************************************
2  * live.cpp : live.com support.
3  *****************************************************************************
4  * Copyright (C) 2003-2004 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>                                      /* malloc(), free() */
28
29 #include <vlc/vlc.h>
30 #include <vlc/input.h>
31 #include "network.h"
32
33 #include <iostream>
34
35 #if defined( WIN32 )
36 #   include <winsock2.h>
37 #endif
38
39 #include "BasicUsageEnvironment.hh"
40 #include "GroupsockHelper.hh"
41 #include "liveMedia.hh"
42
43 extern "C" {
44 #include "../access/mms/asf.h"  /* Who said ugly ? */
45 }
46
47 #if (LIVEMEDIA_LIBRARY_VERSION_INT < 1089936000)
48 #define RECLAIM_ENV(env) delete (env)
49 #else
50 #define RECLAIM_ENV(env) (env)->reclaim()
51 #endif
52
53 using namespace std;
54
55 /*****************************************************************************
56  * Module descriptor
57  *****************************************************************************/
58 static int  Open ( vlc_object_t * );
59 static void Close( vlc_object_t * );
60
61 #define CACHING_TEXT N_("Caching value (ms)")
62 #define CACHING_LONGTEXT N_( \
63     "Allows you to modify the default caching value for RTSP streams. This " \
64     "value should be set in millisecond units." )
65
66 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
67 #define KASENNA_LONGTEXT N_( "Kasenna server speak an old and unstandard " \
68     "dialect of RTSP. When you set this parameter, VLC will try this dialect "\
69     "for communication. In this mode you cannot talk to normal RTSP servers." )
70
71 vlc_module_begin();
72     set_description( _("live.com (RTSP/RTP/SDP) demuxer" ) );
73     set_capability( "demux2", 50 );
74     set_shortname( "Live.com RTP/RTSP");
75     set_callbacks( Open, Close );
76     add_shortcut( "live" );
77     set_category( CAT_INPUT );
78     set_subcategory( SUBCAT_INPUT_DEMUX );
79
80     add_submodule();
81         set_description( _("RTSP/RTP access and demux") );
82         add_shortcut( "rtsp" );
83         add_shortcut( "sdp" );
84         set_capability( "access_demux", 0 );
85         set_callbacks( Open, Close );
86         add_bool( "rtsp-tcp", 0, NULL,
87                   N_("Use RTP over RTSP (TCP)"),
88                   N_("Use RTP over RTSP (TCP)"), VLC_TRUE );
89         add_integer( "rtsp-caching", 4 * DEFAULT_PTS_DELAY / 1000, NULL,
90             CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
91         add_bool( "rtsp-kasenna", VLC_FALSE, NULL, KASENNA_TEXT,
92                   KASENNA_LONGTEXT, VLC_TRUE );
93 vlc_module_end();
94
95 /* TODO:
96  *  - Improve support of PS/TS
97  *  - Support X-QT/X-QUICKTIME generic codec for audio.
98  *
99  *  - Check memory leak, delete/free -> still one when using rtsp-tcp but I'm
100  *  not sure if it comes from me.
101  *
102  */
103
104 /*****************************************************************************
105  * Local prototypes
106  *****************************************************************************/
107 typedef struct
108 {
109     demux_t     *p_demux;
110
111     vlc_bool_t   b_quicktime;
112     vlc_bool_t   b_muxed;
113     vlc_bool_t   b_asf;
114
115     es_format_t  fmt;
116     es_out_id_t  *p_es;
117
118     stream_t     *p_out_muxed;    /* for muxed stream */
119
120     RTPSource    *rtpSource;
121     FramedSource *readSource;
122     vlc_bool_t   b_rtcp_sync;
123
124     uint8_t      *p_buffer;
125     unsigned int  i_buffer;
126
127     char         waiting;
128
129     mtime_t      i_pts;
130
131 } live_track_t;
132
133 struct demux_sys_t
134 {
135     char         *p_sdp;    /* XXX mallocated */
136     char         *psz_path; /* URL-encoded path */
137
138     MediaSession     *ms;
139     TaskScheduler    *scheduler;
140     UsageEnvironment *env ;
141     RTSPClient       *rtsp;
142
143     /* */
144     int              i_track;
145     live_track_t     **track;   /* XXX mallocated */
146     mtime_t          i_pcr;
147     mtime_t          i_pcr_start;
148
149     /* Asf */
150     asf_header_t     asfh;
151     stream_t         *p_out_asf;
152
153     /* */
154     mtime_t          i_length;
155     mtime_t          i_start;
156
157     /* */
158     vlc_bool_t       b_multicast;   /* true if one of the tracks is multicasted */
159     vlc_bool_t       b_no_data;     /* true if we never receive any data */
160     int              i_no_data_ti;  /* consecutive number of TaskInterrupt */
161
162     char             event;
163 };
164
165 static int Demux  ( demux_t * );
166 static int Control( demux_t *, int, va_list );
167
168 static int ParseASF( demux_t * );
169
170 static int RollOverTcp( demux_t * );
171
172 static void StreamRead( void *, unsigned int, unsigned int,
173                         struct timeval, unsigned int );
174 static void StreamClose( void * );
175 static void TaskInterrupt( void * );
176
177 /*****************************************************************************
178  * DemuxOpen:
179  *****************************************************************************/
180 static int  Open ( vlc_object_t *p_this )
181 {
182     demux_t     *p_demux = (demux_t*)p_this;
183     demux_sys_t *p_sys;
184
185     MediaSubsessionIterator *iter;
186     MediaSubsession *sub;
187
188     vlc_bool_t b_rtsp_tcp;
189     uint8_t *p_peek;
190
191     int     i_sdp;
192     int     i_sdp_max;
193     uint8_t *p_sdp;
194
195     if( p_demux->s )
196     {
197         /* See if it looks like a SDP
198            v, o, s fields are mandatory and in this order */
199         if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
200
201         if( strncmp( (char*)p_peek, "v=0\r\n", 5 ) &&
202             strncmp( (char*)p_peek, "v=0\n", 4 ) &&
203             ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
204         {
205             return VLC_EGENERIC;
206         }
207     }
208     else
209     {
210         var_Create( p_demux, "rtsp-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
211     }
212
213     p_demux->pf_demux  = Demux;
214     p_demux->pf_control= Control;
215     p_demux->p_sys     = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
216     p_sys->p_sdp = NULL;
217     p_sys->scheduler = NULL;
218     p_sys->env = NULL;
219     p_sys->ms = NULL;
220     p_sys->rtsp = NULL;
221     p_sys->i_track = 0;
222     p_sys->track   = NULL;
223     p_sys->i_pcr   = 0;
224     p_sys->i_pcr_start = 0;
225     p_sys->i_length = 0;
226     p_sys->i_start = 0;
227     p_sys->p_out_asf = NULL;
228     p_sys->b_no_data = VLC_TRUE;
229     p_sys->i_no_data_ti = 0;
230     p_sys->b_multicast = VLC_FALSE;
231     p_sys->psz_path = p_demux->psz_path;
232
233
234     if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
235     {
236         msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
237         goto error;
238     }
239     if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
240     {
241         msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
242         goto error;
243     }
244
245     if( strcasecmp( p_demux->psz_access, "sdp" ) && 
246         vlc_UrlIsNotEncoded( p_sys->psz_path ) )
247     {
248         p_sys->psz_path = vlc_UrlEncode( p_sys->psz_path );
249         if( p_sys->psz_path == NULL )
250             goto error;
251     }
252
253     if( p_demux->s == NULL && !strcasecmp( p_demux->psz_access, "rtsp" ) )
254     {
255         char *psz_url;
256         char *psz_options;
257
258         if( ( p_sys->rtsp = RTSPClient::createNew(*p_sys->env, 1/*verbose*/,
259               "VLC Media Player" ) ) == NULL )
260         {
261             msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
262                      p_sys->env->getResultMsg() );
263             goto error;
264         }
265         psz_url = (char*)malloc( strlen( p_sys->psz_path ) + 8 );
266         sprintf( psz_url, "rtsp://%s", p_sys->psz_path );
267
268         psz_options = p_sys->rtsp->sendOptionsCmd( psz_url );
269         if( psz_options )
270             delete [] psz_options;
271
272         p_sdp = (uint8_t*)p_sys->rtsp->describeURL( psz_url,
273                               NULL, var_CreateGetBool( p_demux, "rtsp-kasenna" ) );
274         if( p_sdp == NULL )
275         {
276             msg_Err( p_demux, "describeURL failed (%s)",
277                      p_sys->env->getResultMsg() );
278             free( psz_url );
279             goto error;
280         }
281         free( psz_url );
282
283         /* malloc-ated copy */
284         p_sys->p_sdp = strdup( (char*)p_sdp );
285         delete[] p_sdp;
286         fprintf( stderr, "sdp=%s\n", p_sys->p_sdp );
287     }
288     else if( p_demux->s == NULL && !strcasecmp( p_demux->psz_access, "sdp" ) )
289     {
290         p_sys->p_sdp = strdup( p_sys->psz_path );
291     }
292     else
293     {
294         /* Gather the complete sdp file */
295         i_sdp = 0;
296         i_sdp_max = 1000;
297         p_sdp = (uint8_t*)malloc( i_sdp_max );
298         for( ;; )
299         {
300             int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
301                                       i_sdp_max - i_sdp - 1 );
302
303             if( i_read < 0 )
304             {
305                 msg_Err( p_demux, "failed to read SDP" );
306                 free( p_sys );
307                 return VLC_EGENERIC;
308             }
309
310             i_sdp += i_read;
311
312             if( i_read < i_sdp_max - i_sdp - 1 )
313             {
314                 p_sdp[i_sdp] = '\0';
315                 break;
316             }
317
318             i_sdp_max += 1000;
319             p_sdp = (uint8_t*)realloc( p_sdp, i_sdp_max );
320         }
321         p_sys->p_sdp = (char*)p_sdp;
322
323         msg_Dbg( p_demux, "sdp=%s\n", p_sys->p_sdp );
324     }
325     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
326     {
327         msg_Err( p_demux, "MediaSession::createNew failed" );
328         goto error;
329     }
330
331     b_rtsp_tcp = var_CreateGetBool( p_demux, "rtsp-tcp" );
332
333     /* Initialise each media subsession */
334     iter = new MediaSubsessionIterator( *p_sys->ms );
335     while( ( sub = iter->next() ) != NULL )
336     {
337         unsigned int i_buffer = 0;
338         Boolean bInit;
339
340         /* Value taken from mplayer */
341         if( !strcmp( sub->mediumName(), "audio" ) )
342             i_buffer = 100000;
343         else if( !strcmp( sub->mediumName(), "video" ) )
344             i_buffer = 2000000;
345         else
346             continue;
347
348         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
349             bInit = sub->initiate( 4 ); /* Constant ? */
350         else
351             bInit = sub->initiate();
352
353         if( !bInit )
354         {
355             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
356                       sub->mediumName(), sub->codecName(),
357                       p_sys->env->getResultMsg() );
358         }
359         else
360         {
361             if( sub->rtpSource() )
362             {
363                 int fd = sub->rtpSource()->RTPgs()->socketNum();
364                 /* Increase the buffer size */
365                 increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
366             }
367
368             msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
369                      sub->codecName() );
370
371             /* Issue the SETUP */
372             if( p_sys->rtsp )
373             {
374                 p_sys->rtsp->setupMediaSubsession( *sub, False,
375                                                    b_rtsp_tcp ? True : False );
376             }
377             if( !p_sys->b_multicast )
378             {
379                 /* Check, because we need diff. rollover behaviour for multicast */
380                 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
381             }
382         }
383     }
384
385     if( p_sys->rtsp )
386     {
387         /* The PLAY */
388         if( !p_sys->rtsp->playMediaSession( *p_sys->ms ) )
389         {
390             msg_Err( p_demux, "PLAY failed %s", p_sys->env->getResultMsg() );
391             goto error;
392         }
393     }
394
395     /* Create all es struct */
396     iter->reset();
397     while( ( sub = iter->next() ) != NULL )
398     {
399         live_track_t *tk;
400
401         if( sub->readSource() == NULL )
402         {
403             continue;
404         }
405
406         tk = (live_track_t*)malloc( sizeof( live_track_t ) );
407         tk->p_demux = p_demux;
408         tk->waiting = 0;
409         tk->i_pts   = 0;
410         tk->b_quicktime = VLC_FALSE;
411         tk->b_muxed     = VLC_FALSE;
412         tk->b_asf       = VLC_FALSE;
413         tk->b_rtcp_sync = VLC_FALSE;
414         tk->p_out_muxed = NULL;
415         tk->p_es        = NULL;
416         tk->i_buffer    = 65536;
417         tk->p_buffer    = (uint8_t *)malloc( 65536 );
418
419         /* Value taken from mplayer */
420         if( !strcmp( sub->mediumName(), "audio" ) )
421         {
422             es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
423             tk->fmt.audio.i_channels = sub->numChannels();
424             tk->fmt.audio.i_rate = sub->rtpSource()->timestampFrequency();
425
426             if( !strcmp( sub->codecName(), "MPA" ) ||
427                 !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
428                 !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
429             {
430                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
431                 tk->fmt.audio.i_rate = 0;
432             }
433             else if( !strcmp( sub->codecName(), "AC3" ) )
434             {
435                 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
436                 tk->fmt.audio.i_rate = 0;
437             }
438             else if( !strcmp( sub->codecName(), "L16" ) )
439             {
440                 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
441                 tk->fmt.audio.i_bitspersample = 16;
442             }
443             else if( !strcmp( sub->codecName(), "L8" ) )
444             {
445                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
446                 tk->fmt.audio.i_bitspersample = 8;
447             }
448             else if( !strcmp( sub->codecName(), "PCMU" ) )
449             {
450                 tk->fmt.i_codec = VLC_FOURCC( 'u', 'l', 'a', 'w' );
451             }
452             else if( !strcmp( sub->codecName(), "PCMA" ) )
453             {
454                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'l', 'a', 'w' );
455             }
456             else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
457             {
458                 unsigned int i_extra;
459                 uint8_t      *p_extra;
460
461                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
462
463                 if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
464                                                          i_extra ) ) )
465                 {
466                     tk->fmt.i_extra = i_extra;
467                     tk->fmt.p_extra = malloc( i_extra );
468                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
469                     delete[] p_extra;
470                 }
471             }
472             else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
473             {
474                 unsigned int i_extra;
475                 uint8_t      *p_extra;
476
477                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
478
479                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
480                                                        i_extra ) ) )
481                 {
482                     tk->fmt.i_extra = i_extra;
483                     tk->fmt.p_extra = malloc( i_extra );
484                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
485                     delete[] p_extra;
486                 }
487             }
488             else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
489             {
490                 tk->b_asf = VLC_TRUE;
491                 if( p_sys->p_out_asf == NULL )
492                     p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
493                                                         p_demux->out );
494             }
495         }
496         else if( !strcmp( sub->mediumName(), "video" ) )
497         {
498             es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
499             if( !strcmp( sub->codecName(), "MPV" ) )
500             {
501                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
502             }
503             else if( !strcmp( sub->codecName(), "H263" ) ||
504                      !strcmp( sub->codecName(), "H263-1998" ) ||
505                      !strcmp( sub->codecName(), "H263-2000" ) )
506             {
507                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '3' );
508             }
509             else if( !strcmp( sub->codecName(), "H261" ) )
510             {
511                 tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '1' );
512             }
513             else if( !strcmp( sub->codecName(), "JPEG" ) )
514             {
515                 tk->fmt.i_codec = VLC_FOURCC( 'M', 'J', 'P', 'G' );
516             }
517             else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
518             {
519                 unsigned int i_extra;
520                 uint8_t      *p_extra;
521
522                 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
523
524                 if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
525                                                        i_extra ) ) )
526                 {
527                     tk->fmt.i_extra = i_extra;
528                     tk->fmt.p_extra = malloc( i_extra );
529                     memcpy( tk->fmt.p_extra, p_extra, i_extra );
530                     delete[] p_extra;
531                 }
532             }
533             else if( !strcmp( sub->codecName(), "X-QT" ) ||
534                      !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
535                      !strcmp( sub->codecName(), "X-QDM" ) ||
536                      !strcmp( sub->codecName(), "X-SV3V-ES" )  ||
537                      !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
538             {
539                 tk->b_quicktime = VLC_TRUE;
540             }
541             else if( !strcmp( sub->codecName(), "MP2T" ) )
542             {
543                 tk->b_muxed = VLC_TRUE;
544                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
545             }
546             else if( !strcmp( sub->codecName(), "MP2P" ) ||
547                      !strcmp( sub->codecName(), "MP1S" ) )
548             {
549                 tk->b_muxed = VLC_TRUE;
550                 tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
551                                                    p_demux->out );
552             }
553             else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
554             {
555                 tk->b_asf = VLC_TRUE;
556                 if( p_sys->p_out_asf == NULL )
557                     p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
558                                                         p_demux->out );;
559             }
560         }
561
562         if( tk->fmt.i_codec != VLC_FOURCC( 'u', 'n', 'd', 'f' ) )
563         {
564             tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
565         }
566
567         if( sub->rtcpInstance() != NULL )
568         {
569             sub->rtcpInstance()->setByeHandler( StreamClose, tk );
570         }
571
572         if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
573         {
574             tk->readSource = sub->readSource();
575             tk->rtpSource  = sub->rtpSource();
576
577             /* Append */
578             p_sys->track = (live_track_t**)realloc( p_sys->track, sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
579             p_sys->track[p_sys->i_track++] = tk;
580         }
581         else
582         {
583             free( tk );
584         }
585     }
586
587     delete iter;
588
589     if( p_sys->p_out_asf && ParseASF( p_demux ) )
590     {
591         msg_Err( p_demux, "cannot find a usable asf header" );
592         /* TODO Clean tracks */
593         goto error;
594     }
595
596     p_sys->i_length = (mtime_t)(p_sys->ms->playEndTime() * 1000000.0);
597     if( p_sys->i_length < 0 )
598     {
599         p_sys->i_length = 0;
600     }
601     else if( p_sys->i_length > 0 )
602     {
603         /* FIXME */
604         /* p_input->stream.p_selected_area->i_size = 1000;*/ /* needed for now */
605     }
606
607     if( p_sys->i_track <= 0 )
608     {
609         msg_Err( p_demux, "no codec supported, aborting" );
610         goto error;
611     }
612
613     return VLC_SUCCESS;
614
615 error:
616     if( p_sys->p_out_asf )
617     {
618         stream_DemuxDelete( p_sys->p_out_asf );
619     }
620     if( p_sys->ms )
621     {
622         Medium::close( p_sys->ms );
623     }
624     if( p_sys->rtsp )
625     {
626         Medium::close( p_sys->rtsp );
627     }
628     if( p_sys->env )
629     {
630         RECLAIM_ENV(p_sys->env);
631     }
632     if( p_sys->scheduler )
633     {
634         delete p_sys->scheduler;
635     }
636     if( p_sys->p_sdp )
637     {
638         free( p_sys->p_sdp );
639     }
640     if( ( p_sys->psz_path != NULL )
641      && ( p_sys->psz_path != p_demux->psz_path ) )
642         free( p_sys->psz_path );
643
644     free( p_sys );
645     return VLC_EGENERIC;
646 }
647
648 /*****************************************************************************
649  * DemuxClose:
650  *****************************************************************************/
651 static void Close( vlc_object_t *p_this )
652 {
653     demux_t *p_demux = (demux_t*)p_this;
654     demux_sys_t *p_sys = p_demux->p_sys;
655     int i;
656
657     for( i = 0; i < p_sys->i_track; i++ )
658     {
659         live_track_t *tk = p_sys->track[i];
660
661         if( tk->b_muxed ) stream_DemuxDelete( tk->p_out_muxed );
662         free( tk->p_buffer );
663         free( tk );
664     }
665
666     if( p_sys->i_track ) free( p_sys->track );
667     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
668
669     if( p_sys->rtsp && p_sys->ms )
670     {
671         /* TEARDOWN */
672         p_sys->rtsp->teardownMediaSession( *p_sys->ms );
673     }
674
675     Medium::close( p_sys->ms );
676
677     if( p_sys->rtsp ) Medium::close( p_sys->rtsp );
678     if( p_sys->env ) RECLAIM_ENV(p_sys->env);
679     if( p_sys->scheduler ) delete p_sys->scheduler;
680     if( p_sys->p_sdp ) free( p_sys->p_sdp );
681     if( p_sys->psz_path != p_demux->psz_path )
682         free( p_sys->psz_path );
683     free( p_sys );
684 }
685
686 /*****************************************************************************
687  * Demux:
688  *****************************************************************************/
689 static int Demux( demux_t *p_demux )
690 {
691     demux_sys_t    *p_sys = p_demux->p_sys;
692     TaskToken      task;
693
694     vlc_bool_t      b_send_pcr = VLC_TRUE;
695     mtime_t         i_pcr = 0;
696     int             i;
697
698     for( i = 0; i < p_sys->i_track; i++ )
699     {
700         live_track_t *tk = p_sys->track[i];
701
702         if( tk->b_asf || tk->b_muxed )
703             b_send_pcr = VLC_FALSE;
704
705         if( i_pcr == 0 )
706         {
707             i_pcr = tk->i_pts;
708         }
709         else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
710         {
711             i_pcr = tk->i_pts ;
712         }
713     }
714     if( i_pcr != p_sys->i_pcr && i_pcr > 0 )
715     {
716         p_sys->i_pcr = i_pcr;
717
718         if( b_send_pcr )
719             es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pcr );
720         if( p_sys->i_pcr_start <= 0 || p_sys->i_pcr_start > i_pcr ||
721             ( p_sys->i_length > 0 && i_pcr - p_sys->i_pcr_start > p_sys->i_length ) )
722         {
723             p_sys->i_pcr_start = i_pcr;
724         }
725     }
726
727     /* First warm we want to read data */
728     p_sys->event = 0;
729     for( i = 0; i < p_sys->i_track; i++ )
730     {
731         live_track_t *tk = p_sys->track[i];
732
733         if( tk->waiting == 0 )
734         {
735             tk->waiting = 1;
736             tk->readSource->getNextFrame( tk->p_buffer, tk->i_buffer,
737                                           StreamRead, tk, StreamClose, tk );
738         }
739     }
740     /* Create a task that will be called if we wait more than 300ms */
741     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
742
743     /* Do the read */
744     p_sys->scheduler->doEventLoop( &p_sys->event );
745
746     /* remove the task */
747     p_sys->scheduler->unscheduleDelayedTask( task );
748
749     /* Check for gap in pts value */
750     for( i = 0; i < p_sys->i_track; i++ )
751     {
752         live_track_t *tk = p_sys->track[i];
753
754         if( !tk->b_muxed && !tk->b_rtcp_sync &&
755             tk->rtpSource->hasBeenSynchronizedUsingRTCP() )
756         {
757             msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
758
759             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
760             tk->b_rtcp_sync = VLC_TRUE;
761
762             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
763             tk->i_pts = 0;
764             p_sys->i_pcr_start = 0;
765             p_sys->i_pcr = 0;
766             i_pcr = 0;
767         }
768     }
769
770     if( p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 120 )
771     {
772         /* FIXME Make this configurable
773         msg_Err( p_demux, "no multicast data received in 36s, aborting" );
774         return 0;
775         */
776     }
777     else if( !p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 3 )
778     {
779         vlc_bool_t b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" );
780
781         if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
782         {
783             msg_Warn( p_demux, "no data received in 900ms. Switching to TCP" );
784             if( RollOverTcp( p_demux ) )
785             {
786                 msg_Err( p_demux, "TCP rollover failed, aborting" );
787                 return 0;
788             }
789             var_SetBool( p_demux, "rtsp-tcp", VLC_TRUE );
790         }
791         else if( p_sys->i_no_data_ti > 10 )
792         {
793             msg_Err( p_demux, "no data received in 3s, aborting" );
794             return 0;
795         }
796     }
797     else if( !p_sys->b_multicast && p_sys->b_no_data&& p_sys->i_no_data_ti > 10 )
798     {
799         /* EOF ? */
800         msg_Warn( p_demux, "no data received in 3s, eof ?" );
801         return 0;
802     }
803
804     return p_demux->b_error ? 0 : 1;
805 }
806
807 /*****************************************************************************
808  * Control:
809  *****************************************************************************/
810 static int Control( demux_t *p_demux, int i_query, va_list args )
811 {
812     demux_sys_t *p_sys = p_demux->p_sys;
813     int64_t *pi64;
814     double  *pf, f;
815     vlc_bool_t *pb, b_bool;
816
817     switch( i_query )
818     {
819         case DEMUX_GET_TIME:
820             pi64 = (int64_t*)va_arg( args, int64_t * );
821             *pi64 = p_sys->i_pcr - p_sys->i_pcr_start + p_sys->i_start;
822             return VLC_SUCCESS;
823
824         case DEMUX_GET_LENGTH:
825             pi64 = (int64_t*)va_arg( args, int64_t * );
826             *pi64 = p_sys->i_length;
827             return VLC_SUCCESS;
828
829         case DEMUX_GET_POSITION:
830             pf = (double*)va_arg( args, double* );
831             if( p_sys->i_length > 0 )
832             {
833                 *pf = (double)( p_sys->i_pcr - p_sys->i_pcr_start +
834                                 p_sys->i_start ) / (double)(p_sys->i_length);
835             }
836             else
837             {
838                 *pf = 0;
839             }
840             return VLC_SUCCESS;
841
842         case DEMUX_SET_POSITION:
843         {
844             float time;
845
846             f = (double)va_arg( args, double );
847             time = f * (double)p_sys->i_length / 1000000.0;   /* in second */
848
849             if( p_sys->rtsp && p_sys->i_length > 0 )
850             {
851                 MediaSubsessionIterator *iter =
852                     new MediaSubsessionIterator( *p_sys->ms );
853                 MediaSubsession *sub;
854                 int i;
855
856                 while( ( sub = iter->next() ) != NULL )
857                 {
858                     p_sys->rtsp->playMediaSubsession( *sub, time );
859                 }
860                 delete iter;
861                 p_sys->i_start = (mtime_t)(f * (double)p_sys->i_length);
862                 p_sys->i_pcr_start = 0;
863                 p_sys->i_pcr       = 0;
864                 
865                 for( i = 0; i < p_sys->i_track; i++ )
866                 {
867                     p_sys->track[i]->i_pts = 0;
868                 }
869
870                 return VLC_SUCCESS;
871             }
872             return VLC_SUCCESS;
873         }
874
875         /* Special for access_demux */
876         case DEMUX_CAN_PAUSE:
877             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
878             if( p_sys->rtsp && p_sys->i_length )
879                 /* Not always true, but will be handled in SET_PAUSE_STATE */
880                 *pb = VLC_TRUE;
881             else
882                 *pb = VLC_FALSE;
883             return VLC_SUCCESS;
884
885         case DEMUX_CAN_CONTROL_PACE:
886             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
887
888 #if 0       /* Disable for now until we have a clock synchro algo
889              * which works with something else than MPEG over UDP */
890             *pb = VLC_FALSE;
891 #endif
892             *pb = VLC_TRUE;
893             return VLC_SUCCESS;
894
895         case DEMUX_SET_PAUSE_STATE:
896             double d_npt;
897             MediaSubsessionIterator *iter;
898             MediaSubsession *sub;
899
900             d_npt = ( (double)( p_sys->i_pcr - p_sys->i_pcr_start +
901                                 p_sys->i_start ) ) / 1000000.00;
902
903             b_bool = (vlc_bool_t)va_arg( args, vlc_bool_t );
904             if( p_sys->rtsp == NULL )
905                 return VLC_EGENERIC;
906
907             iter = new MediaSubsessionIterator( *p_sys->ms );
908             while( ( sub = iter->next() ) != NULL )
909             {
910                 if( ( b_bool && !p_sys->rtsp->pauseMediaSubsession( *sub ) ) ||
911                     ( !b_bool && !p_sys->rtsp->playMediaSubsession( *sub,
912                       d_npt > 0 ? d_npt : -1 ) ) )
913                 {
914                     delete iter;
915                     return VLC_EGENERIC;
916                 }
917             }
918             delete iter;
919 #if 0
920             /* reset PCR and PCR start, mmh won't work well for multi-stream I fear */
921             for( i = 0; i < p_sys->i_track; i++ )
922             {
923                 p_sys->track[i]->i_pts = 0;
924             }
925             p_sys->i_pcr_start = 0; /* FIXME Wrong */
926             p_sys->i_pcr = 0;
927 #endif
928             return VLC_SUCCESS;
929
930         case DEMUX_GET_TITLE_INFO:
931         case DEMUX_SET_TITLE:
932         case DEMUX_SET_SEEKPOINT:
933             return VLC_EGENERIC;
934
935         case DEMUX_GET_PTS_DELAY:
936             pi64 = (int64_t*)va_arg( args, int64_t * );
937             *pi64 = (int64_t)var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
938             return VLC_SUCCESS;
939
940         default:
941             return VLC_EGENERIC;
942     }
943 }
944
945 /*****************************************************************************
946  * RollOverTcp: reopen the rtsp into TCP mode
947  * XXX: ugly, a lot of code are duplicated from Open()
948  *****************************************************************************/
949 static int RollOverTcp( demux_t *p_demux )
950 {
951     demux_sys_t *p_sys = p_demux->p_sys;
952     MediaSubsessionIterator *iter;
953     MediaSubsession *sub;
954     char *psz_url;
955     char *psz_options;
956     uint8_t *p_sdp;
957     int i_tk;
958
959     /* We close the old RTSP session */
960     p_sys->rtsp->teardownMediaSession( *p_sys->ms );
961
962     Medium::close( p_sys->ms );
963     Medium::close( p_sys->rtsp );
964
965     p_sys->ms = NULL;
966     p_sys->rtsp = NULL;
967
968     /* Reopen rtsp client */
969     if( ( p_sys->rtsp = RTSPClient::createNew(*p_sys->env, 1/*verbose*/,
970           "VLC Media Player" ) ) == NULL )
971     {
972         msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
973                  p_sys->env->getResultMsg() );
974         return VLC_EGENERIC;
975     }
976
977     asprintf( &psz_url, "rtsp://%s", p_sys->psz_path );
978
979     if( ( psz_options = p_sys->rtsp->sendOptionsCmd( psz_url ) ) )
980         delete [] psz_options;
981
982     p_sdp = (uint8_t*)p_sys->rtsp->describeURL( psz_url,
983                           NULL, var_CreateGetBool( p_demux, "rtsp-kasenna" ) );
984     free( psz_url );
985     if( p_sdp == NULL )
986     {
987         msg_Err( p_demux, "describeURL failed (%s)",
988                  p_sys->env->getResultMsg() );
989         return VLC_EGENERIC;
990     }
991
992     /* malloc-ated copy */
993     p_sys->p_sdp = strdup( (char*)p_sdp );
994     delete[] p_sdp;
995
996     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
997     {
998         msg_Err( p_demux, "MediaSession::createNew failed" );
999         return VLC_EGENERIC;
1000     }
1001
1002     /* Initialise each media subsession */
1003     iter = new MediaSubsessionIterator( *p_sys->ms );
1004     while( ( sub = iter->next() ) != NULL )
1005     {
1006         Boolean bInit;
1007
1008         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
1009             bInit = sub->initiate( 4 ); /* Constant ? */
1010         else
1011             bInit = sub->initiate();
1012
1013         if( !bInit )
1014         {
1015             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
1016                       sub->mediumName(), sub->codecName(),
1017                       p_sys->env->getResultMsg() );
1018             continue;
1019         }
1020         msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
1021                  sub->codecName() );
1022
1023         /* Issue the SETUP */
1024         p_sys->rtsp->setupMediaSubsession( *sub, False, True /* tcp */ );
1025     }
1026
1027     /* The PLAY */
1028     if( !p_sys->rtsp->playMediaSession( *p_sys->ms ) )
1029     {
1030         msg_Err( p_demux, "PLAY failed %s", p_sys->env->getResultMsg() );
1031         return VLC_EGENERIC;
1032     }
1033
1034     /* Update all tracks */
1035     iter->reset();
1036     i_tk = 0;
1037     while( ( sub = iter->next() ) != NULL )
1038     {
1039         live_track_t *tk;
1040
1041         if( sub->readSource() == NULL )
1042             continue;
1043         if( i_tk >= p_sys->i_track )
1044         {
1045             msg_Err( p_demux, "WTF !" );
1046             break;
1047         }
1048
1049         tk = p_sys->track[i_tk];
1050
1051         /* Reset state */
1052         tk->waiting = 0;
1053         tk->i_pts   = 0;
1054         tk->b_rtcp_sync = VLC_FALSE;
1055
1056         if( sub->rtcpInstance() != NULL )
1057             sub->rtcpInstance()->setByeHandler( StreamClose, tk );
1058
1059         tk->readSource = sub->readSource();
1060         tk->rtpSource  = sub->rtpSource();
1061
1062         i_tk++;
1063     }
1064
1065     delete iter;
1066
1067     return VLC_SUCCESS;
1068 }
1069
1070
1071 /*****************************************************************************
1072  *
1073  *****************************************************************************/
1074 static void StreamRead( void *p_private, unsigned int i_size,
1075                         unsigned int i_truncated_bytes, struct timeval pts,
1076                         unsigned int duration )
1077 {
1078     live_track_t   *tk = (live_track_t*)p_private;
1079     demux_t        *p_demux = tk->p_demux;
1080     demux_sys_t    *p_sys = p_demux->p_sys;
1081     block_t        *p_block;
1082
1083     mtime_t i_pts = (uint64_t)pts.tv_sec * UI64C(1000000) +
1084         (uint64_t)pts.tv_usec;
1085
1086     /* XXX Beurk beurk beurk Avoid having negative value XXX */
1087     i_pts &= UI64C(0x00ffffffffffffff);
1088
1089     if( tk->b_quicktime && tk->p_es == NULL )
1090     {
1091         QuickTimeGenericRTPSource *qtRTPSource =
1092             (QuickTimeGenericRTPSource*)tk->rtpSource;
1093         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1094         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1095
1096         if( qtState.sdAtomSize < 16 + 32 )
1097         {
1098             /* invalid */
1099             p_sys->event = 0xff;
1100             tk->waiting = 0;
1101             return;
1102         }
1103         tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1104         tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
1105         tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1106
1107         tk->fmt.i_extra        = qtState.sdAtomSize - 16;
1108         tk->fmt.p_extra        = malloc( tk->fmt.i_extra );
1109         memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1110
1111         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1112     }
1113
1114 #if 0
1115     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1116              i_size,
1117              pts.tv_sec * 1000000LL + pts.tv_usec );
1118 #endif
1119
1120     /* grow buffer if it looks like buffer is too small, but don't eat
1121      * up all the memory on strange streams */
1122     if( i_truncated_bytes > 0 && tk->i_buffer < 2000000 )
1123     {
1124         void *p_tmp;
1125         msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1126         msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1127         tk->i_buffer *= 2;
1128         p_tmp = realloc( tk->p_buffer, tk->i_buffer );
1129         if (p_tmp == NULL)
1130         {
1131             msg_Warn( p_demux, "realloc failed" );
1132         }
1133         else
1134         {
1135             tk->p_buffer = (uint8_t*)p_tmp;
1136         }
1137     }
1138     if( i_size > tk->i_buffer )
1139     {
1140         msg_Warn( p_demux, "buffer overflow" );
1141     }
1142     /* FIXME could i_size be > buffer size ? */
1143     if( tk->fmt.i_codec == VLC_FOURCC('h','2','6','1') )
1144     {
1145 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1081468800
1146         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->rtpSource;
1147         uint32_t header = h261Source->lastSpecialHeader();
1148 #else
1149         uint32_t header = 0;
1150         msg_Warn( p_demux, "need livemedia library >= \"2004.04.09\"" );
1151 #endif
1152         p_block = block_New( p_demux, i_size + 4 );
1153         memcpy( p_block->p_buffer, &header, 4 );
1154         memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1155     }
1156     else if( tk->b_asf )
1157     {
1158         int i_copy = __MIN( p_sys->asfh.i_min_data_packet_size, (int)i_size );
1159         p_block = block_New( p_demux, p_sys->asfh.i_min_data_packet_size );
1160
1161         memcpy( p_block->p_buffer, tk->p_buffer, i_copy );
1162     }
1163     else
1164     {
1165         p_block = block_New( p_demux, i_size );
1166         memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1167     }
1168     if( tk->fmt.i_codec == VLC_FOURCC('h','2','6','1') &&
1169         tk->rtpSource->curPacketMarkerBit() )
1170     {
1171         p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1172     }
1173     //p_block->i_rate = p_input->stream.control.i_rate;
1174
1175     if( i_pts != tk->i_pts && !tk->b_muxed )
1176     {
1177         p_block->i_dts = ( tk->fmt.i_cat == VIDEO_ES ) ? 0 : i_pts;
1178         p_block->i_pts = i_pts;
1179     }
1180     //fprintf( stderr, "tk -> dpts=%lld\n", i_pts - tk->i_pts );
1181
1182     if( tk->b_muxed )
1183     {
1184         stream_DemuxSend( tk->p_out_muxed, p_block );
1185     }
1186     else if( tk->b_asf )
1187     {
1188         stream_DemuxSend( p_sys->p_out_asf, p_block );
1189     }
1190     else
1191     {
1192         es_out_Send( p_demux->out, tk->p_es, p_block );
1193     }
1194
1195     /* warm that's ok */
1196     p_sys->event = 0xff;
1197
1198     /* we have read data */
1199     tk->waiting = 0;
1200     p_demux->p_sys->b_no_data = VLC_FALSE;
1201     p_demux->p_sys->i_no_data_ti = 0;
1202
1203     if( i_pts > 0 && !tk->b_muxed )
1204     {
1205         tk->i_pts = i_pts;
1206     }
1207 }
1208
1209 /*****************************************************************************
1210  *
1211  *****************************************************************************/
1212 static void StreamClose( void *p_private )
1213 {
1214     live_track_t   *tk = (live_track_t*)p_private;
1215     demux_t        *p_demux = tk->p_demux;
1216     demux_sys_t    *p_sys = p_demux->p_sys;
1217
1218     fprintf( stderr, "StreamClose\n" );
1219
1220     p_sys->event = 0xff;
1221     p_demux->b_error = VLC_TRUE;
1222 }
1223
1224
1225 /*****************************************************************************
1226  *
1227  *****************************************************************************/
1228 static void TaskInterrupt( void *p_private )
1229 {
1230     demux_t *p_demux = (demux_t*)p_private;
1231
1232     fprintf( stderr, "TaskInterrupt\n" );
1233
1234     p_demux->p_sys->i_no_data_ti++;
1235
1236     /* Avoid lock */
1237     p_demux->p_sys->event = 0xff;
1238 }
1239
1240 /*****************************************************************************
1241  *
1242  *****************************************************************************/
1243 static int b64_decode( char *dest, char *src );
1244
1245 static int ParseASF( demux_t *p_demux )
1246 {
1247     demux_sys_t    *p_sys = p_demux->p_sys;
1248
1249     const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1250     char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1251     char *psz_end;
1252     block_t *p_header;
1253
1254     /* Parse the asf header */
1255     if( psz_asf == NULL )
1256         return VLC_EGENERIC;
1257
1258     psz_asf += strlen( psz_marker );
1259     psz_asf = strdup( psz_asf );    /* Duplicate it */
1260     psz_end = strchr( psz_asf, '\n' );
1261
1262     while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1263         *psz_end-- = '\0';
1264
1265     if( psz_asf >= psz_end )
1266     {
1267         free( psz_asf );
1268         return VLC_EGENERIC;
1269     }
1270
1271     /* Always smaller */
1272     p_header = block_New( p_demux, psz_end - psz_asf );
1273     p_header->i_buffer = b64_decode( (char*)p_header->p_buffer, psz_asf );
1274     fprintf( stderr, "Size=%d Hdrb64=%s\n", p_header->i_buffer, psz_asf );
1275     if( p_header->i_buffer <= 0 )
1276     {
1277         free( psz_asf );
1278         return VLC_EGENERIC;
1279     }
1280
1281     /* Parse it to get packet size */
1282     E_(asf_HeaderParse)( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
1283
1284     /* Send it to demuxer */
1285     stream_DemuxSend( p_sys->p_out_asf, p_header );
1286
1287     free( psz_asf );
1288     return VLC_SUCCESS;
1289 }
1290 /*char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";*/
1291 static int b64_decode( char *dest, char *src )
1292 {
1293     const char *dest_start = dest;
1294     int  i_level;
1295     int  last = 0;
1296     int  b64[256] = {
1297         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
1298         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
1299         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
1300         52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
1301         -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
1302         15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
1303         -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
1304         41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
1305         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
1306         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
1307         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
1308         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
1309         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
1310         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
1311         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
1312         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
1313         };
1314
1315     for( i_level = 0; *src != '\0'; src++ )
1316     {
1317         int  c;
1318
1319         c = b64[(unsigned int)*src];
1320         if( c == -1 )
1321         {
1322             continue;
1323         }
1324
1325         switch( i_level )
1326         {
1327             case 0:
1328                 i_level++;
1329                 break;
1330             case 1:
1331                 *dest++ = ( last << 2 ) | ( ( c >> 4)&0x03 );
1332                 i_level++;
1333                 break;
1334             case 2:
1335                 *dest++ = ( ( last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
1336                 i_level++;
1337                 break;
1338             case 3:
1339                 *dest++ = ( ( last &0x03 ) << 6 ) | c;
1340                 i_level = 0;
1341         }
1342         last = c;
1343     }
1344
1345     *dest = '\0';
1346
1347     return dest - dest_start;
1348 }