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