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