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