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