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