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