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