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