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