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