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