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