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