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