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