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