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