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