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