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