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