]> git.sesse.net Git - vlc/blob - modules/demux/live555.cpp
Reset PCR when gap has been detected.
[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  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29
30 #include <vlc/vlc.h>
31
32 #include <vlc_demux.h>
33 #include <vlc_interface.h>
34 #include <vlc_network.h>
35
36 #include <iostream>
37
38 #if defined( WIN32 )
39 #   include <winsock2.h>
40 #endif
41
42 #include "UsageEnvironment.hh"
43 #include "BasicUsageEnvironment.hh"
44 #include "GroupsockHelper.hh"
45 #include "liveMedia.hh"
46
47 extern "C" {
48 #include "../access/mms/asf.h"  /* Who said ugly ? */
49 }
50
51 using namespace std;
52
53 /*****************************************************************************
54  * Module descriptor
55  *****************************************************************************/
56 static int  Open ( vlc_object_t * );
57 static void Close( vlc_object_t * );
58
59 #define CACHING_TEXT N_("Caching value (ms)")
60 #define CACHING_LONGTEXT N_( \
61     "Allows you to modify the default caching value for RTSP streams. This " \
62     "value should be set in millisecond units." )
63
64 #define KASENNA_TEXT N_( "Kasenna RTSP dialect")
65 #define KASENNA_LONGTEXT N_( "Kasenna servers use an old and unstandard " \
66     "dialect of RTSP. When you set this parameter, VLC will try this dialect "\
67     "for communication. In this mode you cannot connect to normal RTSP servers." )
68
69 #define USER_TEXT N_("RTSP user name")
70 #define USER_LONGTEXT N_("Allows you to modify the user name that will " \
71     "be used for authenticating the connection.")
72 #define PASS_TEXT N_("RTSP password")
73 #define PASS_LONGTEXT N_("Allows you to modify the password that will be " \
74     "used for the connection.")
75
76 vlc_module_begin();
77     set_description( _("RTP/RTSP/SDP demuxer (using Live555)" ) );
78     set_capability( "demux2", 50 );
79     set_shortname( "RTP/RTSP");
80     set_callbacks( Open, Close );
81     add_shortcut( "live" );
82     add_shortcut( "livedotcom" );
83     set_category( CAT_INPUT );
84     set_subcategory( SUBCAT_INPUT_DEMUX );
85
86     add_submodule();
87         set_description( _("RTSP/RTP access and demux") );
88         add_shortcut( "rtsp" );
89         add_shortcut( "sdp" );
90         set_capability( "access_demux", 0 );
91         set_callbacks( Open, Close );
92         add_bool( "rtsp-tcp", 0, NULL,
93                   N_("Use RTP over RTSP (TCP)"),
94                   N_("Use RTP over RTSP (TCP)"), VLC_TRUE );
95         add_integer( "rtp-client-port", -1, NULL,
96                   N_("Client port"),
97                   N_("Port to use for the RTP source of the session"), VLC_TRUE );
98         add_bool( "rtsp-http", 0, NULL,
99                   N_("Tunnel RTSP and RTP over HTTP"),
100                   N_("Tunnel RTSP and RTP over HTTP"), VLC_TRUE );
101         add_integer( "rtsp-http-port", 80, NULL,
102                   N_("HTTP tunnel port"),
103                   N_("Port to use for tunneling the RTSP/RTP over HTTP."),
104                   VLC_TRUE );
105         add_integer("rtsp-caching", 4 * DEFAULT_PTS_DELAY / 1000, NULL,
106                     CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
107         add_bool(   "rtsp-kasenna", VLC_FALSE, NULL, KASENNA_TEXT,
108                     KASENNA_LONGTEXT, VLC_TRUE );
109         add_string( "rtsp-user", NULL, NULL, USER_TEXT,
110                     USER_LONGTEXT, VLC_TRUE );
111         add_string( "rtsp-pwd", NULL, NULL, PASS_TEXT,
112                     PASS_LONGTEXT, VLC_TRUE );
113 vlc_module_end();
114
115
116 /*****************************************************************************
117  * Local prototypes
118  *****************************************************************************/
119
120 typedef struct
121 {
122     demux_t         *p_demux;
123     MediaSubsession *sub;
124
125     es_format_t     fmt;
126     es_out_id_t     *p_es;
127
128     vlc_bool_t      b_muxed;
129     vlc_bool_t      b_quicktime;
130     vlc_bool_t      b_asf;
131     stream_t        *p_out_muxed;    /* for muxed stream */
132
133     uint8_t         *p_buffer;
134     unsigned int    i_buffer;
135
136     vlc_bool_t      b_rtcp_sync;
137     char            waiting;
138     int64_t         i_pts;
139     u_int32_t       i_start_seq;
140
141 } live_track_t;
142
143 struct timeout_thread_t
144 {
145     VLC_COMMON_MEMBERS
146
147     int64_t      i_remain;
148     demux_sys_t  *p_sys;
149 };
150
151 struct demux_sys_t
152 {
153     char            *p_sdp;    /* XXX mallocated */
154     char            *psz_path; /* URL-encoded path */
155
156     MediaSession     *ms;
157     TaskScheduler    *scheduler;
158     UsageEnvironment *env ;
159     RTSPClient       *rtsp;
160
161     /* */
162     int              i_track;
163     live_track_t     **track;   /* XXX mallocated */
164
165     /* Weird formats */
166     asf_header_t     asfh;
167     stream_t         *p_out_asf;
168     vlc_bool_t       b_real;
169
170     /* */
171     int64_t          i_pcr; /* The clock */
172     int64_t          i_npt; /* The current time in the stream */
173     int64_t          i_npt_length;
174     int64_t          i_npt_start;
175
176     /* timeout thread information */
177     int              i_timeout;     /* session timeout value in seconds */
178     vlc_bool_t       b_timeout_call;/* mark to send an RTSP call to prevent server timeout */
179     timeout_thread_t *p_timeout;    /* the actual thread that makes sure we don't timeout */
180
181     /* */
182     vlc_bool_t       b_multicast;   /* true if one of the tracks is multicasted */
183     vlc_bool_t       b_no_data;     /* true if we never receive any data */
184     int              i_no_data_ti;  /* consecutive number of TaskInterrupt */
185
186     char             event;
187 };
188
189 static int Demux  ( demux_t * );
190 static int Control( demux_t *, int, va_list );
191
192 static int Connect      ( demux_t * );
193 static int SessionsSetup( demux_t * );
194 static int Play         ( demux_t *);
195 static int ParseASF     ( demux_t * );
196 static int RollOverTcp  ( demux_t * );
197
198 static void StreamRead  ( void *, unsigned int, unsigned int,
199                           struct timeval, unsigned int );
200 static void StreamClose ( void * );
201 static void TaskInterrupt( void * );
202
203 static void TimeoutPrevention( timeout_thread_t * );
204
205 static unsigned char* parseH264ConfigStr( char const* configStr,
206                                           unsigned int& configSize );
207
208 /*****************************************************************************
209  * DemuxOpen:
210  *****************************************************************************/
211 static int  Open ( vlc_object_t *p_this )
212 {
213     demux_t     *p_demux = (demux_t*)p_this;
214     demux_sys_t *p_sys = NULL;
215
216     MediaSubsessionIterator *iter   = NULL;
217     MediaSubsession         *sub    = NULL;
218     int i, i_return;
219
220     if( p_demux->s )
221     {
222         /* See if it looks like a SDP
223            v, o, s fields are mandatory and in this order */
224         const uint8_t *p_peek;
225         if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
226
227         if( memcmp( p_peek, "v=0\r\n", 5 ) &&
228             memcmp( p_peek, "v=0\n", 4 ) &&
229             ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
230         {
231             return VLC_EGENERIC;
232         }
233     }
234     else
235     {
236         var_Create( p_demux, "rtsp-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
237     }
238
239     p_demux->pf_demux  = Demux;
240     p_demux->pf_control= Control;
241     p_demux->p_sys     = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
242     if( !p_sys ) return VLC_ENOMEM;
243
244     p_sys->p_sdp = NULL;
245     p_sys->scheduler = NULL;
246     p_sys->env = NULL;
247     p_sys->ms = NULL;
248     p_sys->rtsp = NULL;
249     p_sys->i_track = 0;
250     p_sys->track   = NULL;
251     p_sys->i_pcr = 0;
252     p_sys->i_npt = 0;
253     p_sys->i_npt_start = 0;
254     p_sys->i_npt_length = 0;
255     p_sys->p_out_asf = NULL;
256     p_sys->b_no_data = VLC_TRUE;
257     p_sys->i_no_data_ti = 0;
258     p_sys->p_timeout = NULL;
259     p_sys->i_timeout = 0;
260     p_sys->b_timeout_call = VLC_FALSE;
261     p_sys->b_multicast = VLC_FALSE;
262     p_sys->b_real = VLC_FALSE;
263     p_sys->psz_path = strdup( p_demux->psz_path );
264
265     if( ( p_sys->scheduler = BasicTaskScheduler::createNew() ) == NULL )
266     {
267         msg_Err( p_demux, "BasicTaskScheduler::createNew failed" );
268         goto error;
269     }
270     if( !( p_sys->env = BasicUsageEnvironment::createNew(*p_sys->scheduler) ) )
271     {
272         msg_Err( p_demux, "BasicUsageEnvironment::createNew failed" );
273         goto error;
274     }
275
276     if( strcasecmp( p_demux->psz_access, "sdp" ) )
277     {
278         char *p = p_sys->psz_path;
279         while( (p = strchr( p, ' ' )) != NULL ) *p = '+';
280     }
281
282     if( p_demux->s != NULL )
283     {
284         /* Gather the complete sdp file */
285         int     i_sdp       = 0;
286         int     i_sdp_max   = 1000;
287         uint8_t *p_sdp      = (uint8_t*) malloc( i_sdp_max );
288
289         for( ;; )
290         {
291             int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp],
292                                       i_sdp_max - i_sdp - 1 );
293
294             if( i_read < 0 )
295             {
296                 msg_Err( p_demux, "failed to read SDP" );
297                 free( p_sys );
298                 return VLC_EGENERIC;
299             }
300
301             i_sdp += i_read;
302
303             if( i_read < i_sdp_max - i_sdp - 1 )
304             {
305                 p_sdp[i_sdp] = '\0';
306                 break;
307             }
308
309             i_sdp_max += 1000;
310             p_sdp = (uint8_t*)realloc( p_sdp, i_sdp_max );
311         }
312         p_sys->p_sdp = (char*)p_sdp;
313     }
314     else if( p_demux->s == NULL && !strcasecmp( p_demux->psz_access, "sdp" ) )
315     {
316         /* sdp:// link from SAP */
317         p_sys->p_sdp = strdup( p_sys->psz_path );
318     }
319     else if( ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
320     {
321         msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
322         goto error;
323     }
324
325     if( p_sys->p_sdp == NULL )
326     {
327         msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
328         goto error;
329     }
330
331     if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
332     {
333         msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
334         goto error;
335     }
336
337     if( p_sys->b_real ) goto error;
338
339     if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
340         goto error;
341
342     if( p_sys->p_out_asf && ParseASF( p_demux ) )
343     {
344         msg_Err( p_demux, "cannot find a usable asf header" );
345         /* TODO Clean tracks */
346         goto error;
347     }
348
349     if( p_sys->i_track <= 0 )
350         goto error;
351
352     return VLC_SUCCESS;
353
354 error:
355     for( i = 0; i < p_sys->i_track; i++ )
356     {
357         live_track_t *tk = p_sys->track[i];
358
359         if( tk->b_muxed ) stream_DemuxDelete( tk->p_out_muxed );
360         free( tk->p_buffer );
361         free( tk );
362     }
363
364     if( p_sys->i_track ) free( p_sys->track );
365     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
366     if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->teardownMediaSession( *p_sys->ms );
367     if( p_sys->ms ) Medium::close( p_sys->ms );
368     if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
369     if( p_sys->env ) p_sys->env->reclaim();
370     if( p_sys->p_timeout )
371     {
372         vlc_object_kill( p_sys->p_timeout );
373         vlc_thread_join( p_sys->p_timeout );
374         vlc_object_detach( p_sys->p_timeout );
375         vlc_object_destroy( p_sys->p_timeout );
376     }
377     if( p_sys->scheduler ) delete p_sys->scheduler;
378     if( p_sys->p_sdp ) free( p_sys->p_sdp );
379     if( p_sys->psz_path ) free( p_sys->psz_path );
380
381     free( p_sys );
382     return VLC_EGENERIC;
383 }
384
385 /*****************************************************************************
386  * DemuxClose:
387  *****************************************************************************/
388 static void Close( vlc_object_t *p_this )
389 {
390     demux_t *p_demux = (demux_t*)p_this;
391     demux_sys_t *p_sys = p_demux->p_sys;
392     int i;
393
394     for( i = 0; i < p_sys->i_track; i++ )
395     {
396         live_track_t *tk = p_sys->track[i];
397
398         if( tk->b_muxed ) stream_DemuxDelete( tk->p_out_muxed );
399         free( tk->p_buffer );
400         free( tk );
401     }
402
403     if( p_sys->i_track ) free( p_sys->track );
404     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
405     if( p_sys->rtsp && p_sys->ms ) p_sys->rtsp->teardownMediaSession( *p_sys->ms );
406     if( p_sys->ms ) Medium::close( p_sys->ms );
407     if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
408     if( p_sys->env ) p_sys->env->reclaim();
409     if( p_sys->p_timeout )
410     {
411         vlc_object_kill( p_sys->p_timeout );
412         vlc_thread_join( p_sys->p_timeout );
413         vlc_object_detach( p_sys->p_timeout );
414         vlc_object_destroy( p_sys->p_timeout );
415     }
416     if( p_sys->scheduler ) delete p_sys->scheduler;
417     if( p_sys->p_sdp ) free( p_sys->p_sdp );
418     if( p_sys->psz_path ) free( p_sys->psz_path );
419
420     free( p_sys );
421 }
422
423 /*****************************************************************************
424  * Connect: connects to the RTSP server to setup the session DESCRIBE
425  *****************************************************************************/
426 static int Connect( demux_t *p_demux )
427 {
428     demux_sys_t *p_sys = p_demux->p_sys;
429     Authenticator authenticator;
430
431     char *psz_user    = NULL;
432     char *psz_pwd     = NULL;
433     char *psz_url     = NULL;
434     char *psz_options = NULL;
435     char *p_sdp       = NULL;
436     int  i_http_port  = 0;
437     int  i_ret        = VLC_SUCCESS;
438
439 createnew:
440     if( var_CreateGetBool( p_demux, "rtsp-http" ) )
441         i_http_port = var_CreateGetInteger( p_demux, "rtsp-http-port" );
442
443     if( ( p_sys->rtsp = RTSPClient::createNew(*p_sys->env,
444           p_demux->p_libvlc->i_verbose > 1,
445           "VLC media player", i_http_port ) ) == NULL )
446     {
447         msg_Err( p_demux, "RTSPClient::createNew failed (%s)",
448                  p_sys->env->getResultMsg() );
449         return VLC_EGENERIC;
450     }
451     psz_url = (char*)malloc( strlen( p_sys->psz_path ) + 8 );
452     sprintf( psz_url, "rtsp://%s", p_sys->psz_path );
453
454     psz_options = p_sys->rtsp->sendOptionsCmd( psz_url );
455     if( psz_options ) delete [] psz_options;
456
457     psz_user = var_CreateGetString( p_demux, "rtsp-user" );
458     psz_pwd  = var_CreateGetString( p_demux, "rtsp-pwd" );
459
460 describe:
461     authenticator.setUsernameAndPassword( (const char*)psz_user, (const char*)psz_pwd );
462     p_sdp = p_sys->rtsp->describeURL( psz_url,
463                 &authenticator, var_CreateGetBool( p_demux, "rtsp-kasenna" ) );
464
465     if( psz_user ) free( psz_user );
466     if( psz_pwd ) free( psz_pwd );
467
468     if( p_sdp == NULL )
469     {
470         /* failure occurred */
471         int i_code = 0;
472         const char *psz_error = p_sys->env->getResultMsg();
473
474         msg_Dbg( p_demux, "DESCRIBE failed with %d: %s", i_code, psz_error );
475         sscanf( psz_error, "%*sRTSP/%*s%3u", &i_code );
476
477         if( i_code == 401 )
478         {
479             char *psz_login = NULL; char *psz_password = NULL;
480             msg_Dbg( p_demux, "authentication failed" );
481
482             i_ret = intf_UserLoginPassword( p_demux, _("RTSP authentication"),
483                            _("Please enter a valid login name and a password."),
484                                                    &psz_login, &psz_password );
485             if( i_ret == DIALOG_OK_YES )
486             {
487                msg_Dbg( p_demux, "retrying with user=%s, pwd=%s",
488                            psz_login, psz_password );
489                if( psz_login ) psz_user = psz_login;
490                if( psz_password ) psz_pwd = psz_password;
491                goto describe;
492             }
493             if( psz_login ) free( psz_login );
494             if( psz_password ) free( psz_password );
495         }
496         else if( !var_CreateGetBool( p_demux, "rtsp-http" ) )
497         {
498             /* Perhaps a firewall is being annoying. Try HTTP tunneling mode */
499             vlc_value_t val;
500             val.b_bool = VLC_TRUE;
501             msg_Dbg( p_demux, "we will now try HTTP tunneling mode" );
502             var_Set( p_demux, "rtsp-http", val );
503             if( psz_url ) free( psz_url );
504             if( p_sys->rtsp ) RTSPClient::close( p_sys->rtsp );
505             goto createnew;
506         }
507         i_ret = VLC_EGENERIC;
508     }
509     if( psz_url ) free( psz_url );
510
511     /* malloc-ated copy */
512     if( p_sys->p_sdp ) free( p_sys->p_sdp );
513     if( p_sdp ) p_sys->p_sdp = strdup( (char*)p_sdp );
514     delete[] p_sdp;
515
516     return i_ret;
517 }
518
519 /*****************************************************************************
520  * Connect: prepares the subsessions and does the SETUP
521  *****************************************************************************/
522 static int SessionsSetup( demux_t *p_demux )
523 {
524     demux_sys_t             *p_sys  = p_demux->p_sys;
525     MediaSubsessionIterator *iter   = NULL;
526     MediaSubsession         *sub    = NULL;
527
528     vlc_bool_t     b_rtsp_tcp = VLC_FALSE;
529     int            i_client_port;
530     int            i_return = VLC_SUCCESS;
531     unsigned int   i_buffer = 0;
532     unsigned const thresh = 200000; /* RTP reorder threshold .2 second (default .1) */
533
534     b_rtsp_tcp    = var_CreateGetBool( p_demux, "rtsp-tcp" );
535     i_client_port = var_CreateGetInteger( p_demux, "rtp-client-port" );
536
537     /* Create the session from the SDP */
538     if( !( p_sys->ms = MediaSession::createNew( *p_sys->env, p_sys->p_sdp ) ) )
539     {
540         msg_Err( p_demux, "Could not create the RTSP Session: %s",
541             p_sys->env->getResultMsg() );
542         return VLC_EGENERIC;
543     }
544
545     /* Initialise each media subsession */
546     iter = new MediaSubsessionIterator( *p_sys->ms );
547     while( ( sub = iter->next() ) != NULL )
548     {
549         Boolean bInit;
550         live_track_t *tk;
551
552         /* Value taken from mplayer */
553         if( !strcmp( sub->mediumName(), "audio" ) )
554             i_buffer = 100000;
555         else if( !strcmp( sub->mediumName(), "video" ) )
556             i_buffer = 2000000;
557         else continue;
558
559         if( i_client_port != -1 )
560         {
561             sub->setClientPortNum( i_client_port );
562             i_client_port += 2;
563         }
564
565         if( strcasestr( sub->codecName(), "REAL" ) )
566         {
567             msg_Info( p_demux, "real codec detected, using real-RTSP instead" );
568             p_sys->b_real = VLC_TRUE; /* This is a problem, we'll handle it later */
569             continue;
570         }
571
572         if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
573             bInit = sub->initiate( 4 ); /* Constant ? */
574         else
575             bInit = sub->initiate();
576
577         if( !bInit )
578         {
579             msg_Warn( p_demux, "RTP subsession '%s/%s' failed (%s)",
580                       sub->mediumName(), sub->codecName(),
581                       p_sys->env->getResultMsg() );
582         }
583         else
584         {
585             if( sub->rtpSource() != NULL )
586             {
587                 int fd = sub->rtpSource()->RTPgs()->socketNum();
588
589                 /* Increase the buffer size */
590                 if( i_buffer > 0 )
591                     increaseReceiveBufferTo( *p_sys->env, fd, i_buffer );
592
593                 /* Increase the RTP reorder timebuffer just a bit */
594                 sub->rtpSource()->setPacketReorderingThresholdTime(thresh);
595             }
596             msg_Dbg( p_demux, "RTP subsession '%s/%s'", sub->mediumName(),
597                      sub->codecName() );
598
599             /* Issue the SETUP */
600             if( p_sys->rtsp )
601             {
602                 if( !( p_sys->rtsp->setupMediaSubsession( *sub, False,
603                                                    b_rtsp_tcp ? True : False ) ) )
604                 {
605                     /* if we get an unsupported transport error, toggle TCP use and try again */
606                     if( !strstr(p_sys->env->getResultMsg(), "461 Unsupported Transport")
607                      || !( p_sys->rtsp->setupMediaSubsession( *sub, False,
608                                                    b_rtsp_tcp ? False : True ) ) )
609                     {
610                         msg_Err( p_demux, "SETUP of'%s/%s' failed %s", sub->mediumName(),
611                                  sub->codecName(), p_sys->env->getResultMsg() );
612                         continue;
613                     }
614                 }
615             }
616
617             /* Check if we will receive data from this subsession for this track */
618             if( sub->readSource() == NULL ) continue;
619             if( !p_sys->b_multicast )
620             {
621                 /* Check, because we need diff. rollover behaviour for multicast */
622                 p_sys->b_multicast = IsMulticastAddress( sub->connectionEndpointAddress() );
623             }
624
625             tk = (live_track_t*)malloc( sizeof( live_track_t ) );
626             tk->p_demux     = p_demux;
627             tk->sub         = sub;
628             tk->p_es        = NULL;
629             tk->b_quicktime = VLC_FALSE;
630             tk->b_asf       = VLC_FALSE;
631             tk->b_muxed     = VLC_FALSE;
632             tk->p_out_muxed = NULL;
633             tk->waiting     = 0;
634             tk->b_rtcp_sync = VLC_FALSE;
635             tk->i_pts       = 0;
636             tk->i_buffer    = 65536;
637             tk->p_buffer    = (uint8_t *)malloc( 65536 );
638
639             /* Value taken from mplayer */
640             if( !strcmp( sub->mediumName(), "audio" ) )
641             {
642                 es_format_Init( &tk->fmt, AUDIO_ES, VLC_FOURCC('u','n','d','f') );
643                 tk->fmt.audio.i_channels = sub->numChannels();
644                 tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
645
646                 if( !strcmp( sub->codecName(), "MPA" ) ||
647                     !strcmp( sub->codecName(), "MPA-ROBUST" ) ||
648                     !strcmp( sub->codecName(), "X-MP3-DRAFT-00" ) )
649                 {
650                     tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
651                     tk->fmt.audio.i_rate = 0;
652                 }
653                 else if( !strcmp( sub->codecName(), "AC3" ) )
654                 {
655                     tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
656                     tk->fmt.audio.i_rate = 0;
657                 }
658                 else if( !strcmp( sub->codecName(), "L16" ) )
659                 {
660                     tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
661                     tk->fmt.audio.i_bitspersample = 16;
662                 }
663                 else if( !strcmp( sub->codecName(), "L8" ) )
664                 {
665                     tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
666                     tk->fmt.audio.i_bitspersample = 8;
667                 }
668                 else if( !strcmp( sub->codecName(), "PCMU" ) )
669                 {
670                     tk->fmt.i_codec = VLC_FOURCC( 'u', 'l', 'a', 'w' );
671                 }
672                 else if( !strcmp( sub->codecName(), "PCMA" ) )
673                 {
674                     tk->fmt.i_codec = VLC_FOURCC( 'a', 'l', 'a', 'w' );
675                 }
676                 else if( !strncmp( sub->codecName(), "G726", 4 ) )
677                 {
678                     tk->fmt.i_codec = VLC_FOURCC( 'g', '7', '2', '6' );
679                     tk->fmt.audio.i_rate = 8000;
680                     tk->fmt.audio.i_channels = 1;
681                     if( !strcmp( sub->codecName()+5, "40" ) )
682                         tk->fmt.i_bitrate = 40000;
683                     else if( !strcmp( sub->codecName()+5, "32" ) )
684                         tk->fmt.i_bitrate = 32000;
685                     else if( !strcmp( sub->codecName()+5, "24" ) )
686                         tk->fmt.i_bitrate = 24000;
687                     else if( !strcmp( sub->codecName()+5, "16" ) )
688                         tk->fmt.i_bitrate = 16000;
689                 }
690                 else if( !strcmp( sub->codecName(), "AMR" ) )
691                 {
692                     tk->fmt.i_codec = VLC_FOURCC( 's', 'a', 'm', 'r' );
693                 }
694                 else if( !strcmp( sub->codecName(), "AMR-WB" ) )
695                 {
696                     tk->fmt.i_codec = VLC_FOURCC( 's', 'a', 'w', 'b' );
697                 }
698                 else if( !strcmp( sub->codecName(), "MP4A-LATM" ) )
699                 {
700                     unsigned int i_extra;
701                     uint8_t      *p_extra;
702
703                     tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
704
705                     if( ( p_extra = parseStreamMuxConfigStr( sub->fmtp_config(),
706                                                              i_extra ) ) )
707                     {
708                         tk->fmt.i_extra = i_extra;
709                         tk->fmt.p_extra = malloc( i_extra );
710                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
711                         delete[] p_extra;
712                     }
713                     /* Because the "faad" decoder does not handle the LATM data length field
714                        at the start of each returned LATM frame, tell the RTP source to omit it. */
715                     ((MPEG4LATMAudioRTPSource*)sub->rtpSource())->omitLATMDataLengthField();
716                 }
717                 else if( !strcmp( sub->codecName(), "MPEG4-GENERIC" ) )
718                 {
719                     unsigned int i_extra;
720                     uint8_t      *p_extra;
721
722                     tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
723
724                     if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
725                                                            i_extra ) ) )
726                     {
727                         tk->fmt.i_extra = i_extra;
728                         tk->fmt.p_extra = malloc( i_extra );
729                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
730                         delete[] p_extra;
731                     }
732                 }
733                 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
734                 {
735                     tk->b_asf = VLC_TRUE;
736                     if( p_sys->p_out_asf == NULL )
737                         p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
738                                                             p_demux->out );
739                 }
740                 else if( !strcmp( sub->codecName(), "X-QT" ) ||
741                          !strcmp( sub->codecName(), "X-QUICKTIME" ) )
742                 {
743                     tk->b_quicktime = VLC_TRUE;
744                 }
745                 else if( !strcmp( sub->codecName(), "SPEEX" ) )
746                 {
747                     tk->fmt.i_codec = VLC_FOURCC( 's', 'p', 'x', 'r' );
748                     if ( sub->rtpTimestampFrequency() )
749                         tk->fmt.audio.i_rate = sub->rtpTimestampFrequency();
750                     else
751                     {
752                         msg_Warn( p_demux,"Using 8kHz as default sample rate." );
753                         tk->fmt.audio.i_rate = 8000;
754                     }
755                 }
756             }
757             else if( !strcmp( sub->mediumName(), "video" ) )
758             {
759                 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
760                 if( !strcmp( sub->codecName(), "MPV" ) )
761                 {
762                     tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
763                 }
764                 else if( !strcmp( sub->codecName(), "H263" ) ||
765                          !strcmp( sub->codecName(), "H263-1998" ) ||
766                          !strcmp( sub->codecName(), "H263-2000" ) )
767                 {
768                     tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '3' );
769                 }
770                 else if( !strcmp( sub->codecName(), "H261" ) )
771                 {
772                     tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '1' );
773                 }
774                 else if( !strcmp( sub->codecName(), "H264" ) )
775                 {
776                     unsigned int i_extra = 0;
777                     uint8_t      *p_extra = NULL;
778
779                     tk->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '4' );
780                     tk->fmt.b_packetized = VLC_FALSE;
781
782                     if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
783                                                     i_extra ) ) )
784                     {
785                         tk->fmt.i_extra = i_extra;
786                         tk->fmt.p_extra = malloc( i_extra );
787                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
788
789                         delete[] p_extra;
790                     }
791                 }
792                 else if( !strcmp( sub->codecName(), "JPEG" ) )
793                 {
794                     tk->fmt.i_codec = VLC_FOURCC( 'M', 'J', 'P', 'G' );
795                 }
796                 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
797                 {
798                     unsigned int i_extra;
799                     uint8_t      *p_extra;
800
801                     tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
802
803                     if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
804                                                            i_extra ) ) )
805                     {
806                         tk->fmt.i_extra = i_extra;
807                         tk->fmt.p_extra = malloc( i_extra );
808                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
809                         delete[] p_extra;
810                     }
811                 }
812                 else if( !strcmp( sub->codecName(), "X-QT" ) ||
813                          !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
814                          !strcmp( sub->codecName(), "X-QDM" ) ||
815                          !strcmp( sub->codecName(), "X-SV3V-ES" )  ||
816                          !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
817                 {
818                     tk->b_quicktime = VLC_TRUE;
819                 }
820                 else if( !strcmp( sub->codecName(), "MP2T" ) )
821                 {
822                     tk->b_muxed = VLC_TRUE;
823                     tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
824                 }
825                 else if( !strcmp( sub->codecName(), "MP2P" ) ||
826                          !strcmp( sub->codecName(), "MP1S" ) )
827                 {
828                     tk->b_muxed = VLC_TRUE;
829                     tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
830                                                        p_demux->out );
831                 }
832                 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
833                 {
834                     tk->b_asf = VLC_TRUE;
835                     if( p_sys->p_out_asf == NULL )
836                         p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
837                                                             p_demux->out );;
838                 }
839             }
840
841             if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
842             {
843                 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
844             }
845
846             if( sub->rtcpInstance() != NULL )
847             {
848                 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
849             }
850
851             if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
852             {
853                 /* Append */
854                 p_sys->track = (live_track_t**)realloc( p_sys->track, sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
855                 p_sys->track[p_sys->i_track++] = tk;
856             }
857             else
858             {
859                 /* BUG ??? */
860                 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
861                 free( tk );
862             }
863         }
864     }
865     delete iter;
866     if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
867
868 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
869     /* Retrieve the starttime if possible */
870     p_sys->i_npt_start = (int64_t)( p_sys->ms->playStartTime() * (double)1000000.0 );
871 #else
872     p_sys->i_npt_start = (int64_t) -1;
873 #endif
874     if( p_sys->i_npt_start < 0 )
875         p_sys->i_npt_start = -1;
876
877 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
878     /* Retrieve the duration if possible */
879     p_sys->i_npt_length = (int64_t)( p_sys->ms->playEndTime() * (double)1000000.0 );
880 #else
881     p_sys->i_npt_length = (int64_t) -1;
882 #endif
883     if( p_sys->i_npt_length < 0 )
884         p_sys->i_npt_length = -1;
885
886     msg_Dbg( p_demux, "setup start: %lld stop:%lld", p_sys->i_npt_start, p_sys->i_npt_length );
887     return i_return;
888 }
889
890 /*****************************************************************************
891  * Play: starts the actual playback of the stream
892  *****************************************************************************/
893 static int Play( demux_t *p_demux )
894 {
895     demux_sys_t *p_sys = p_demux->p_sys;
896     int i;
897
898     if( p_sys->rtsp )
899     {
900         /* The PLAY */
901         if( !p_sys->rtsp->playMediaSession( *p_sys->ms, p_sys->i_npt_start, -1, 1 ) )
902         {
903             msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
904             return VLC_EGENERIC;
905         }
906
907         /* Retrieve the timeout value and set up a timeout prevention thread */
908         p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
909         if( p_sys->i_timeout <= 0 )
910             p_sys->i_timeout = 60; /* default value from RFC2326 */
911         if( !p_sys->p_timeout )
912         {
913             msg_Dbg( p_demux, "We have a timeout of %d seconds",  p_sys->i_timeout );
914             p_sys->p_timeout = (timeout_thread_t *)vlc_object_create( p_demux, sizeof(timeout_thread_t) );
915             p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
916             if( vlc_thread_create( p_sys->p_timeout, "liveMedia-timeout", TimeoutPrevention,
917                                    VLC_THREAD_PRIORITY_LOW, VLC_TRUE ) )
918             {
919                 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
920                 vlc_object_destroy( p_sys->p_timeout );
921             }
922             msg_Dbg( p_demux, "spawned timeout thread" );
923             vlc_object_attach( p_sys->p_timeout, p_demux );
924         }
925     }
926     p_sys->i_pcr = 0;
927
928 #if 0
929     /* TODO */
930     for( i = 0; i < p_sys->i_track; i++ )
931     {
932         //p_sys->track[i]->i_pts = 0;
933         p_sys->track[i]->i_start_seq = (int)p_sys->track[i]->sub->rtpInfo.seqNum;
934         msg_Dbg( p_demux, "set startseq: %u", p_sys->track[i]->i_start_seq );
935     }
936 #endif
937
938 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
939     /* Retrieve the starttime if possible */
940     p_sys->i_npt_start = (int64_t)( p_sys->ms->playStartTime() * (double)1000000.0 );
941 #else
942     p_sys->i_npt_start = -1;
943 #endif
944     if( p_sys->i_npt_start < 0 )
945     {
946         p_sys->i_npt_start = -1;
947         p_sys->i_npt = 0;
948     }
949     else
950         p_sys->i_npt = p_sys->i_npt_start;
951
952 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
953     /* Retrieve the duration if possible */
954     p_sys->i_npt_length = (int64_t)( p_sys->ms->playEndTime() * (double)1000000.0 );
955 #else
956     p_sys->i_npt_length = -1;
957 #endif
958     if( p_sys->i_npt_length < 0 )
959         p_sys->i_npt_length = -1;
960
961     msg_Dbg( p_demux, "play start: %lld stop:%lld", p_sys->i_npt_start, p_sys->i_npt_length );
962     return VLC_SUCCESS;
963 }
964
965
966 /*****************************************************************************
967  * Demux:
968  *****************************************************************************/
969 static int Demux( demux_t *p_demux )
970 {
971     demux_sys_t    *p_sys = p_demux->p_sys;
972     TaskToken      task;
973
974     vlc_bool_t      b_send_pcr = VLC_TRUE;
975     int64_t         i_pcr = 0;
976     int             i;
977
978     /* Check if we need to send the server a Keep-A-Live signal */
979     if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
980     {
981         char *psz_bye = NULL;
982         p_sys->rtsp->getMediaSessionParameter( *p_sys->ms, NULL, psz_bye );
983         p_sys->b_timeout_call = VLC_FALSE;
984     }
985
986
987     for( i = 0; i < p_sys->i_track; i++ )
988     {
989         live_track_t *tk = p_sys->track[i];
990
991         if( tk->b_asf || tk->b_muxed )
992             b_send_pcr = VLC_FALSE;
993 #if 0
994         if( i_pcr == 0 )
995         {
996             i_pcr = tk->i_pts;
997         }
998         else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
999         {
1000             i_pcr = tk->i_pts ;
1001         }
1002 #endif
1003     }
1004     if( p_sys->i_pcr > 0 )
1005     {
1006         if( b_send_pcr )
1007             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
1008     }
1009
1010     /* First warn we want to read data */
1011     p_sys->event = 0;
1012     for( i = 0; i < p_sys->i_track; i++ )
1013     {
1014         live_track_t *tk = p_sys->track[i];
1015
1016         if( tk->waiting == 0 )
1017         {
1018             tk->waiting = 1;
1019             tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1020                                           StreamRead, tk, StreamClose, tk );
1021         }
1022     }
1023     /* Create a task that will be called if we wait more than 300ms */
1024     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
1025
1026     /* Do the read */
1027     p_sys->scheduler->doEventLoop( &p_sys->event );
1028
1029     /* remove the task */
1030     p_sys->scheduler->unscheduleDelayedTask( task );
1031
1032     /* Check for gap in pts value */
1033     for( i = 0; i < p_sys->i_track; i++ )
1034     {
1035         live_track_t *tk = p_sys->track[i];
1036
1037         if( !tk->b_muxed && !tk->b_rtcp_sync &&
1038             tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1039         {
1040             msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1041
1042             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1043             tk->b_rtcp_sync = VLC_TRUE;
1044             /* reset PCR */
1045             tk->i_pts = 0;
1046             p_sys->i_pcr = 0;
1047             i_pcr = 0;
1048         }
1049     }
1050
1051     if( p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 120 )
1052     {
1053         /* FIXME Make this configurable
1054         msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1055         return 0;
1056         */
1057     }
1058     else if( !p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 34 )
1059     {
1060         vlc_bool_t b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" );
1061
1062         if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1063         {
1064             msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1065             if( RollOverTcp( p_demux ) )
1066             {
1067                 msg_Err( p_demux, "TCP rollover failed, aborting" );
1068                 return 0;
1069             }
1070         }
1071         else if( p_sys->i_no_data_ti > 34 )
1072         {
1073             msg_Err( p_demux, "no data received in 10s, aborting" );
1074             return 0;
1075         }
1076     }
1077     else if( !p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 34 )
1078     {
1079         /* EOF ? */
1080         msg_Warn( p_demux, "no data received in 10s, eof ?" );
1081         return 0;
1082     }
1083     return p_demux->b_error ? 0 : 1;
1084 }
1085
1086 /*****************************************************************************
1087  * Control:
1088  *****************************************************************************/
1089 static int Control( demux_t *p_demux, int i_query, va_list args )
1090 {
1091     demux_sys_t *p_sys = p_demux->p_sys;
1092     int64_t *pi64;
1093     double  *pf, f;
1094     vlc_bool_t *pb, b_bool;
1095
1096     switch( i_query )
1097     {
1098         case DEMUX_GET_TIME:
1099             pi64 = (int64_t*)va_arg( args, int64_t * );
1100             if( p_sys->i_npt > 0 )
1101             {
1102                 *pi64 = p_sys->i_npt;
1103                 return VLC_SUCCESS;
1104             }
1105             return VLC_EGENERIC;
1106
1107         case DEMUX_GET_LENGTH:
1108             pi64 = (int64_t*)va_arg( args, int64_t * );
1109             if( p_sys->i_npt_length > 0 )
1110             {
1111                 *pi64 = p_sys->i_npt_length;
1112                 return VLC_SUCCESS;
1113             }
1114             return VLC_EGENERIC;
1115
1116         case DEMUX_GET_POSITION:
1117             pf = (double*)va_arg( args, double* );
1118             if( p_sys->i_npt_length > 0 && p_sys->i_npt > 0 )
1119             {
1120                 *pf = (double)p_sys->i_npt / (double)p_sys->i_npt_length;
1121                 return VLC_SUCCESS;
1122             }
1123             return VLC_EGENERIC;
1124
1125         case DEMUX_SET_POSITION:
1126         {
1127             float time;
1128
1129             f = (double)va_arg( args, double );
1130             if( p_sys->rtsp && p_sys->i_npt_length > 0 )
1131             {
1132                 int i;
1133                 time = f * (double)p_sys->i_npt_length / 1000000.0;   /* in second */
1134                 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, time, -1, 1 ) )
1135                 {
1136                     msg_Err( p_demux, "PLAY failed %s",
1137                         p_sys->env->getResultMsg() );
1138                     return VLC_EGENERIC;
1139                 }
1140                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1141                 p_sys->i_pcr = 0;
1142 #if 0
1143                 /* Retrieve RTP-Info values */
1144                 for( i = 0; i < p_sys->i_track; i++ )
1145                 {
1146                     //p_sys->track[i]->i_pts = 0;
1147                     p_sys->track[i]->i_start_seq = p_sys->track[i]->sub->rtpInfo.seqNum;
1148                     msg_Dbg( p_demux, "set pos startseq: %u", p_sys->track[i]->i_start_seq );
1149                 }
1150 #endif
1151 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
1152                 /* Retrieve the starttime if possible */
1153                 p_sys->i_npt_start = (int64_t)( p_sys->ms->playStartTime() * (double)1000000.0 );
1154 #else
1155                 p_sys->i_npt_start = -1;
1156 #endif
1157                 if( p_sys->i_npt_start < 0 )
1158                 {
1159                     p_sys->i_npt_start = -1;
1160                     p_sys->i_npt = 0;
1161                 }
1162                 else
1163                     p_sys->i_npt = p_sys->i_npt_start;
1164
1165 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
1166                 /* Retrieve the duration if possible */
1167                 p_sys->i_npt_length = (int64_t)( p_sys->ms->playEndTime() * (double)1000000.0 );
1168 #else
1169                 p_sys->i_npt_length = -1;
1170 #endif
1171                 if( p_sys->i_npt_length < 0 )
1172                     p_sys->i_npt_length = -1;
1173
1174                 msg_Dbg( p_demux, "seek start: %lld stop:%lld", p_sys->i_npt_start, p_sys->i_npt_length );
1175                 return VLC_SUCCESS;
1176             }
1177             return VLC_EGENERIC;
1178         }
1179         /* Special for access_demux */
1180         case DEMUX_CAN_PAUSE:
1181             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1182             if( p_sys->rtsp && p_sys->i_npt_length )
1183                 /* Not always true, but will be handled in SET_PAUSE_STATE */
1184                 *pb = VLC_TRUE;
1185             else
1186                 *pb = VLC_FALSE;
1187             return VLC_SUCCESS;
1188
1189         case DEMUX_CAN_CONTROL_PACE:
1190             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1191
1192 #if 1       /* Disable for now until we have a clock synchro algo
1193              * which works with something else than MPEG over UDP */
1194             *pb = VLC_FALSE;
1195 #else
1196             *pb = VLC_TRUE;
1197 #endif
1198             return VLC_SUCCESS;
1199
1200         case DEMUX_SET_PAUSE_STATE:
1201         {
1202             double d_npt = (double) p_sys->i_npt / I64C(1000000);
1203             int i;
1204
1205             b_bool = (vlc_bool_t)va_arg( args, vlc_bool_t );
1206             if( p_sys->rtsp == NULL )
1207                 return VLC_EGENERIC;
1208
1209             /* FIXME */
1210             if( ( b_bool && !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) ) ||
1211                     ( !b_bool && !p_sys->rtsp->playMediaSession( *p_sys->ms,
1212                       d_npt > 0 ? d_npt : -1 ) ) )
1213             {
1214                     msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1215                     return VLC_EGENERIC;
1216             }
1217             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1218             p_sys->i_pcr = 0;
1219 #if 0
1220             for( i = 0; i < p_sys->i_track; i++ )
1221             {
1222                 //p_sys->track[i]->i_pts = 0;
1223                 p_sys->track[i]->i_start_seq = p_sys->track[i]->sub->rtpInfo.seqNum;
1224                 msg_Dbg( p_demux, "set pause startseq: %u", p_sys->track[i]->i_start_seq );
1225             }
1226 #endif
1227 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
1228             /* Retrieve the starttime if possible */
1229             p_sys->i_npt_start = (int64_t)( p_sys->ms->playStartTime() * (double)1000000.0 );
1230 #else
1231             p_sys->i_npt_start = -1;
1232 #endif
1233             if( p_sys->i_npt_start < 0 )
1234             {
1235                 p_sys->i_npt_start = -1;
1236                 p_sys->i_npt = 0;
1237             }
1238             else
1239                 p_sys->i_npt = p_sys->i_npt_start;
1240
1241 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
1242             /* Retrieve the duration if possible */
1243             p_sys->i_npt_length = (int64_t)( p_sys->ms->playEndTime() * (double)1000000.0 );
1244 #else
1245             p_sys->i_npt_length = -1;
1246 #endif
1247             if( p_sys->i_npt_length < 0 )
1248                 p_sys->i_npt_length = -1;
1249
1250             msg_Dbg( p_demux, "pause start: %lld stop:%lld", p_sys->i_npt_start, p_sys->i_npt_length );
1251             return VLC_SUCCESS;
1252         }
1253         case DEMUX_GET_TITLE_INFO:
1254         case DEMUX_SET_TITLE:
1255         case DEMUX_SET_SEEKPOINT:
1256             return VLC_EGENERIC;
1257
1258         case DEMUX_GET_PTS_DELAY:
1259             pi64 = (int64_t*)va_arg( args, int64_t * );
1260             *pi64 = (int64_t)var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1261             return VLC_SUCCESS;
1262
1263         default:
1264             return VLC_EGENERIC;
1265     }
1266 }
1267
1268 /*****************************************************************************
1269  * RollOverTcp: reopen the rtsp into TCP mode
1270  * XXX: ugly, a lot of code are duplicated from Open()
1271  * This should REALLY be fixed
1272  *****************************************************************************/
1273 static int RollOverTcp( demux_t *p_demux )
1274 {
1275     demux_sys_t *p_sys = p_demux->p_sys;
1276     int i, i_return;
1277
1278     var_SetBool( p_demux, "rtsp-tcp", VLC_TRUE );
1279
1280     /* We close the old RTSP session */
1281     for( i = 0; i < p_sys->i_track; i++ )
1282     {
1283         live_track_t *tk = p_sys->track[i];
1284
1285         if( tk->b_muxed ) stream_DemuxDelete( tk->p_out_muxed );
1286         free( tk->p_buffer );
1287         free( tk );
1288     }
1289     if( p_sys->i_track ) free( p_sys->track );
1290     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
1291
1292     p_sys->rtsp->teardownMediaSession( *p_sys->ms );
1293     Medium::close( p_sys->ms );
1294     RTSPClient::close( p_sys->rtsp );
1295
1296     p_sys->ms = NULL;
1297     p_sys->rtsp = NULL;
1298     p_sys->track = NULL;
1299     p_sys->i_track = 0;
1300
1301     /* Reopen rtsp client */
1302     if( p_demux->s != NULL && ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1303     {
1304         msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
1305         goto error;
1306     }
1307
1308     if( p_sys->p_sdp == NULL )
1309     {
1310         msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1311         goto error;
1312     }
1313
1314     if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1315     {
1316         msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1317         goto error;
1318     }
1319
1320     if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1321         goto error;
1322
1323     return VLC_SUCCESS;
1324
1325 error:
1326     return VLC_EGENERIC;
1327 }
1328
1329
1330 /*****************************************************************************
1331  *
1332  *****************************************************************************/
1333 static void StreamRead( void *p_private, unsigned int i_size,
1334                         unsigned int i_truncated_bytes, struct timeval pts,
1335                         unsigned int duration )
1336 {
1337     live_track_t   *tk = (live_track_t*)p_private;
1338     demux_t        *p_demux = tk->p_demux;
1339     demux_sys_t    *p_sys = p_demux->p_sys;
1340     block_t        *p_block;
1341
1342     //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1343
1344     int64_t i_pts = (uint64_t)pts.tv_sec * UI64C(1000000) +
1345         (uint64_t)pts.tv_usec;
1346
1347     /* XXX Beurk beurk beurk Avoid having negative value XXX */
1348     i_pts &= UI64C(0x00ffffffffffffff);
1349
1350     if( tk->b_quicktime && tk->p_es == NULL )
1351     {
1352         QuickTimeGenericRTPSource *qtRTPSource =
1353             (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1354         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1355         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1356
1357         if( tk->fmt.i_cat == VIDEO_ES ) {
1358             if( qtState.sdAtomSize < 16 + 32 )
1359             {
1360                 /* invalid */
1361                 p_sys->event = 0xff;
1362                 tk->waiting = 0;
1363                 return;
1364             }
1365             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1366             tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
1367             tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1368
1369             if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1370             {
1371                 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1372                 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1373                                   + qtRTPSource->qtState.sdAtomSize;
1374                 while (pos+8 < endpos) {
1375                     unsigned atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1376                     if( atomLength == 0 || atomLength > endpos-pos) break;
1377                     if( memcmp(pos+4, "avcC", 4) == 0 &&
1378                         atomLength > 8 &&
1379                         atomLength <= INT_MAX )
1380                     {
1381                         tk->fmt.i_extra = atomLength-8;
1382                         tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1383                         memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1384                         break;
1385                     }
1386                     pos += atomLength;
1387                 }
1388             }
1389             else
1390             {
1391                 tk->fmt.i_extra        = qtState.sdAtomSize - 16;
1392                 tk->fmt.p_extra        = malloc( tk->fmt.i_extra );
1393                 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1394             }
1395         }
1396         else {
1397             if( qtState.sdAtomSize < 4 )
1398             {
1399                 /* invalid */
1400                 p_sys->event = 0xff;
1401                 tk->waiting = 0;
1402                 return;
1403             }
1404             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1405         }
1406         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1407     }
1408
1409 #if 0
1410     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1411              i_size,
1412              pts.tv_sec * 1000000LL + pts.tv_usec );
1413 #endif
1414
1415     /* grow buffer if it looks like buffer is too small, but don't eat
1416      * up all the memory on strange streams */
1417     if( i_truncated_bytes > 0 && tk->i_buffer < 2000000 )
1418     {
1419         void *p_tmp;
1420         msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1421         msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1422         tk->i_buffer *= 2;
1423         p_tmp = realloc( tk->p_buffer, tk->i_buffer );
1424         if( p_tmp == NULL )
1425         {
1426             msg_Warn( p_demux, "realloc failed" );
1427         }
1428         else
1429         {
1430             tk->p_buffer = (uint8_t*)p_tmp;
1431         }
1432     }
1433     if( i_size > tk->i_buffer )
1434     {
1435         msg_Warn( p_demux, "buffer overflow" );
1436     }
1437     /* FIXME could i_size be > buffer size ? */
1438     if( tk->fmt.i_codec == VLC_FOURCC('s','a','m','r') ||
1439         tk->fmt.i_codec == VLC_FOURCC('s','a','w','b') )
1440     {
1441         AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1442
1443         p_block = block_New( p_demux, i_size + 1 );
1444         p_block->p_buffer[0] = amrSource->lastFrameHeader();
1445         memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1446     }
1447     else if( tk->fmt.i_codec == VLC_FOURCC('H','2','6','1') )
1448     {
1449 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1081468800
1450         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1451         uint32_t header = h261Source->lastSpecialHeader();
1452 #else
1453         uint32_t header = 0;
1454         msg_Warn( p_demux, "need livemedia library >= \"2004.04.09\"" );
1455 #endif
1456         p_block = block_New( p_demux, i_size + 4 );
1457         memcpy( p_block->p_buffer, &header, 4 );
1458         memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1459
1460         if( tk->sub->rtpSource()->curPacketMarkerBit() )
1461             p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1462     }
1463     else if( tk->fmt.i_codec == VLC_FOURCC('h','2','6','4') )
1464     {
1465         if( (tk->p_buffer[0] & 0x1f) >= 24 )
1466             msg_Warn( p_demux, "unsupported NAL type for H264" );
1467
1468         /* Normal NAL type */
1469         p_block = block_New( p_demux, i_size + 4 );
1470         p_block->p_buffer[0] = 0x00;
1471         p_block->p_buffer[1] = 0x00;
1472         p_block->p_buffer[2] = 0x00;
1473         p_block->p_buffer[3] = 0x01;
1474         memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1475     }
1476     else if( tk->b_asf )
1477     {
1478         int i_copy = __MIN( p_sys->asfh.i_min_data_packet_size, (int)i_size );
1479         p_block = block_New( p_demux, p_sys->asfh.i_min_data_packet_size );
1480
1481         memcpy( p_block->p_buffer, tk->p_buffer, i_copy );
1482     }
1483     else
1484     {
1485         p_block = block_New( p_demux, i_size );
1486         memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1487     }
1488
1489     /* Update NPT */
1490     //msg_Dbg( p_demux, "current %d, start_seq %u", (int)tk->sub->rtpSource()->curPacketRTPSeqNum(), tk->i_start_seq );
1491     if( (tk->fmt.i_cat == VIDEO_ES) && (p_sys->i_pcr < i_pts) &&
1492         (i_pts > 0) && (p_sys->i_pcr > 0) )
1493     {
1494         p_sys->i_npt += __MAX( 0, i_pts - p_sys->i_pcr );
1495         p_sys->i_pcr = i_pts;
1496         //msg_Dbg( p_demux, "npt update" );
1497     }
1498     else if( /*tk->fmt.i_cat == VIDEO_ES &&*/ p_sys->i_pcr < i_pts )
1499     {
1500         p_sys->i_pcr = i_pts;
1501     }
1502     //msg_Dbg( p_demux, "npt %lld", p_sys->i_npt );
1503
1504     if( (i_pts != tk->i_pts) && (!tk->b_muxed) )
1505     {
1506         p_block->i_dts = ( tk->fmt.i_cat == VIDEO_ES ) ? 0 : i_pts;
1507         p_block->i_pts = i_pts;
1508     }
1509
1510     if( tk->b_muxed )
1511     {
1512         stream_DemuxSend( tk->p_out_muxed, p_block );
1513     }
1514     else if( tk->b_asf )
1515     {
1516         stream_DemuxSend( p_sys->p_out_asf, p_block );
1517     }
1518     else
1519     {
1520         es_out_Send( p_demux->out, tk->p_es, p_block );
1521     }
1522
1523     /* warn that's ok */
1524     p_sys->event = 0xff;
1525
1526     /* we have read data */
1527     tk->waiting = 0;
1528     p_demux->p_sys->b_no_data = VLC_FALSE;
1529     p_demux->p_sys->i_no_data_ti = 0;
1530
1531     if( i_pts > 0 && !tk->b_muxed )
1532     {
1533         tk->i_pts = i_pts;
1534     }
1535 }
1536
1537 /*****************************************************************************
1538  *
1539  *****************************************************************************/
1540 static void StreamClose( void *p_private )
1541 {
1542     live_track_t   *tk = (live_track_t*)p_private;
1543     demux_t        *p_demux = tk->p_demux;
1544     demux_sys_t    *p_sys = p_demux->p_sys;
1545
1546     msg_Dbg( p_demux, "StreamClose" );
1547
1548     p_sys->event = 0xff;
1549     p_demux->b_error = VLC_TRUE;
1550 }
1551
1552
1553 /*****************************************************************************
1554  *
1555  *****************************************************************************/
1556 static void TaskInterrupt( void *p_private )
1557 {
1558     demux_t *p_demux = (demux_t*)p_private;
1559
1560     p_demux->p_sys->i_no_data_ti++;
1561
1562     /* Avoid lock */
1563     p_demux->p_sys->event = 0xff;
1564 }
1565
1566 /*****************************************************************************
1567  *
1568  *****************************************************************************/
1569 static void TimeoutPrevention( timeout_thread_t *p_timeout )
1570 {
1571     p_timeout->b_die = VLC_FALSE;
1572     p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1573     p_timeout->i_remain *= 1000000;
1574
1575     vlc_thread_ready( p_timeout );
1576
1577     /* Avoid lock */
1578     while( !p_timeout->b_die )
1579     {
1580         if( p_timeout->i_remain <= 0 )
1581         {
1582             p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1583             p_timeout->i_remain *= 1000000;
1584             p_timeout->p_sys->b_timeout_call = VLC_TRUE;
1585             msg_Dbg( p_timeout, "reset the timeout timer" );
1586         }
1587         p_timeout->i_remain -= 200000;
1588         msleep( 200000 ); /* 200 ms */
1589     }
1590 }
1591
1592 /*****************************************************************************
1593  *
1594  *****************************************************************************/
1595 static int b64_decode( char *dest, char *src );
1596
1597 static int ParseASF( demux_t *p_demux )
1598 {
1599     demux_sys_t    *p_sys = p_demux->p_sys;
1600
1601     const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1602     char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1603     char *psz_end;
1604     block_t *p_header;
1605
1606     /* Parse the asf header */
1607     if( psz_asf == NULL )
1608         return VLC_EGENERIC;
1609
1610     psz_asf += strlen( psz_marker );
1611     psz_asf = strdup( psz_asf );    /* Duplicate it */
1612     psz_end = strchr( psz_asf, '\n' );
1613
1614     while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1615         *psz_end-- = '\0';
1616
1617     if( psz_asf >= psz_end )
1618     {
1619         free( psz_asf );
1620         return VLC_EGENERIC;
1621     }
1622
1623     /* Always smaller */
1624     p_header = block_New( p_demux, psz_end - psz_asf );
1625     p_header->i_buffer = b64_decode( (char*)p_header->p_buffer, psz_asf );
1626     //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
1627     if( p_header->i_buffer <= 0 )
1628     {
1629         free( psz_asf );
1630         return VLC_EGENERIC;
1631     }
1632
1633     /* Parse it to get packet size */
1634     E_(asf_HeaderParse)( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
1635
1636     /* Send it to demuxer */
1637     stream_DemuxSend( p_sys->p_out_asf, p_header );
1638
1639     free( psz_asf );
1640     return VLC_SUCCESS;
1641 }
1642
1643
1644 static unsigned char* parseH264ConfigStr( char const* configStr,
1645                                           unsigned int& configSize )
1646 {
1647     char *dup, *psz;
1648     int i, i_records = 1;
1649
1650     if( configSize )
1651     configSize = 0;
1652
1653     if( configStr == NULL || *configStr == '\0' )
1654         return NULL;
1655
1656     psz = dup = strdup( configStr );
1657
1658     /* Count the number of comma's */
1659     for( psz = dup; *psz != '\0'; ++psz )
1660     {
1661         if( *psz == ',')
1662         {
1663             ++i_records;
1664             *psz = '\0';
1665         }
1666     }
1667
1668     unsigned char *cfg = new unsigned char[5 * strlen(dup)];
1669     psz = dup;
1670     for( i = 0; i < i_records; i++ )
1671     {
1672         cfg[configSize++] = 0x00;
1673         cfg[configSize++] = 0x00;
1674         cfg[configSize++] = 0x00;
1675         cfg[configSize++] = 0x01;
1676
1677         configSize += b64_decode( (char*)&cfg[configSize], psz );
1678         psz += strlen(psz)+1;
1679     }
1680
1681     if( dup ) free( dup );
1682     return cfg;
1683 }
1684
1685 /*char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";*/
1686 static int b64_decode( char *dest, char *src )
1687 {
1688     const char *dest_start = dest;
1689     int  i_level;
1690     int  last = 0;
1691     int  b64[256] = {
1692         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
1693         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
1694         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
1695         52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
1696         -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
1697         15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
1698         -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
1699         41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
1700         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
1701         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
1702         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
1703         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
1704         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
1705         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
1706         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
1707         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
1708         };
1709
1710     for( i_level = 0; *src != '\0'; src++ )
1711     {
1712         int  c;
1713
1714         c = b64[(unsigned int)*src];
1715         if( c == -1 )
1716         {
1717             continue;
1718         }
1719
1720         switch( i_level )
1721         {
1722             case 0:
1723                 i_level++;
1724                 break;
1725             case 1:
1726                 *dest++ = ( last << 2 ) | ( ( c >> 4)&0x03 );
1727                 i_level++;
1728                 break;
1729             case 2:
1730                 *dest++ = ( ( last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
1731                 i_level++;
1732                 break;
1733             case 3:
1734                 *dest++ = ( ( last &0x03 ) << 6 ) | c;
1735                 i_level = 0;
1736         }
1737         last = c;
1738     }
1739
1740     *dest = '\0';
1741
1742     return dest - dest_start;
1743 }