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