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