]> git.sesse.net Git - vlc/blob - modules/demux/live555.cpp
Remove stdlib.h
[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 #include <string.h>
32
33 #include <vlc_demux.h>
34 #include <vlc_interface.h>
35 #include <vlc_network.h>
36
37 #include <iostream>
38
39 #if defined( WIN32 )
40 #   include <winsock2.h>
41 #endif
42
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', ' ' );
748                 }
749             }
750             else if( !strcmp( sub->mediumName(), "video" ) )
751             {
752                 es_format_Init( &tk->fmt, VIDEO_ES, VLC_FOURCC('u','n','d','f') );
753                 if( !strcmp( sub->codecName(), "MPV" ) )
754                 {
755                     tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
756                 }
757                 else if( !strcmp( sub->codecName(), "H263" ) ||
758                          !strcmp( sub->codecName(), "H263-1998" ) ||
759                          !strcmp( sub->codecName(), "H263-2000" ) )
760                 {
761                     tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '3' );
762                 }
763                 else if( !strcmp( sub->codecName(), "H261" ) )
764                 {
765                     tk->fmt.i_codec = VLC_FOURCC( 'H', '2', '6', '1' );
766                 }
767                 else if( !strcmp( sub->codecName(), "H264" ) )
768                 {
769                     unsigned int i_extra = 0;
770                     uint8_t      *p_extra = NULL;
771
772                     tk->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '4' );
773                     tk->fmt.b_packetized = VLC_FALSE;
774
775                     if((p_extra=parseH264ConfigStr( sub->fmtp_spropparametersets(),
776                                                     i_extra ) ) )
777                     {
778                         tk->fmt.i_extra = i_extra;
779                         tk->fmt.p_extra = malloc( i_extra );
780                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
781
782                         delete[] p_extra;
783                     }
784                 }
785                 else if( !strcmp( sub->codecName(), "JPEG" ) )
786                 {
787                     tk->fmt.i_codec = VLC_FOURCC( 'M', 'J', 'P', 'G' );
788                 }
789                 else if( !strcmp( sub->codecName(), "MP4V-ES" ) )
790                 {
791                     unsigned int i_extra;
792                     uint8_t      *p_extra;
793
794                     tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
795
796                     if( ( p_extra = parseGeneralConfigStr( sub->fmtp_config(),
797                                                            i_extra ) ) )
798                     {
799                         tk->fmt.i_extra = i_extra;
800                         tk->fmt.p_extra = malloc( i_extra );
801                         memcpy( tk->fmt.p_extra, p_extra, i_extra );
802                         delete[] p_extra;
803                     }
804                 }
805                 else if( !strcmp( sub->codecName(), "X-QT" ) ||
806                          !strcmp( sub->codecName(), "X-QUICKTIME" ) ||
807                          !strcmp( sub->codecName(), "X-QDM" ) ||
808                          !strcmp( sub->codecName(), "X-SV3V-ES" )  ||
809                          !strcmp( sub->codecName(), "X-SORENSONVIDEO" ) )
810                 {
811                     tk->b_quicktime = VLC_TRUE;
812                 }
813                 else if( !strcmp( sub->codecName(), "MP2T" ) )
814                 {
815                     tk->b_muxed = VLC_TRUE;
816                     tk->p_out_muxed = stream_DemuxNew( p_demux, "ts", p_demux->out );
817                 }
818                 else if( !strcmp( sub->codecName(), "MP2P" ) ||
819                          !strcmp( sub->codecName(), "MP1S" ) )
820                 {
821                     tk->b_muxed = VLC_TRUE;
822                     tk->p_out_muxed = stream_DemuxNew( p_demux, "ps",
823                                                        p_demux->out );
824                 }
825                 else if( !strcmp( sub->codecName(), "X-ASF-PF" ) )
826                 {
827                     tk->b_asf = VLC_TRUE;
828                     if( p_sys->p_out_asf == NULL )
829                         p_sys->p_out_asf = stream_DemuxNew( p_demux, "asf",
830                                                             p_demux->out );;
831                 }
832             }
833
834             if( !tk->b_quicktime && !tk->b_muxed && !tk->b_asf )
835             {
836                 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
837             }
838
839             if( sub->rtcpInstance() != NULL )
840             {
841                 sub->rtcpInstance()->setByeHandler( StreamClose, tk );
842             }
843
844             if( tk->p_es || tk->b_quicktime || tk->b_muxed || tk->b_asf )
845             {
846                 /* Append */
847                 p_sys->track = (live_track_t**)realloc( p_sys->track, sizeof( live_track_t ) * ( p_sys->i_track + 1 ) );
848                 p_sys->track[p_sys->i_track++] = tk;
849             }
850             else
851             {
852                 /* BUG ??? */
853                 msg_Err( p_demux, "unusable RTSP track. this should not happen" );
854                 free( tk );
855             }
856         }
857     }
858     delete iter;
859     if( p_sys->i_track <= 0 ) i_return = VLC_EGENERIC;
860
861 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
862     /* Retrieve the starttime if possible */
863     p_sys->i_npt_start = (int64_t)( p_sys->ms->playStartTime() * (double)1000000.0 );
864 #else
865     p_sys->i_npt_start = (int64_t) -1;
866 #endif
867     if( p_sys->i_npt_start < 0 )
868         p_sys->i_npt_start = -1;
869
870 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
871     /* Retrieve the duration if possible */
872     p_sys->i_npt_length = (int64_t)( p_sys->ms->playEndTime() * (double)1000000.0 );
873 #else
874     p_sys->i_npt_length = (int64_t) -1;
875 #endif
876     if( p_sys->i_npt_length < 0 )
877         p_sys->i_npt_length = -1;
878
879     msg_Dbg( p_demux, "setup start: %lld stop:%lld", p_sys->i_npt_start, p_sys->i_npt_length );
880     return i_return;
881 }
882
883 /*****************************************************************************
884  * Play: starts the actual playback of the stream
885  *****************************************************************************/
886 static int Play( demux_t *p_demux )
887 {
888     demux_sys_t *p_sys = p_demux->p_sys;
889     int i;
890
891     if( p_sys->rtsp )
892     {
893         /* The PLAY */
894         if( !p_sys->rtsp->playMediaSession( *p_sys->ms, p_sys->i_npt_start, -1, 1 ) )
895         {
896             msg_Err( p_demux, "RTSP PLAY failed %s", p_sys->env->getResultMsg() );
897             return VLC_EGENERIC;
898         }
899
900         /* Retrieve the timeout value and set up a timeout prevention thread */
901         p_sys->i_timeout = p_sys->rtsp->sessionTimeoutParameter();
902         if( p_sys->i_timeout > 0 && !p_sys->p_timeout )
903         {
904             msg_Dbg( p_demux, "We have a timeout of %d seconds",  p_sys->i_timeout );
905             p_sys->p_timeout = (timeout_thread_t *)vlc_object_create( p_demux, sizeof(timeout_thread_t) );
906             p_sys->p_timeout->p_sys = p_demux->p_sys; /* lol, object recursion :D */
907             if( vlc_thread_create( p_sys->p_timeout, "liveMedia-timeout", TimeoutPrevention,
908                                    VLC_THREAD_PRIORITY_LOW, VLC_TRUE ) )
909             {
910                 msg_Err( p_demux, "cannot spawn liveMedia timeout thread" );
911                 vlc_object_destroy( p_sys->p_timeout );
912             }
913             msg_Dbg( p_demux, "spawned timeout thread" );
914             vlc_object_attach( p_sys->p_timeout, p_demux );
915         }
916     }
917     p_sys->i_pcr = 0;
918
919 #if 0
920     /* TODO */
921     for( i = 0; i < p_sys->i_track; i++ )
922     {
923         //p_sys->track[i]->i_pts = 0;
924         p_sys->track[i]->i_start_seq = (int)p_sys->track[i]->sub->rtpInfo.seqNum;
925         msg_Dbg( p_demux, "set startseq: %u", p_sys->track[i]->i_start_seq );
926     }
927 #endif
928
929 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
930     /* Retrieve the starttime if possible */
931     p_sys->i_npt_start = (int64_t)( p_sys->ms->playStartTime() * (double)1000000.0 );
932 #else
933     p_sys->i_npt_start = -1;
934 #endif
935     if( p_sys->i_npt_start < 0 )
936     {
937         p_sys->i_npt_start = -1;
938         p_sys->i_npt = 0;
939     }
940     else
941         p_sys->i_npt = p_sys->i_npt_start;
942
943 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
944     /* Retrieve the duration if possible */
945     p_sys->i_npt_length = (int64_t)( p_sys->ms->playEndTime() * (double)1000000.0 );
946 #else
947     p_sys->i_npt_length = -1;
948 #endif
949     if( p_sys->i_npt_length < 0 )
950         p_sys->i_npt_length = -1;
951
952     msg_Dbg( p_demux, "play start: %lld stop:%lld", p_sys->i_npt_start, p_sys->i_npt_length );
953     return VLC_SUCCESS;
954 }
955
956
957 /*****************************************************************************
958  * Demux:
959  *****************************************************************************/
960 static int Demux( demux_t *p_demux )
961 {
962     demux_sys_t    *p_sys = p_demux->p_sys;
963     TaskToken      task;
964
965     vlc_bool_t      b_send_pcr = VLC_TRUE;
966     int64_t         i_pcr = 0;
967     int             i;
968
969     /* Check if we need to send the server a Keep-A-Live signal */
970     if( p_sys->b_timeout_call && p_sys->rtsp && p_sys->ms )
971     {
972         char *psz_bye = NULL;
973         p_sys->rtsp->getMediaSessionParameter( *p_sys->ms, NULL, psz_bye );
974         p_sys->b_timeout_call = VLC_FALSE;
975     }
976
977
978     for( i = 0; i < p_sys->i_track; i++ )
979     {
980         live_track_t *tk = p_sys->track[i];
981
982         if( tk->b_asf || tk->b_muxed )
983             b_send_pcr = VLC_FALSE;
984 #if 0
985         if( i_pcr == 0 )
986         {
987             i_pcr = tk->i_pts;
988         }
989         else if( tk->i_pts != 0 && i_pcr > tk->i_pts )
990         {
991             i_pcr = tk->i_pts ;
992         }
993 #endif
994     }
995     if( p_sys->i_pcr > 0 )
996     {
997         if( b_send_pcr )
998             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
999     }
1000
1001     /* First warn we want to read data */
1002     p_sys->event = 0;
1003     for( i = 0; i < p_sys->i_track; i++ )
1004     {
1005         live_track_t *tk = p_sys->track[i];
1006
1007         if( tk->waiting == 0 )
1008         {
1009             tk->waiting = 1;
1010             tk->sub->readSource()->getNextFrame( tk->p_buffer, tk->i_buffer,
1011                                           StreamRead, tk, StreamClose, tk );
1012         }
1013     }
1014     /* Create a task that will be called if we wait more than 300ms */
1015     task = p_sys->scheduler->scheduleDelayedTask( 300000, TaskInterrupt, p_demux );
1016
1017     /* Do the read */
1018     p_sys->scheduler->doEventLoop( &p_sys->event );
1019
1020     /* remove the task */
1021     p_sys->scheduler->unscheduleDelayedTask( task );
1022
1023     /* Check for gap in pts value */
1024     for( i = 0; i < p_sys->i_track; i++ )
1025     {
1026         live_track_t *tk = p_sys->track[i];
1027
1028         if( !tk->b_muxed && !tk->b_rtcp_sync &&
1029             tk->sub->rtpSource() && tk->sub->rtpSource()->hasBeenSynchronizedUsingRTCP() )
1030         {
1031             msg_Dbg( p_demux, "tk->rtpSource->hasBeenSynchronizedUsingRTCP()" );
1032
1033             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1034             tk->b_rtcp_sync = VLC_TRUE;
1035 #if 0
1036             /* reset PCR */
1037             tk->i_pts = 0;
1038             p_sys->i_pcr = 0;
1039             i_pcr = 0;
1040 #endif
1041         }
1042     }
1043
1044     if( p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 120 )
1045     {
1046         /* FIXME Make this configurable
1047         msg_Err( p_demux, "no multicast data received in 36s, aborting" );
1048         return 0;
1049         */
1050     }
1051     else if( !p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 34 )
1052     {
1053         vlc_bool_t b_rtsp_tcp = var_GetBool( p_demux, "rtsp-tcp" );
1054
1055         if( !b_rtsp_tcp && p_sys->rtsp && p_sys->ms )
1056         {
1057             msg_Warn( p_demux, "no data received in 10s. Switching to TCP" );
1058             if( RollOverTcp( p_demux ) )
1059             {
1060                 msg_Err( p_demux, "TCP rollover failed, aborting" );
1061                 return 0;
1062             }
1063         }
1064         else if( p_sys->i_no_data_ti > 34 )
1065         {
1066             msg_Err( p_demux, "no data received in 10s, aborting" );
1067             return 0;
1068         }
1069     }
1070     else if( !p_sys->b_multicast && p_sys->b_no_data && p_sys->i_no_data_ti > 34 )
1071     {
1072         /* EOF ? */
1073         msg_Warn( p_demux, "no data received in 10s, eof ?" );
1074         return 0;
1075     }
1076     return p_demux->b_error ? 0 : 1;
1077 }
1078
1079 /*****************************************************************************
1080  * Control:
1081  *****************************************************************************/
1082 static int Control( demux_t *p_demux, int i_query, va_list args )
1083 {
1084     demux_sys_t *p_sys = p_demux->p_sys;
1085     int64_t *pi64;
1086     double  *pf, f;
1087     vlc_bool_t *pb, b_bool;
1088
1089     switch( i_query )
1090     {
1091         case DEMUX_GET_TIME:
1092             pi64 = (int64_t*)va_arg( args, int64_t * );
1093             if( p_sys->i_npt > 0 )
1094             {
1095                 *pi64 = p_sys->i_npt;
1096                 return VLC_SUCCESS;
1097             }
1098             return VLC_EGENERIC;
1099
1100         case DEMUX_GET_LENGTH:
1101             pi64 = (int64_t*)va_arg( args, int64_t * );
1102             if( p_sys->i_npt_length > 0 )
1103             {
1104                 *pi64 = p_sys->i_npt_length;
1105                 return VLC_SUCCESS;
1106             }
1107             return VLC_EGENERIC;
1108
1109         case DEMUX_GET_POSITION:
1110             pf = (double*)va_arg( args, double* );
1111             if( p_sys->i_npt_length > 0 && p_sys->i_npt > 0 )
1112             {
1113                 *pf = (double)p_sys->i_npt / (double)p_sys->i_npt_length;
1114                 return VLC_SUCCESS;
1115             }
1116             return VLC_EGENERIC;
1117
1118         case DEMUX_SET_POSITION:
1119         {
1120             float time;
1121
1122             f = (double)va_arg( args, double );
1123             if( p_sys->rtsp && p_sys->i_npt_length > 0 )
1124             {
1125                 int i;
1126                 time = f * (double)p_sys->i_npt_length / 1000000.0;   /* in second */
1127                 if( !p_sys->rtsp->playMediaSession( *p_sys->ms, time, -1, 1 ) )
1128                 {
1129                     msg_Err( p_demux, "PLAY failed %s",
1130                         p_sys->env->getResultMsg() );
1131                     return VLC_EGENERIC;
1132                 }
1133                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1134                 p_sys->i_pcr = 0;
1135 #if 0
1136                 /* Retrieve RTP-Info values */
1137                 for( i = 0; i < p_sys->i_track; i++ )
1138                 {
1139                     //p_sys->track[i]->i_pts = 0;
1140                     p_sys->track[i]->i_start_seq = p_sys->track[i]->sub->rtpInfo.seqNum;
1141                     msg_Dbg( p_demux, "set pos startseq: %u", p_sys->track[i]->i_start_seq );
1142                 }
1143 #endif
1144 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
1145                 /* Retrieve the starttime if possible */
1146                 p_sys->i_npt_start = (int64_t)( p_sys->ms->playStartTime() * (double)1000000.0 );
1147 #else
1148                 p_sys->i_npt_start = -1;
1149 #endif
1150                 if( p_sys->i_npt_start < 0 )
1151                 {
1152                     p_sys->i_npt_start = -1;
1153                     p_sys->i_npt = 0;
1154                 }
1155                 else
1156                     p_sys->i_npt = p_sys->i_npt_start;
1157
1158 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
1159                 /* Retrieve the duration if possible */
1160                 p_sys->i_npt_length = (int64_t)( p_sys->ms->playEndTime() * (double)1000000.0 );
1161 #else
1162                 p_sys->i_npt_length = -1;
1163 #endif
1164                 if( p_sys->i_npt_length < 0 )
1165                     p_sys->i_npt_length = -1;
1166
1167                 msg_Dbg( p_demux, "seek start: %lld stop:%lld", p_sys->i_npt_start, p_sys->i_npt_length );
1168                 return VLC_SUCCESS;
1169             }
1170             return VLC_EGENERIC;
1171         }
1172         /* Special for access_demux */
1173         case DEMUX_CAN_PAUSE:
1174             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1175             if( p_sys->rtsp && p_sys->i_npt_length )
1176                 /* Not always true, but will be handled in SET_PAUSE_STATE */
1177                 *pb = VLC_TRUE;
1178             else
1179                 *pb = VLC_FALSE;
1180             return VLC_SUCCESS;
1181
1182         case DEMUX_CAN_CONTROL_PACE:
1183             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1184
1185 #if 1       /* Disable for now until we have a clock synchro algo
1186              * which works with something else than MPEG over UDP */
1187             *pb = VLC_FALSE;
1188 #else
1189             *pb = VLC_TRUE;
1190 #endif
1191             return VLC_SUCCESS;
1192
1193         case DEMUX_SET_PAUSE_STATE:
1194         {
1195             double d_npt = (double) p_sys->i_npt / I64C(1000000);
1196             int i;
1197
1198             b_bool = (vlc_bool_t)va_arg( args, vlc_bool_t );
1199             if( p_sys->rtsp == NULL )
1200                 return VLC_EGENERIC;
1201
1202             /* FIXME */
1203             if( ( b_bool && !p_sys->rtsp->pauseMediaSession( *p_sys->ms ) ) ||
1204                     ( !b_bool && !p_sys->rtsp->playMediaSession( *p_sys->ms,
1205                       d_npt > 0 ? d_npt : -1 ) ) )
1206             {
1207                     msg_Err( p_demux, "PLAY or PAUSE failed %s", p_sys->env->getResultMsg() );
1208                     return VLC_EGENERIC;
1209             }
1210             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1211             p_sys->i_pcr = 0;
1212 #if 0
1213             for( i = 0; i < p_sys->i_track; i++ )
1214             {
1215                 //p_sys->track[i]->i_pts = 0;
1216                 p_sys->track[i]->i_start_seq = p_sys->track[i]->sub->rtpInfo.seqNum;
1217                 msg_Dbg( p_demux, "set pause startseq: %u", p_sys->track[i]->i_start_seq );
1218             }
1219 #endif
1220 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
1221             /* Retrieve the starttime if possible */
1222             p_sys->i_npt_start = (int64_t)( p_sys->ms->playStartTime() * (double)1000000.0 );
1223 #else
1224             p_sys->i_npt_start = -1;
1225 #endif
1226             if( p_sys->i_npt_start < 0 )
1227             {
1228                 p_sys->i_npt_start = -1;
1229                 p_sys->i_npt = 0;
1230             }
1231             else
1232                 p_sys->i_npt = p_sys->i_npt_start;
1233
1234 #if (LIVEMEDIA_LIBRARY_VERSION_INT >= 9999999999)
1235             /* Retrieve the duration if possible */
1236             p_sys->i_npt_length = (int64_t)( p_sys->ms->playEndTime() * (double)1000000.0 );
1237 #else
1238             p_sys->i_npt_length = -1;
1239 #endif
1240             if( p_sys->i_npt_length < 0 )
1241                 p_sys->i_npt_length = -1;
1242
1243             msg_Dbg( p_demux, "pause start: %lld stop:%lld", p_sys->i_npt_start, p_sys->i_npt_length );
1244             return VLC_SUCCESS;
1245         }
1246         case DEMUX_GET_TITLE_INFO:
1247         case DEMUX_SET_TITLE:
1248         case DEMUX_SET_SEEKPOINT:
1249             return VLC_EGENERIC;
1250
1251         case DEMUX_GET_PTS_DELAY:
1252             pi64 = (int64_t*)va_arg( args, int64_t * );
1253             *pi64 = (int64_t)var_GetInteger( p_demux, "rtsp-caching" ) * 1000;
1254             return VLC_SUCCESS;
1255
1256         default:
1257             return VLC_EGENERIC;
1258     }
1259 }
1260
1261 /*****************************************************************************
1262  * RollOverTcp: reopen the rtsp into TCP mode
1263  * XXX: ugly, a lot of code are duplicated from Open()
1264  * This should REALLY be fixed
1265  *****************************************************************************/
1266 static int RollOverTcp( demux_t *p_demux )
1267 {
1268     demux_sys_t *p_sys = p_demux->p_sys;
1269     int i, i_return;
1270
1271     var_SetBool( p_demux, "rtsp-tcp", VLC_TRUE );
1272
1273     /* We close the old RTSP session */
1274     for( i = 0; i < p_sys->i_track; i++ )
1275     {
1276         live_track_t *tk = p_sys->track[i];
1277
1278         if( tk->b_muxed ) stream_DemuxDelete( tk->p_out_muxed );
1279         free( tk->p_buffer );
1280         free( tk );
1281     }
1282     if( p_sys->i_track ) free( p_sys->track );
1283     if( p_sys->p_out_asf ) stream_DemuxDelete( p_sys->p_out_asf );
1284
1285     p_sys->rtsp->teardownMediaSession( *p_sys->ms );
1286     Medium::close( p_sys->ms );
1287     RTSPClient::close( p_sys->rtsp );
1288
1289     p_sys->ms = NULL;
1290     p_sys->rtsp = NULL;
1291     p_sys->track = NULL;
1292     p_sys->i_track = 0;
1293
1294     /* Reopen rtsp client */
1295     if( p_demux->s != NULL && ( i_return = Connect( p_demux ) ) != VLC_SUCCESS )
1296     {
1297         msg_Err( p_demux, "Failed to connect with rtsp://%s", p_sys->psz_path );
1298         goto error;
1299     }
1300
1301     if( p_sys->p_sdp == NULL )
1302     {
1303         msg_Err( p_demux, "Failed to retrieve the RTSP Session Description" );
1304         goto error;
1305     }
1306
1307     if( ( i_return = SessionsSetup( p_demux ) ) != VLC_SUCCESS )
1308     {
1309         msg_Err( p_demux, "Nothing to play for rtsp://%s", p_sys->psz_path );
1310         goto error;
1311     }
1312
1313     if( ( i_return = Play( p_demux ) ) != VLC_SUCCESS )
1314         goto error;
1315
1316     return VLC_SUCCESS;
1317
1318 error:
1319     return VLC_EGENERIC;
1320 }
1321
1322
1323 /*****************************************************************************
1324  *
1325  *****************************************************************************/
1326 static void StreamRead( void *p_private, unsigned int i_size,
1327                         unsigned int i_truncated_bytes, struct timeval pts,
1328                         unsigned int duration )
1329 {
1330     live_track_t   *tk = (live_track_t*)p_private;
1331     demux_t        *p_demux = tk->p_demux;
1332     demux_sys_t    *p_sys = p_demux->p_sys;
1333     block_t        *p_block;
1334
1335     //msg_Dbg( p_demux, "pts: %d", pts.tv_sec );
1336
1337     int64_t i_pts = (uint64_t)pts.tv_sec * UI64C(1000000) +
1338         (uint64_t)pts.tv_usec;
1339
1340     /* XXX Beurk beurk beurk Avoid having negative value XXX */
1341     i_pts &= UI64C(0x00ffffffffffffff);
1342
1343     if( tk->b_quicktime && tk->p_es == NULL )
1344     {
1345         QuickTimeGenericRTPSource *qtRTPSource =
1346             (QuickTimeGenericRTPSource*)tk->sub->rtpSource();
1347         QuickTimeGenericRTPSource::QTState &qtState = qtRTPSource->qtState;
1348         uint8_t *sdAtom = (uint8_t*)&qtState.sdAtom[4];
1349
1350         if( tk->fmt.i_cat == VIDEO_ES ) {
1351             if( qtState.sdAtomSize < 16 + 32 )
1352             {
1353                 /* invalid */
1354                 p_sys->event = 0xff;
1355                 tk->waiting = 0;
1356                 return;
1357             }
1358             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1359             tk->fmt.video.i_width  = (sdAtom[28] << 8) | sdAtom[29];
1360             tk->fmt.video.i_height = (sdAtom[30] << 8) | sdAtom[31];
1361
1362             if( tk->fmt.i_codec == VLC_FOURCC('a', 'v', 'c', '1') )
1363             {
1364                 uint8_t *pos = (uint8_t*)qtRTPSource->qtState.sdAtom + 86;
1365                 uint8_t *endpos = (uint8_t*)qtRTPSource->qtState.sdAtom
1366                                   + qtRTPSource->qtState.sdAtomSize;
1367                 while (pos+8 < endpos) {
1368                     unsigned atomLength = pos[0]<<24 | pos[1]<<16 | pos[2]<<8 | pos[3];
1369                     if( atomLength == 0 || atomLength > endpos-pos) break;
1370                     if( memcmp(pos+4, "avcC", 4) == 0 &&
1371                         atomLength > 8 &&
1372                         atomLength <= INT_MAX )
1373                     {
1374                         tk->fmt.i_extra = atomLength-8;
1375                         tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1376                         memcpy(tk->fmt.p_extra, pos+8, atomLength-8);
1377                         break;
1378                     }
1379                     pos += atomLength;
1380                 }
1381             }
1382             else
1383             {
1384                 tk->fmt.i_extra        = qtState.sdAtomSize - 16;
1385                 tk->fmt.p_extra        = malloc( tk->fmt.i_extra );
1386                 memcpy( tk->fmt.p_extra, &sdAtom[12], tk->fmt.i_extra );
1387             }
1388         }
1389         else {
1390             if( qtState.sdAtomSize < 4 )
1391             {
1392                 /* invalid */
1393                 p_sys->event = 0xff;
1394                 tk->waiting = 0;
1395                 return;
1396             }
1397             tk->fmt.i_codec = VLC_FOURCC(sdAtom[0],sdAtom[1],sdAtom[2],sdAtom[3]);
1398         }
1399         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
1400     }
1401
1402 #if 0
1403     fprintf( stderr, "StreamRead size=%d pts=%lld\n",
1404              i_size,
1405              pts.tv_sec * 1000000LL + pts.tv_usec );
1406 #endif
1407
1408     /* grow buffer if it looks like buffer is too small, but don't eat
1409      * up all the memory on strange streams */
1410     if( i_truncated_bytes > 0 && tk->i_buffer < 2000000 )
1411     {
1412         void *p_tmp;
1413         msg_Dbg( p_demux, "lost %d bytes", i_truncated_bytes );
1414         msg_Dbg( p_demux, "increasing buffer size to %d", tk->i_buffer * 2 );
1415         tk->i_buffer *= 2;
1416         p_tmp = realloc( tk->p_buffer, tk->i_buffer );
1417         if( p_tmp == NULL )
1418         {
1419             msg_Warn( p_demux, "realloc failed" );
1420         }
1421         else
1422         {
1423             tk->p_buffer = (uint8_t*)p_tmp;
1424         }
1425     }
1426     if( i_size > tk->i_buffer )
1427     {
1428         msg_Warn( p_demux, "buffer overflow" );
1429     }
1430     /* FIXME could i_size be > buffer size ? */
1431     if( tk->fmt.i_codec == VLC_FOURCC('s','a','m','r') ||
1432         tk->fmt.i_codec == VLC_FOURCC('s','a','w','b') )
1433     {
1434         AMRAudioSource *amrSource = (AMRAudioSource*)tk->sub->readSource();
1435
1436         p_block = block_New( p_demux, i_size + 1 );
1437         p_block->p_buffer[0] = amrSource->lastFrameHeader();
1438         memcpy( p_block->p_buffer + 1, tk->p_buffer, i_size );
1439     }
1440     else if( tk->fmt.i_codec == VLC_FOURCC('H','2','6','1') )
1441     {
1442 #if LIVEMEDIA_LIBRARY_VERSION_INT >= 1081468800
1443         H261VideoRTPSource *h261Source = (H261VideoRTPSource*)tk->sub->rtpSource();
1444         uint32_t header = h261Source->lastSpecialHeader();
1445 #else
1446         uint32_t header = 0;
1447         msg_Warn( p_demux, "need livemedia library >= \"2004.04.09\"" );
1448 #endif
1449         p_block = block_New( p_demux, i_size + 4 );
1450         memcpy( p_block->p_buffer, &header, 4 );
1451         memcpy( p_block->p_buffer + 4, tk->p_buffer, i_size );
1452
1453         if( tk->sub->rtpSource()->curPacketMarkerBit() )
1454             p_block->i_flags |= BLOCK_FLAG_END_OF_FRAME;
1455     }
1456     else if( tk->fmt.i_codec == VLC_FOURCC('h','2','6','4') )
1457     {
1458         if( (tk->p_buffer[0] & 0x1f) >= 24 )
1459             msg_Warn( p_demux, "unsupported NAL type for H264" );
1460
1461         /* Normal NAL type */
1462         p_block = block_New( p_demux, i_size + 4 );
1463         p_block->p_buffer[0] = 0x00;
1464         p_block->p_buffer[1] = 0x00;
1465         p_block->p_buffer[2] = 0x00;
1466         p_block->p_buffer[3] = 0x01;
1467         memcpy( &p_block->p_buffer[4], tk->p_buffer, i_size );
1468     }
1469     else if( tk->b_asf )
1470     {
1471         int i_copy = __MIN( p_sys->asfh.i_min_data_packet_size, (int)i_size );
1472         p_block = block_New( p_demux, p_sys->asfh.i_min_data_packet_size );
1473
1474         memcpy( p_block->p_buffer, tk->p_buffer, i_copy );
1475     }
1476     else
1477     {
1478         p_block = block_New( p_demux, i_size );
1479         memcpy( p_block->p_buffer, tk->p_buffer, i_size );
1480     }
1481
1482     /* Update NPT */
1483     //msg_Dbg( p_demux, "current %d, start_seq %u", (int)tk->sub->rtpSource()->curPacketRTPSeqNum(), tk->i_start_seq );
1484     if( (tk->fmt.i_cat == VIDEO_ES) && (p_sys->i_pcr < i_pts) &&
1485         (i_pts > 0) && (p_sys->i_pcr > 0) )
1486     {
1487         p_sys->i_npt += __MAX( 0, i_pts - p_sys->i_pcr );
1488         p_sys->i_pcr = i_pts;
1489         //msg_Dbg( p_demux, "npt update" );
1490     }
1491     else if( /*tk->fmt.i_cat == VIDEO_ES &&*/ p_sys->i_pcr < i_pts )
1492     {
1493         p_sys->i_pcr = i_pts;
1494     }
1495     //msg_Dbg( p_demux, "npt %lld", p_sys->i_npt );
1496
1497     if( (i_pts != tk->i_pts) && (!tk->b_muxed) )
1498     {
1499         p_block->i_dts = ( tk->fmt.i_cat == VIDEO_ES ) ? 0 : i_pts;
1500         p_block->i_pts = i_pts;
1501     }
1502
1503     if( tk->b_muxed )
1504     {
1505         stream_DemuxSend( tk->p_out_muxed, p_block );
1506     }
1507     else if( tk->b_asf )
1508     {
1509         stream_DemuxSend( p_sys->p_out_asf, p_block );
1510     }
1511     else
1512     {
1513         es_out_Send( p_demux->out, tk->p_es, p_block );
1514     }
1515
1516     /* warn that's ok */
1517     p_sys->event = 0xff;
1518
1519     /* we have read data */
1520     tk->waiting = 0;
1521     p_demux->p_sys->b_no_data = VLC_FALSE;
1522     p_demux->p_sys->i_no_data_ti = 0;
1523
1524     if( i_pts > 0 && !tk->b_muxed )
1525     {
1526         tk->i_pts = i_pts;
1527     }
1528 }
1529
1530 /*****************************************************************************
1531  *
1532  *****************************************************************************/
1533 static void StreamClose( void *p_private )
1534 {
1535     live_track_t   *tk = (live_track_t*)p_private;
1536     demux_t        *p_demux = tk->p_demux;
1537     demux_sys_t    *p_sys = p_demux->p_sys;
1538
1539     msg_Dbg( p_demux, "StreamClose" );
1540
1541     p_sys->event = 0xff;
1542     p_demux->b_error = VLC_TRUE;
1543 }
1544
1545
1546 /*****************************************************************************
1547  *
1548  *****************************************************************************/
1549 static void TaskInterrupt( void *p_private )
1550 {
1551     demux_t *p_demux = (demux_t*)p_private;
1552
1553     p_demux->p_sys->i_no_data_ti++;
1554
1555     /* Avoid lock */
1556     p_demux->p_sys->event = 0xff;
1557 }
1558
1559 /*****************************************************************************
1560  *  
1561  *****************************************************************************/
1562 static void TimeoutPrevention( timeout_thread_t *p_timeout )
1563 {
1564     p_timeout->b_die = VLC_FALSE;
1565     p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1566     p_timeout->i_remain *= 1000000;
1567
1568     vlc_thread_ready( p_timeout );
1569
1570     /* Avoid lock */
1571     while( !p_timeout->b_die )
1572     {
1573         if( p_timeout->i_remain <= 0 )
1574         {
1575             p_timeout->i_remain = (int64_t)p_timeout->p_sys->i_timeout -2;
1576             p_timeout->i_remain *= 1000000;
1577             p_timeout->p_sys->b_timeout_call = VLC_TRUE;
1578             msg_Dbg( p_timeout, "reset the timeout timer" );
1579         }
1580         p_timeout->i_remain -= 200000;
1581         msleep( 200000 ); /* 200 ms */
1582     }
1583 }
1584
1585 /*****************************************************************************
1586  *
1587  *****************************************************************************/
1588 static int b64_decode( char *dest, char *src );
1589
1590 static int ParseASF( demux_t *p_demux )
1591 {
1592     demux_sys_t    *p_sys = p_demux->p_sys;
1593
1594     const char *psz_marker = "a=pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,";
1595     char *psz_asf = strcasestr( p_sys->p_sdp, psz_marker );
1596     char *psz_end;
1597     block_t *p_header;
1598
1599     /* Parse the asf header */
1600     if( psz_asf == NULL )
1601         return VLC_EGENERIC;
1602
1603     psz_asf += strlen( psz_marker );
1604     psz_asf = strdup( psz_asf );    /* Duplicate it */
1605     psz_end = strchr( psz_asf, '\n' );
1606
1607     while( psz_end > psz_asf && ( *psz_end == '\n' || *psz_end == '\r' ) )
1608         *psz_end-- = '\0';
1609
1610     if( psz_asf >= psz_end )
1611     {
1612         free( psz_asf );
1613         return VLC_EGENERIC;
1614     }
1615
1616     /* Always smaller */
1617     p_header = block_New( p_demux, psz_end - psz_asf );
1618     p_header->i_buffer = b64_decode( (char*)p_header->p_buffer, psz_asf );
1619     //msg_Dbg( p_demux, "Size=%d Hdrb64=%s", p_header->i_buffer, psz_asf );
1620     if( p_header->i_buffer <= 0 )
1621     {
1622         free( psz_asf );
1623         return VLC_EGENERIC;
1624     }
1625
1626     /* Parse it to get packet size */
1627     E_(asf_HeaderParse)( &p_sys->asfh, p_header->p_buffer, p_header->i_buffer );
1628
1629     /* Send it to demuxer */
1630     stream_DemuxSend( p_sys->p_out_asf, p_header );
1631
1632     free( psz_asf );
1633     return VLC_SUCCESS;
1634 }
1635
1636
1637 static unsigned char* parseH264ConfigStr( char const* configStr,
1638                                           unsigned int& configSize )
1639 {
1640     char *dup, *psz;
1641     int i, i_records = 1;
1642
1643     if( configSize )
1644     configSize = 0;
1645
1646     if( configStr == NULL || *configStr == '\0' )
1647         return NULL;
1648
1649     psz = dup = strdup( configStr );
1650
1651     /* Count the number of comma's */
1652     for( psz = dup; *psz != '\0'; ++psz )
1653     {
1654         if( *psz == ',')
1655         {
1656             ++i_records;
1657             *psz = '\0';
1658         }
1659     }
1660
1661     unsigned char *cfg = new unsigned char[5 * strlen(dup)];
1662     psz = dup;
1663     for( i = 0; i < i_records; i++ )
1664     {
1665         cfg[configSize++] = 0x00;
1666         cfg[configSize++] = 0x00;
1667         cfg[configSize++] = 0x00;
1668         cfg[configSize++] = 0x01;
1669
1670         configSize += b64_decode( (char*)&cfg[configSize], psz );
1671         psz += strlen(psz)+1;
1672     }
1673
1674     if( dup ) free( dup );
1675     return cfg;
1676 }
1677
1678 /*char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";*/
1679 static int b64_decode( char *dest, char *src )
1680 {
1681     const char *dest_start = dest;
1682     int  i_level;
1683     int  last = 0;
1684     int  b64[256] = {
1685         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
1686         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
1687         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
1688         52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
1689         -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
1690         15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
1691         -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
1692         41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
1693         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
1694         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
1695         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
1696         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
1697         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
1698         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
1699         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
1700         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
1701         };
1702
1703     for( i_level = 0; *src != '\0'; src++ )
1704     {
1705         int  c;
1706
1707         c = b64[(unsigned int)*src];
1708         if( c == -1 )
1709         {
1710             continue;
1711         }
1712
1713         switch( i_level )
1714         {
1715             case 0:
1716                 i_level++;
1717                 break;
1718             case 1:
1719                 *dest++ = ( last << 2 ) | ( ( c >> 4)&0x03 );
1720                 i_level++;
1721                 break;
1722             case 2:
1723                 *dest++ = ( ( last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
1724                 i_level++;
1725                 break;
1726             case 3:
1727                 *dest++ = ( ( last &0x03 ) << 6 ) | c;
1728                 i_level = 0;
1729         }
1730         last = c;
1731     }
1732
1733     *dest = '\0';
1734
1735     return dest - dest_start;
1736 }