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