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