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