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