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