]> git.sesse.net Git - vlc/blob - src/input/input.c
191e1264480547a0667a66ccddfbfe236aa2f970
[vlc] / src / input / input.c
1 /*****************************************************************************
2  * input.c: input thread
3  *****************************************************************************
4  * Copyright (C) 1998-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Christophe Massiot <massiot@via.ecp.fr>
8  *          Laurent Aimar <fenrir@via.ecp.fr>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33
34 #include <limits.h>
35 #include <assert.h>
36 #include <errno.h>
37
38 #include "input_internal.h"
39 #include "event.h"
40 #include "es_out.h"
41 #include "es_out_timeshift.h"
42 #include "access.h"
43 #include "demux.h"
44 #include "stream.h"
45 #include "item.h"
46 #include "resource.h"
47
48 #include <vlc_sout.h>
49 #include "../stream_output/stream_output.h"
50
51 #include <vlc_dialog.h>
52 #include <vlc_url.h>
53 #include <vlc_charset.h>
54 #include <vlc_fs.h>
55 #include <vlc_strings.h>
56
57 #ifdef HAVE_SYS_STAT_H
58 #   include <sys/stat.h>
59 #endif
60
61 /*****************************************************************************
62  * Local prototypes
63  *****************************************************************************/
64 static void Destructor( input_thread_t * p_input );
65
66 static  void *Run            ( vlc_object_t *p_this );
67
68 static input_thread_t * Create  ( vlc_object_t *, input_item_t *,
69                                   const char *, bool, input_resource_t * );
70 static  int             Init    ( input_thread_t *p_input );
71 static void             End     ( input_thread_t *p_input );
72 static void             MainLoop( input_thread_t *p_input, bool b_interactive );
73
74 static void ObjectKillChildrens( input_thread_t *, vlc_object_t * );
75
76 static inline int ControlPop( input_thread_t *, int *, vlc_value_t *, mtime_t i_deadline, bool b_postpone_seek );
77 static void       ControlRelease( int i_type, vlc_value_t val );
78 static bool       ControlIsSeekRequest( int i_type );
79 static bool       Control( input_thread_t *, int, vlc_value_t );
80
81 static int  UpdateTitleSeekpointFromAccess( input_thread_t * );
82 static void UpdateGenericFromAccess( input_thread_t * );
83
84 static int  UpdateTitleSeekpointFromDemux( input_thread_t * );
85 static void UpdateGenericFromDemux( input_thread_t * );
86
87 static void MRLSections( input_thread_t *, char *, int *, int *, int *, int *);
88
89 static input_source_t *InputSourceNew( input_thread_t *);
90 static int  InputSourceInit( input_thread_t *, input_source_t *,
91                              const char *, const char *psz_forced_demux );
92 static void InputSourceClean( input_source_t * );
93 static void InputSourceMeta( input_thread_t *, input_source_t *, vlc_meta_t * );
94
95 /* TODO */
96 //static void InputGetAttachments( input_thread_t *, input_source_t * );
97 static void SlaveDemux( input_thread_t *p_input, bool *pb_demux_polled );
98 static void SlaveSeek( input_thread_t *p_input );
99
100 static void InputMetaUser( input_thread_t *p_input, vlc_meta_t *p_meta );
101 static void InputUpdateMeta( input_thread_t *p_input, vlc_meta_t *p_meta );
102 static void InputGetExtraFiles( input_thread_t *p_input,
103                                 int *pi_list, char ***pppsz_list,
104                                 const char *psz_access, const char *psz_path );
105
106 static void AppendAttachment( int *pi_attachment, input_attachment_t ***ppp_attachment,
107                               int i_new, input_attachment_t **pp_new );
108
109 static void SubtitleAdd( input_thread_t *p_input, char *psz_subtitle, bool b_forced );
110
111 static void input_ChangeState( input_thread_t *p_input, int i_state ); /* TODO fix name */
112
113 /* Do not let a pts_delay from access/demux go beyong 60s */
114 #define INPUT_PTS_DELAY_MAX INT64_C(60000000)
115
116 #undef input_Create
117 /**
118  * Create a new input_thread_t.
119  *
120  * You need to call input_Start on it when you are done
121  * adding callback on the variables/events you want to monitor.
122  *
123  * \param p_parent a vlc_object
124  * \param p_item an input item
125  * \param psz_log an optional prefix for this input logs
126  * \param p_resource an optional input ressource
127  * \return a pointer to the spawned input thread
128  */
129 input_thread_t *input_Create( vlc_object_t *p_parent,
130                               input_item_t *p_item,
131                               const char *psz_log, input_resource_t *p_resource )
132 {
133     return Create( p_parent, p_item, psz_log, false, p_resource );
134 }
135
136 #undef input_CreateAndStart
137 /**
138  * Create a new input_thread_t and start it.
139  *
140  * Provided for convenience.
141  *
142  * \see input_Create
143  */
144 input_thread_t *input_CreateAndStart( vlc_object_t *p_parent,
145                                       input_item_t *p_item, const char *psz_log )
146 {
147     input_thread_t *p_input = input_Create( p_parent, p_item, psz_log, NULL );
148
149     if( input_Start( p_input ) )
150     {
151         vlc_object_release( p_input );
152         return NULL;
153     }
154     return p_input;
155 }
156
157 #undef input_Read
158 /**
159  * Initialize an input thread and run it until it stops by itself.
160  *
161  * \param p_parent a vlc_object
162  * \param p_item an input item
163  * \return an error code, VLC_SUCCESS on success
164  */
165 int input_Read( vlc_object_t *p_parent, input_item_t *p_item )
166 {
167     input_thread_t *p_input = Create( p_parent, p_item, NULL, false, NULL );
168     if( !p_input )
169         return VLC_EGENERIC;
170
171     if( !Init( p_input ) )
172     {
173         MainLoop( p_input, false );
174         End( p_input );
175     }
176
177     vlc_object_release( p_input );
178     return VLC_SUCCESS;
179 }
180
181 /**
182  * Initialize an input and initialize it to preparse the item
183  * This function is blocking. It will only accept parsing regular files.
184  *
185  * \param p_parent a vlc_object_t
186  * \param p_item an input item
187  * \return VLC_SUCCESS or an error
188  */
189 int input_Preparse( vlc_object_t *p_parent, input_item_t *p_item )
190 {
191     input_thread_t *p_input;
192
193     /* Allocate descriptor */
194     p_input = Create( p_parent, p_item, NULL, true, NULL );
195     if( !p_input )
196         return VLC_EGENERIC;
197
198     if( !Init( p_input ) )
199         End( p_input );
200
201     vlc_object_release( p_input );
202
203     return VLC_SUCCESS;
204 }
205
206 /**
207  * Start a input_thread_t created by input_Create.
208  *
209  * You must not start an already running input_thread_t.
210  *
211  * \param the input thread to start
212  */
213 int input_Start( input_thread_t *p_input )
214 {
215     /* Create thread and wait for its readiness. */
216     if( vlc_thread_create( p_input, "input", Run,
217                            VLC_THREAD_PRIORITY_INPUT ) )
218     {
219         input_ChangeState( p_input, ERROR_S );
220         msg_Err( p_input, "cannot create input thread" );
221         return VLC_EGENERIC;
222     }
223     return VLC_SUCCESS;
224 }
225
226 /**
227  * Request a running input thread to stop and die
228  *
229  * b_abort must be true when a user stop is requested and not because you have
230  * detected an error or an eof. It will be used to properly send the
231  * INPUT_EVENT_ABORT event.
232  *
233  * \param p_input the input thread to stop
234  * \param b_abort true if the input has been aborted by a user request
235  */
236 void input_Stop( input_thread_t *p_input, bool b_abort )
237 {
238     /* Set die for input and ALL of this childrens (even (grand-)grand-childrens)
239      * It is needed here even if it is done in INPUT_CONTROL_SET_DIE handler to
240      * unlock the control loop */
241     ObjectKillChildrens( p_input, VLC_OBJECT(p_input) );
242
243     vlc_mutex_lock( &p_input->p->lock_control );
244     p_input->p->b_abort |= b_abort;
245     vlc_mutex_unlock( &p_input->p->lock_control );
246
247     input_ControlPush( p_input, INPUT_CONTROL_SET_DIE, NULL );
248 }
249
250 input_resource_t *input_DetachResource( input_thread_t *p_input )
251 {
252     assert( p_input->b_dead );
253
254     input_resource_SetInput( p_input->p->p_resource, NULL );
255
256     input_resource_t *p_resource = input_resource_Detach( p_input->p->p_resource );
257     p_input->p->p_sout = NULL;
258
259     return p_resource;
260 }
261
262 /**
263  * Get the item from an input thread
264  * FIXME it does not increase ref count of the item.
265  * if it is used after p_input is destroyed nothing prevent it from
266  * being freed.
267  */
268 input_item_t *input_GetItem( input_thread_t *p_input )
269 {
270     assert( p_input && p_input->p );
271     return p_input->p->p_item;
272 }
273
274 /*****************************************************************************
275  * ObjectKillChildrens
276  *****************************************************************************/
277 static void ObjectKillChildrens( input_thread_t *p_input, vlc_object_t *p_obj )
278 {
279     vlc_list_t *p_list;
280     int i;
281
282     /* FIXME ObjectKillChildrens seems a very bad idea in fact */
283     i = vlc_internals( p_obj )->i_object_type;
284     if( i == VLC_OBJECT_VOUT ||i == VLC_OBJECT_AOUT ||
285         p_obj == VLC_OBJECT(p_input->p->p_sout) ||
286         i == VLC_OBJECT_DECODER )
287         return;
288
289     vlc_object_kill( p_obj );
290
291     p_list = vlc_list_children( p_obj );
292     for( i = 0; i < p_list->i_count; i++ )
293         ObjectKillChildrens( p_input, p_list->p_values[i].p_object );
294     vlc_list_release( p_list );
295 }
296
297 /*****************************************************************************
298  * This function creates a new input, and returns a pointer
299  * to its description. On error, it returns NULL.
300  *
301  * XXX Do not forget to update vlc_input.h if you add new variables.
302  *****************************************************************************/
303 static input_thread_t *Create( vlc_object_t *p_parent, input_item_t *p_item,
304                                const char *psz_header, bool b_quick,
305                                input_resource_t *p_resource )
306 {
307     static const char input_name[] = "input";
308     input_thread_t *p_input = NULL;                 /* thread descriptor */
309     int i;
310
311     /* Allocate descriptor */
312     p_input = vlc_custom_create( p_parent, sizeof( *p_input ),
313                                  VLC_OBJECT_INPUT, input_name );
314     if( p_input == NULL )
315         return NULL;
316
317     vlc_object_attach( p_input, p_parent );
318
319     /* Construct a nice name for the input timer */
320     char psz_timer_name[255];
321     char * psz_name = input_item_GetName( p_item );
322     snprintf( psz_timer_name, sizeof(psz_timer_name),
323               "input launching for '%s'", psz_name );
324
325     msg_Dbg( p_input, "Creating an input for '%s'", psz_name);
326
327     free( psz_name );
328
329     /* Start a timer to mesure how long it takes
330      * to launch an input */
331     stats_TimerStart( p_input, psz_timer_name,
332         STATS_TIMER_INPUT_LAUNCHING );
333
334     p_input->p = calloc( 1, sizeof( input_thread_private_t ) );
335     if( !p_input->p )
336         return NULL;
337
338     p_input->b_preparsing = b_quick;
339     p_input->psz_header = psz_header ? strdup( psz_header ) : NULL;
340
341     /* Init Common fields */
342     p_input->b_eof = false;
343     p_input->p->b_can_pace_control = true;
344     p_input->p->i_start = 0;
345     p_input->p->i_time  = 0;
346     p_input->p->i_stop  = 0;
347     p_input->p->i_run   = 0;
348     p_input->p->i_title = 0;
349     p_input->p->title = NULL;
350     p_input->p->i_title_offset = p_input->p->i_seekpoint_offset = 0;
351     p_input->p->i_state = INIT_S;
352     p_input->p->i_rate = INPUT_RATE_DEFAULT
353                          / var_CreateGetFloat( p_input, "rate" );
354     /* Currently, the input rate variable is an integer. So we need to destroy
355      * the float variable inherited from the configuration. */
356     var_Destroy( p_input, "rate" );
357     p_input->p->b_recording = false;
358     memset( &p_input->p->bookmark, 0, sizeof(p_input->p->bookmark) );
359     TAB_INIT( p_input->p->i_bookmark, p_input->p->pp_bookmark );
360     TAB_INIT( p_input->p->i_attachment, p_input->p->attachment );
361     p_input->p->p_sout   = NULL;
362     p_input->p->b_out_pace_control = false;
363
364     vlc_gc_incref( p_item ); /* Released in Destructor() */
365     p_input->p->p_item = p_item;
366
367     /* Init Input fields */
368     p_input->p->input.p_access = NULL;
369     p_input->p->input.p_stream = NULL;
370     p_input->p->input.p_demux  = NULL;
371     p_input->p->input.b_title_demux = false;
372     p_input->p->input.i_title  = 0;
373     p_input->p->input.title    = NULL;
374     p_input->p->input.i_title_offset = p_input->p->input.i_seekpoint_offset = 0;
375     p_input->p->input.b_can_pace_control = true;
376     p_input->p->input.b_can_rate_control = true;
377     p_input->p->input.b_rescale_ts = true;
378     p_input->p->input.b_eof = false;
379
380     vlc_mutex_lock( &p_item->lock );
381
382     if( !p_item->p_stats )
383         p_item->p_stats = stats_NewInputStats( p_input );
384     vlc_mutex_unlock( &p_item->lock );
385
386     /* No slave */
387     p_input->p->i_slave = 0;
388     p_input->p->slave   = NULL;
389
390     /* */
391     if( p_resource )
392         p_input->p->p_resource = p_resource;
393     else
394         p_input->p->p_resource = input_resource_New();
395     input_resource_SetInput( p_input->p->p_resource, p_input );
396
397     /* Init control buffer */
398     vlc_mutex_init( &p_input->p->lock_control );
399     vlc_cond_init( &p_input->p->wait_control );
400     p_input->p->i_control = 0;
401     p_input->p->b_abort = false;
402
403     /* Parse input options */
404     vlc_mutex_lock( &p_item->lock );
405     assert( (int)p_item->optflagc == p_item->i_options );
406     for( i = 0; i < p_item->i_options; i++ )
407         var_OptionParse( VLC_OBJECT(p_input), p_item->ppsz_options[i],
408                          !!(p_item->optflagv[i] & VLC_INPUT_OPTION_TRUSTED) );
409     vlc_mutex_unlock( &p_item->lock );
410
411     /* Create Object Variables for private use only */
412     input_ConfigVarInit( p_input );
413
414     /* Create Objects variables for public Get and Set */
415     input_ControlVarInit( p_input );
416
417     /* */
418     if( !p_input->b_preparsing )
419     {
420         char *psz_bookmarks = var_GetNonEmptyString( p_input, "bookmarks" );
421         if( psz_bookmarks )
422         {
423             /* FIXME: have a common cfg parsing routine used by sout and others */
424             char *psz_parser, *psz_start, *psz_end;
425             psz_parser = psz_bookmarks;
426             while( (psz_start = strchr( psz_parser, '{' ) ) )
427             {
428                  seekpoint_t *p_seekpoint;
429                  char backup;
430                  psz_start++;
431                  psz_end = strchr( psz_start, '}' );
432                  if( !psz_end ) break;
433                  psz_parser = psz_end + 1;
434                  backup = *psz_parser;
435                  *psz_parser = 0;
436                  *psz_end = ',';
437
438                  p_seekpoint = vlc_seekpoint_New();
439                  while( (psz_end = strchr( psz_start, ',' ) ) )
440                  {
441                      *psz_end = 0;
442                      if( !strncmp( psz_start, "name=", 5 ) )
443                      {
444                          p_seekpoint->psz_name = strdup(psz_start + 5);
445                      }
446                      else if( !strncmp( psz_start, "bytes=", 6 ) )
447                      {
448                          p_seekpoint->i_byte_offset = atoll(psz_start + 6);
449                      }
450                      else if( !strncmp( psz_start, "time=", 5 ) )
451                      {
452                          p_seekpoint->i_time_offset = atoll(psz_start + 5) *
453                                                         1000000;
454                      }
455                      psz_start = psz_end + 1;
456                 }
457                 msg_Dbg( p_input, "adding bookmark: %s, bytes=%"PRId64", time=%"PRId64,
458                                   p_seekpoint->psz_name, p_seekpoint->i_byte_offset,
459                                   p_seekpoint->i_time_offset );
460                 input_Control( p_input, INPUT_ADD_BOOKMARK, p_seekpoint );
461                 vlc_seekpoint_Delete( p_seekpoint );
462                 *psz_parser = backup;
463             }
464             free( psz_bookmarks );
465         }
466     }
467
468     /* Remove 'Now playing' info as it is probably outdated */
469     input_item_SetNowPlaying( p_item, NULL );
470     input_SendEventMeta( p_input );
471
472     /* */
473     if( p_input->b_preparsing )
474         p_input->i_flags |= OBJECT_FLAGS_QUIET | OBJECT_FLAGS_NOINTERACT;
475
476     /* */
477     memset( &p_input->p->counters, 0, sizeof( p_input->p->counters ) );
478     vlc_mutex_init( &p_input->p->counters.counters_lock );
479
480     p_input->p->p_es_out_display = input_EsOutNew( p_input, p_input->p->i_rate );
481     p_input->p->p_es_out = NULL;
482
483     /* Set the destructor when we are sure we are initialized */
484     vlc_object_set_destructor( p_input, (vlc_destructor_t)Destructor );
485
486     return p_input;
487 }
488
489 /**
490  * Input destructor (called when the object's refcount reaches 0).
491  */
492 static void Destructor( input_thread_t * p_input )
493 {
494 #ifndef NDEBUG
495     char * psz_name = input_item_GetName( p_input->p->p_item );
496     msg_Dbg( p_input, "Destroying the input for '%s'", psz_name);
497     free( psz_name );
498 #endif
499
500     stats_TimerDump( p_input, STATS_TIMER_INPUT_LAUNCHING );
501     stats_TimerClean( p_input, STATS_TIMER_INPUT_LAUNCHING );
502
503     if( p_input->p->p_es_out_display )
504         es_out_Delete( p_input->p->p_es_out_display );
505
506     if( p_input->p->p_resource )
507         input_resource_Delete( p_input->p->p_resource );
508
509     vlc_gc_decref( p_input->p->p_item );
510
511     vlc_mutex_destroy( &p_input->p->counters.counters_lock );
512
513     for( int i = 0; i < p_input->p->i_control; i++ )
514     {
515         input_control_t *p_ctrl = &p_input->p->control[i];
516         ControlRelease( p_ctrl->i_type, p_ctrl->val );
517     }
518
519     vlc_cond_destroy( &p_input->p->wait_control );
520     vlc_mutex_destroy( &p_input->p->lock_control );
521     free( p_input->p );
522 }
523
524 /*****************************************************************************
525  * Run: main thread loop
526  * This is the "normal" thread that spawns the input processing chain,
527  * reads the stream, cleans up and waits
528  *****************************************************************************/
529 static void *Run( vlc_object_t *p_this )
530 {
531     input_thread_t *p_input = (input_thread_t *)p_this;
532     const int canc = vlc_savecancel();
533
534     if( Init( p_input ) )
535         goto exit;
536
537     MainLoop( p_input, true ); /* FIXME it can be wrong (like with VLM) */
538
539     /* Clean up */
540     End( p_input );
541
542 exit:
543     /* Tell we're dead */
544     vlc_mutex_lock( &p_input->p->lock_control );
545     const bool b_abort = p_input->p->b_abort;
546     vlc_mutex_unlock( &p_input->p->lock_control );
547
548     if( b_abort )
549         input_SendEventAbort( p_input );
550     input_SendEventDead( p_input );
551
552     vlc_restorecancel( canc );
553     return NULL;
554 }
555
556 /*****************************************************************************
557  * Main loop: Fill buffers from access, and demux
558  *****************************************************************************/
559
560 /**
561  * MainLoopDemux
562  * It asks the demuxer to demux some data
563  */
564 static void MainLoopDemux( input_thread_t *p_input, bool *pb_changed, bool *pb_demux_polled, mtime_t i_start_mdate )
565 {
566     int i_ret;
567
568     *pb_changed = false;
569     *pb_demux_polled = p_input->p->input.p_demux->pf_demux != NULL;
570
571     if( ( p_input->p->i_stop > 0 && p_input->p->i_time >= p_input->p->i_stop ) ||
572         ( p_input->p->i_run > 0 && i_start_mdate+p_input->p->i_run < mdate() ) )
573         i_ret = 0; /* EOF */
574     else
575         i_ret = demux_Demux( p_input->p->input.p_demux );
576
577     if( i_ret > 0 )
578     {
579         if( p_input->p->input.p_demux->info.i_update )
580         {
581             if( p_input->p->input.b_title_demux )
582             {
583                 i_ret = UpdateTitleSeekpointFromDemux( p_input );
584                 *pb_changed = true;
585             }
586             UpdateGenericFromDemux( p_input );
587         }
588         else if( p_input->p->input.p_access &&
589                  p_input->p->input.p_access->info.i_update )
590         {
591             if( !p_input->p->input.b_title_demux )
592             {
593                 i_ret = UpdateTitleSeekpointFromAccess( p_input );
594                 *pb_changed = true;
595             }
596             UpdateGenericFromAccess( p_input );
597         }
598     }
599
600     if( i_ret == 0 )    /* EOF */
601     {
602         msg_Dbg( p_input, "EOF reached" );
603         p_input->p->input.b_eof = true;
604     }
605     else if( i_ret < 0 )
606     {
607         input_ChangeState( p_input, ERROR_S );
608     }
609
610     if( i_ret > 0 && p_input->p->i_slave > 0 )
611     {
612         bool b_demux_polled;
613         SlaveDemux( p_input, &b_demux_polled );
614
615         *pb_demux_polled |= b_demux_polled;
616     }
617 }
618
619 static int MainLoopTryRepeat( input_thread_t *p_input, mtime_t *pi_start_mdate )
620 {
621     int i_repeat = var_GetInteger( p_input, "input-repeat" );
622     if( i_repeat == 0 )
623         return VLC_EGENERIC;
624
625     vlc_value_t val;
626
627     msg_Dbg( p_input, "repeating the same input (%d)", i_repeat );
628     if( i_repeat > 0 )
629     {
630         i_repeat--;
631         var_SetInteger( p_input, "input-repeat", i_repeat );
632     }
633
634     /* Seek to start title/seekpoint */
635     val.i_int = p_input->p->input.i_title_start -
636         p_input->p->input.i_title_offset;
637     if( val.i_int < 0 || val.i_int >= p_input->p->input.i_title )
638         val.i_int = 0;
639     input_ControlPush( p_input,
640                        INPUT_CONTROL_SET_TITLE, &val );
641
642     val.i_int = p_input->p->input.i_seekpoint_start -
643         p_input->p->input.i_seekpoint_offset;
644     if( val.i_int > 0 /* TODO: check upper boundary */ )
645         input_ControlPush( p_input,
646                            INPUT_CONTROL_SET_SEEKPOINT, &val );
647
648     /* Seek to start position */
649     if( p_input->p->i_start > 0 )
650     {
651         val.i_time = p_input->p->i_start;
652         input_ControlPush( p_input, INPUT_CONTROL_SET_TIME, &val );
653     }
654     else
655     {
656         val.f_float = 0.0;
657         input_ControlPush( p_input, INPUT_CONTROL_SET_POSITION, &val );
658     }
659
660     /* */
661     *pi_start_mdate = mdate();
662     return VLC_SUCCESS;
663 }
664
665 /**
666  * MainLoopInterface
667  * It update the variables used by the interfaces
668  */
669 static void MainLoopInterface( input_thread_t *p_input )
670 {
671     double f_position = 0.0;
672     mtime_t i_time = 0;
673     mtime_t i_length = 0;
674
675     /* update input status variables */
676     if( demux_Control( p_input->p->input.p_demux,
677                        DEMUX_GET_POSITION, &f_position ) )
678         f_position = 0.0;
679
680     if( demux_Control( p_input->p->input.p_demux,
681                        DEMUX_GET_TIME, &i_time ) )
682         i_time = 0;
683     p_input->p->i_time = i_time;
684
685     if( demux_Control( p_input->p->input.p_demux,
686                        DEMUX_GET_LENGTH, &i_length ) )
687         i_length = 0;
688
689     es_out_SetTimes( p_input->p->p_es_out, f_position, i_time, i_length );
690
691     /* update current bookmark */
692     vlc_mutex_lock( &p_input->p->p_item->lock );
693     p_input->p->bookmark.i_time_offset = i_time;
694     if( p_input->p->input.p_stream )
695         p_input->p->bookmark.i_byte_offset = stream_Tell( p_input->p->input.p_stream );
696     vlc_mutex_unlock( &p_input->p->p_item->lock );
697 }
698
699 /**
700  * MainLoopStatistic
701  * It updates the globals statics
702  */
703 static void MainLoopStatistic( input_thread_t *p_input )
704 {
705     stats_ComputeInputStats( p_input, p_input->p->p_item->p_stats );
706     input_SendEventStatistics( p_input );
707 }
708
709 /**
710  * MainLoop
711  * The main input loop.
712  */
713 static void MainLoop( input_thread_t *p_input, bool b_interactive )
714 {
715     mtime_t i_start_mdate = mdate();
716     mtime_t i_intf_update = 0;
717     mtime_t i_statistic_update = 0;
718     mtime_t i_last_seek_mdate = 0;
719     bool b_pause_after_eof = b_interactive &&
720                              var_CreateGetBool( p_input, "play-and-pause" );
721
722     /* Start the timer */
723     stats_TimerStop( p_input, STATS_TIMER_INPUT_LAUNCHING );
724
725     while( vlc_object_alive( p_input ) && !p_input->b_error )
726     {
727         bool b_force_update;
728         vlc_value_t val;
729         mtime_t i_current;
730         mtime_t i_wakeup;
731         bool b_paused;
732         bool b_demux_polled;
733
734         /* Demux data */
735         b_force_update = false;
736         i_wakeup = 0;
737         /* FIXME if p_input->p->i_state == PAUSE_S the access/access_demux
738          * is paused -> this may cause problem with some of them
739          * The same problem can be seen when seeking while paused */
740         b_paused = p_input->p->i_state == PAUSE_S &&
741                    ( !es_out_GetBuffering( p_input->p->p_es_out ) || p_input->p->input.b_eof );
742
743         b_demux_polled = true;
744         if( !b_paused )
745         {
746             if( !p_input->p->input.b_eof )
747             {
748                 MainLoopDemux( p_input, &b_force_update, &b_demux_polled, i_start_mdate );
749
750                 i_wakeup = es_out_GetWakeup( p_input->p->p_es_out );
751             }
752             else if( !es_out_GetEmpty( p_input->p->p_es_out ) )
753             {
754                 msg_Dbg( p_input, "waiting decoder fifos to empty" );
755                 i_wakeup = mdate() + INPUT_IDLE_SLEEP;
756             }
757             /* Pause after eof only if the input is pausable.
758              * This way we won't trigger timeshifting for nothing */
759             else if( b_pause_after_eof && p_input->p->b_can_pause )
760             {
761                 msg_Dbg( p_input, "pausing at EOF (pause after each)");
762                 val.i_int = PAUSE_S;
763                 Control( p_input, INPUT_CONTROL_SET_STATE, val );
764
765                 b_pause_after_eof = false;
766                 b_paused = true;
767             }
768             else
769             {
770                 if( MainLoopTryRepeat( p_input, &i_start_mdate ) )
771                     break;
772                 b_pause_after_eof = var_GetBool( p_input, "play-and-pause" );
773             }
774         }
775
776         /* */
777         do {
778             mtime_t i_deadline = i_wakeup;
779             if( b_paused || !b_demux_polled )
780                 i_deadline = __MIN( i_intf_update, i_statistic_update );
781
782             /* Handle control */
783             for( ;; )
784             {
785                 mtime_t i_limit = i_deadline;
786
787                 /* We will postpone the execution of a seek until we have
788                  * finished the ES bufferisation (postpone is limited to
789                  * 125ms) */
790                 bool b_buffering = es_out_GetBuffering( p_input->p->p_es_out ) &&
791                                    !p_input->p->input.b_eof;
792                 if( b_buffering )
793                 {
794                     /* When postpone is in order, check the ES level every 20ms */
795                     mtime_t i_current = mdate();
796                     if( i_last_seek_mdate + INT64_C(125000) >= i_current )
797                         i_limit = __MIN( i_deadline, i_current + INT64_C(20000) );
798                 }
799
800                 int i_type;
801                 if( ControlPop( p_input, &i_type, &val, i_limit, b_buffering ) )
802                 {
803                     if( b_buffering && i_limit < i_deadline )
804                         continue;
805                     break;
806                 }
807
808                 msg_Dbg( p_input, "control type=%d", i_type );
809
810                 if( Control( p_input, i_type, val ) )
811                 {
812                     if( ControlIsSeekRequest( i_type ) )
813                         i_last_seek_mdate = mdate();
814                     b_force_update = true;
815                 }
816             }
817
818             /* Update interface and statistics */
819             i_current = mdate();
820             if( i_intf_update < i_current || b_force_update )
821             {
822                 MainLoopInterface( p_input );
823                 i_intf_update = i_current + INT64_C(250000);
824                 b_force_update = false;
825             }
826             if( i_statistic_update < i_current )
827             {
828                 MainLoopStatistic( p_input );
829                 i_statistic_update = i_current + INT64_C(1000000);
830             }
831
832             /* Update the wakeup time */
833             if( i_wakeup != 0 )
834                 i_wakeup = es_out_GetWakeup( p_input->p->p_es_out );
835         } while( i_current < i_wakeup );
836     }
837
838     if( !p_input->b_error )
839         input_ChangeState( p_input, END_S );
840 }
841
842 static void InitStatistics( input_thread_t * p_input )
843 {
844     if( p_input->b_preparsing ) return;
845
846     /* Prepare statistics */
847 #define INIT_COUNTER( c, type, compute ) p_input->p->counters.p_##c = \
848  stats_CounterCreate( p_input, VLC_VAR_##type, STATS_##compute);
849     if( libvlc_stats( p_input ) )
850     {
851         INIT_COUNTER( read_bytes, INTEGER, COUNTER );
852         INIT_COUNTER( read_packets, INTEGER, COUNTER );
853         INIT_COUNTER( demux_read, INTEGER, COUNTER );
854         INIT_COUNTER( input_bitrate, FLOAT, DERIVATIVE );
855         INIT_COUNTER( demux_bitrate, FLOAT, DERIVATIVE );
856         INIT_COUNTER( demux_corrupted, INTEGER, COUNTER );
857         INIT_COUNTER( demux_discontinuity, INTEGER, COUNTER );
858         INIT_COUNTER( played_abuffers, INTEGER, COUNTER );
859         INIT_COUNTER( lost_abuffers, INTEGER, COUNTER );
860         INIT_COUNTER( displayed_pictures, INTEGER, COUNTER );
861         INIT_COUNTER( lost_pictures, INTEGER, COUNTER );
862         INIT_COUNTER( decoded_audio, INTEGER, COUNTER );
863         INIT_COUNTER( decoded_video, INTEGER, COUNTER );
864         INIT_COUNTER( decoded_sub, INTEGER, COUNTER );
865         p_input->p->counters.p_sout_send_bitrate = NULL;
866         p_input->p->counters.p_sout_sent_packets = NULL;
867         p_input->p->counters.p_sout_sent_bytes = NULL;
868         if( p_input->p->counters.p_demux_bitrate )
869             p_input->p->counters.p_demux_bitrate->update_interval = 1000000;
870         if( p_input->p->counters.p_input_bitrate )
871             p_input->p->counters.p_input_bitrate->update_interval = 1000000;
872     }
873 }
874
875 #ifdef ENABLE_SOUT
876 static int InitSout( input_thread_t * p_input )
877 {
878     if( p_input->b_preparsing )
879         return VLC_SUCCESS;
880
881     /* Find a usable sout and attach it to p_input */
882     char *psz = var_GetNonEmptyString( p_input, "sout" );
883     if( psz && strncasecmp( p_input->p->p_item->psz_uri, "vlc:", 4 ) )
884     {
885         p_input->p->p_sout  = input_resource_RequestSout( p_input->p->p_resource, NULL, psz );
886         if( !p_input->p->p_sout )
887         {
888             input_ChangeState( p_input, ERROR_S );
889             msg_Err( p_input, "cannot start stream output instance, " \
890                               "aborting" );
891             free( psz );
892             return VLC_EGENERIC;
893         }
894         if( libvlc_stats( p_input ) )
895         {
896             INIT_COUNTER( sout_sent_packets, INTEGER, COUNTER );
897             INIT_COUNTER( sout_sent_bytes, INTEGER, COUNTER );
898             INIT_COUNTER( sout_send_bitrate, FLOAT, DERIVATIVE );
899             if( p_input->p->counters.p_sout_send_bitrate )
900                  p_input->p->counters.p_sout_send_bitrate->update_interval =
901                          1000000;
902         }
903     }
904     else
905     {
906         input_resource_RequestSout( p_input->p->p_resource, NULL, NULL );
907     }
908     free( psz );
909
910     return VLC_SUCCESS;
911 }
912 #endif
913
914 static void InitTitle( input_thread_t * p_input )
915 {
916     input_source_t *p_master = &p_input->p->input;
917
918     if( p_input->b_preparsing )
919         return;
920
921     /* Create global title (from master) */
922     p_input->p->i_title = p_master->i_title;
923     p_input->p->title   = p_master->title;
924     p_input->p->i_title_offset = p_master->i_title_offset;
925     p_input->p->i_seekpoint_offset = p_master->i_seekpoint_offset;
926     if( p_input->p->i_title > 0 )
927     {
928         /* Setup variables */
929         input_ControlVarNavigation( p_input );
930         input_SendEventTitle( p_input, 0 );
931     }
932
933     /* Global flag */
934     p_input->p->b_can_pace_control    = p_master->b_can_pace_control;
935     p_input->p->b_can_pause        = p_master->b_can_pause;
936     p_input->p->b_can_rate_control = p_master->b_can_rate_control;
937 }
938
939 static void StartTitle( input_thread_t * p_input )
940 {
941     vlc_value_t val;
942
943     /* Start title/chapter */
944     val.i_int = p_input->p->input.i_title_start -
945                 p_input->p->input.i_title_offset;
946     if( val.i_int > 0 && val.i_int < p_input->p->input.i_title )
947         input_ControlPush( p_input, INPUT_CONTROL_SET_TITLE, &val );
948
949     val.i_int = p_input->p->input.i_seekpoint_start -
950                 p_input->p->input.i_seekpoint_offset;
951     if( val.i_int > 0 /* TODO: check upper boundary */ )
952         input_ControlPush( p_input, INPUT_CONTROL_SET_SEEKPOINT, &val );
953
954     /* Start/stop/run time */
955     p_input->p->i_start = (int64_t)(1000000.0
956                                      * var_GetFloat( p_input, "start-time" ));
957     p_input->p->i_stop  = (int64_t)(1000000.0
958                                      * var_GetFloat( p_input, "stop-time" ));
959     p_input->p->i_run   = (int64_t)(1000000.0
960                                      * var_GetFloat( p_input, "run-time" ));
961     if( p_input->p->i_run < 0 )
962     {
963         msg_Warn( p_input, "invalid run-time ignored" );
964         p_input->p->i_run = 0;
965     }
966
967     if( p_input->p->i_start > 0 )
968     {
969         vlc_value_t s;
970
971         msg_Dbg( p_input, "starting at time: %ds",
972                  (int)( p_input->p->i_start / INT64_C(1000000) ) );
973
974         s.i_time = p_input->p->i_start;
975         input_ControlPush( p_input, INPUT_CONTROL_SET_TIME, &s );
976     }
977     if( p_input->p->i_stop > 0 && p_input->p->i_stop <= p_input->p->i_start )
978     {
979         msg_Warn( p_input, "invalid stop-time ignored" );
980         p_input->p->i_stop = 0;
981     }
982     p_input->p->b_fast_seek = var_GetBool( p_input, "input-fast-seek" );
983 }
984
985 static void LoadSubtitles( input_thread_t *p_input )
986 {
987     /* Load subtitles */
988     /* Get fps and set it if not already set */
989     const double f_fps = p_input->p->f_fps;
990     if( f_fps > 1.0 )
991     {
992         float f_requested_fps;
993
994         var_Create( p_input, "sub-original-fps", VLC_VAR_FLOAT );
995         var_SetFloat( p_input, "sub-original-fps", f_fps );
996
997         f_requested_fps = var_CreateGetFloat( p_input, "sub-fps" );
998         if( f_requested_fps != f_fps )
999         {
1000             var_Create( p_input, "sub-fps", VLC_VAR_FLOAT|
1001                                             VLC_VAR_DOINHERIT );
1002             var_SetFloat( p_input, "sub-fps", f_requested_fps );
1003         }
1004     }
1005
1006     const int i_delay = var_CreateGetInteger( p_input, "sub-delay" );
1007     if( i_delay != 0 )
1008         var_SetTime( p_input, "spu-delay", (mtime_t)i_delay * 100000 );
1009
1010     /* Look for and add subtitle files */
1011     bool b_forced = true;
1012
1013     char *psz_subtitle = var_GetNonEmptyString( p_input, "sub-file" );
1014     if( psz_subtitle != NULL )
1015     {
1016         msg_Dbg( p_input, "forced subtitle: %s", psz_subtitle );
1017         SubtitleAdd( p_input, psz_subtitle, b_forced );
1018         b_forced = false;
1019     }
1020
1021     if( var_GetBool( p_input, "sub-autodetect-file" ) )
1022     {
1023         char *psz_autopath = var_GetNonEmptyString( p_input, "sub-autodetect-path" );
1024         char **ppsz_subs = subtitles_Detect( p_input, psz_autopath,
1025                                              p_input->p->p_item->psz_uri );
1026         free( psz_autopath );
1027
1028         for( int i = 0; ppsz_subs && ppsz_subs[i]; i++ )
1029         {
1030             if( !psz_subtitle || strcmp( psz_subtitle, ppsz_subs[i] ) )
1031             {
1032                 SubtitleAdd( p_input, ppsz_subs[i], b_forced );
1033                 b_forced = false;
1034             }
1035
1036             free( ppsz_subs[i] );
1037         }
1038         free( ppsz_subs );
1039     }
1040     free( psz_subtitle );
1041
1042     /* Load subtitles from attachments */
1043     int i_attachment = 0;
1044     input_attachment_t **pp_attachment = NULL;
1045
1046     vlc_mutex_lock( &p_input->p->p_item->lock );
1047     for( int i = 0; i < p_input->p->i_attachment; i++ )
1048     {
1049         const input_attachment_t *a = p_input->p->attachment[i];
1050         if( !strcmp( a->psz_mime, "application/x-srt" ) )
1051             TAB_APPEND( i_attachment, pp_attachment,
1052                         vlc_input_attachment_New( a->psz_name, NULL,
1053                                                   a->psz_description, NULL, 0 ) );
1054     }
1055     vlc_mutex_unlock( &p_input->p->p_item->lock );
1056
1057     if( i_attachment > 0 )
1058         var_Create( p_input, "sub-description", VLC_VAR_STRING );
1059     for( int i = 0; i < i_attachment; i++ )
1060     {
1061         input_attachment_t *a = pp_attachment[i];
1062         if( !a )
1063             continue;
1064         char *psz_mrl;
1065         if( a->psz_name[i] &&
1066             asprintf( &psz_mrl, "attachment://%s", a->psz_name ) >= 0 )
1067         {
1068             var_SetString( p_input, "sub-description", a->psz_description ? a->psz_description : "");
1069
1070             SubtitleAdd( p_input, psz_mrl, b_forced );
1071
1072             b_forced = false;
1073             free( psz_mrl );
1074         }
1075         vlc_input_attachment_Delete( a );
1076     }
1077     free( pp_attachment );
1078     if( i_attachment > 0 )
1079         var_Destroy( p_input, "sub-description" );
1080 }
1081
1082 static void LoadSlaves( input_thread_t *p_input )
1083 {
1084     char *psz = var_GetNonEmptyString( p_input, "input-slave" );
1085     if( !psz )
1086         return;
1087
1088     char *psz_org = psz;
1089     while( psz && *psz )
1090     {
1091         while( *psz == ' ' || *psz == '#' )
1092             psz++;
1093
1094         char *psz_delim = strchr( psz, '#' );
1095         if( psz_delim )
1096             *psz_delim++ = '\0';
1097
1098         if( *psz == 0 )
1099             break;
1100
1101         msg_Dbg( p_input, "adding slave input '%s'", psz );
1102
1103         input_source_t *p_slave = InputSourceNew( p_input );
1104         if( p_slave && !InputSourceInit( p_input, p_slave, psz, NULL ) )
1105             TAB_APPEND( p_input->p->i_slave, p_input->p->slave, p_slave );
1106         else
1107             free( p_slave );
1108
1109         psz = psz_delim;
1110     }
1111     free( psz_org );
1112 }
1113
1114 static void UpdatePtsDelay( input_thread_t *p_input )
1115 {
1116     input_thread_private_t *p_sys = p_input->p;
1117
1118     /* Get max pts delay from input source */
1119     mtime_t i_pts_delay = p_sys->input.i_pts_delay;
1120     for( int i = 0; i < p_sys->i_slave; i++ )
1121         i_pts_delay = __MAX( i_pts_delay, p_sys->slave[i]->i_pts_delay );
1122
1123     if( i_pts_delay < 0 )
1124         i_pts_delay = 0;
1125
1126     /* Take care of audio/spu delay */
1127     const mtime_t i_audio_delay = var_GetTime( p_input, "audio-delay" );
1128     const mtime_t i_spu_delay   = var_GetTime( p_input, "spu-delay" );
1129     const mtime_t i_extra_delay = __MIN( i_audio_delay, i_spu_delay );
1130     if( i_extra_delay < 0 )
1131         i_pts_delay -= i_extra_delay;
1132
1133     /* Update cr_average depending on the caching */
1134     const int i_cr_average = var_GetInteger( p_input, "cr-average" ) * i_pts_delay / DEFAULT_PTS_DELAY;
1135
1136     /* */
1137     es_out_SetJitter( p_input->p->p_es_out, i_pts_delay, i_cr_average );
1138 }
1139
1140 static void InitPrograms( input_thread_t * p_input )
1141 {
1142     int i_es_out_mode;
1143     vlc_value_t val;
1144
1145     /* Compute correct pts_delay */
1146     UpdatePtsDelay( p_input );
1147
1148     /* Set up es_out */
1149     i_es_out_mode = ES_OUT_MODE_AUTO;
1150     if( p_input->p->p_sout )
1151     {
1152         if( var_GetBool( p_input, "sout-all" ) )
1153         {
1154             i_es_out_mode = ES_OUT_MODE_ALL;
1155         }
1156         else
1157         {
1158             var_Get( p_input, "programs", &val );
1159             if( val.p_list && val.p_list->i_count )
1160             {
1161                 i_es_out_mode = ES_OUT_MODE_PARTIAL;
1162                 /* Note : we should remove the "program" callback. */
1163             }
1164             else
1165             {
1166                 var_FreeList( &val, NULL );
1167             }
1168         }
1169     }
1170     es_out_SetMode( p_input->p->p_es_out, i_es_out_mode );
1171
1172     /* Inform the demuxer about waited group (needed only for DVB) */
1173     if( i_es_out_mode == ES_OUT_MODE_ALL )
1174     {
1175         demux_Control( p_input->p->input.p_demux, DEMUX_SET_GROUP, -1, NULL );
1176     }
1177     else if( i_es_out_mode == ES_OUT_MODE_PARTIAL )
1178     {
1179         demux_Control( p_input->p->input.p_demux, DEMUX_SET_GROUP, -1,
1180                         val.p_list );
1181     }
1182     else
1183     {
1184         demux_Control( p_input->p->input.p_demux, DEMUX_SET_GROUP,
1185                        (int) var_GetInteger( p_input, "program" ), NULL );
1186     }
1187 }
1188
1189 static int Init( input_thread_t * p_input )
1190 {
1191     vlc_meta_t *p_meta;
1192     int i;
1193
1194     for( i = 0; i < p_input->p->p_item->i_options; i++ )
1195     {
1196         if( !strncmp( p_input->p->p_item->ppsz_options[i], "meta-file", 9 ) )
1197         {
1198             msg_Dbg( p_input, "Input is a meta file: disabling unneeded options" );
1199             var_SetString( p_input, "sout", "" );
1200             var_SetBool( p_input, "sout-all", false );
1201             var_SetString( p_input, "input-slave", "" );
1202             var_SetInteger( p_input, "input-repeat", 0 );
1203             var_SetString( p_input, "sub-file", "" );
1204             var_SetBool( p_input, "sub-autodetect-file", false );
1205         }
1206     }
1207
1208     InitStatistics( p_input );
1209 #ifdef ENABLE_SOUT
1210     if( InitSout( p_input ) )
1211         goto error;
1212 #endif
1213
1214     /* Create es out */
1215     p_input->p->p_es_out = input_EsOutTimeshiftNew( p_input, p_input->p->p_es_out_display, p_input->p->i_rate );
1216
1217     /* */
1218     input_ChangeState( p_input, OPENING_S );
1219     input_SendEventCache( p_input, 0.0 );
1220
1221     /* */
1222     if( InputSourceInit( p_input, &p_input->p->input,
1223                          p_input->p->p_item->psz_uri, NULL ) )
1224     {
1225         goto error;
1226     }
1227
1228     InitTitle( p_input );
1229
1230     /* Load master infos */
1231     /* Init length */
1232     mtime_t i_length;
1233     if( demux_Control( p_input->p->input.p_demux, DEMUX_GET_LENGTH,
1234                          &i_length ) )
1235         i_length = 0;
1236     if( i_length <= 0 )
1237         i_length = input_item_GetDuration( p_input->p->p_item );
1238     input_SendEventLength( p_input, i_length );
1239
1240     input_SendEventPosition( p_input, 0.0, 0 );
1241
1242     if( !p_input->b_preparsing )
1243     {
1244         StartTitle( p_input );
1245         LoadSubtitles( p_input );
1246         LoadSlaves( p_input );
1247         InitPrograms( p_input );
1248     }
1249
1250     if( !p_input->b_preparsing && p_input->p->p_sout )
1251     {
1252         p_input->p->b_out_pace_control = (p_input->p->p_sout->i_out_pace_nocontrol > 0);
1253
1254         if( p_input->p->b_can_pace_control && p_input->p->b_out_pace_control )
1255         {
1256             /* We don't want a high input priority here or we'll
1257              * end-up sucking up all the CPU time */
1258             vlc_thread_set_priority( p_input, VLC_THREAD_PRIORITY_LOW );
1259         }
1260
1261         msg_Dbg( p_input, "starting in %s mode",
1262                  p_input->p->b_out_pace_control ? "async" : "sync" );
1263     }
1264
1265     p_meta = vlc_meta_New();
1266     if( p_meta )
1267     {
1268         /* Get meta data from users */
1269         InputMetaUser( p_input, p_meta );
1270
1271         /* Get meta data from master input */
1272         InputSourceMeta( p_input, &p_input->p->input, p_meta );
1273
1274         /* And from slave */
1275         for( int i = 0; i < p_input->p->i_slave; i++ )
1276             InputSourceMeta( p_input, p_input->p->slave[i], p_meta );
1277
1278         /* */
1279         InputUpdateMeta( p_input, p_meta );
1280     }
1281
1282     msg_Dbg( p_input, "`%s' successfully opened",
1283              p_input->p->p_item->psz_uri );
1284
1285     /* initialization is complete */
1286     input_ChangeState( p_input, PLAYING_S );
1287
1288     return VLC_SUCCESS;
1289
1290 error:
1291     input_ChangeState( p_input, ERROR_S );
1292
1293     if( p_input->p->p_es_out )
1294         es_out_Delete( p_input->p->p_es_out );
1295     es_out_SetMode( p_input->p->p_es_out_display, ES_OUT_MODE_END );
1296     if( p_input->p->p_resource )
1297     {
1298         if( p_input->p->p_sout )
1299             input_resource_RequestSout( p_input->p->p_resource,
1300                                          p_input->p->p_sout, NULL );
1301         input_resource_SetInput( p_input->p->p_resource, NULL );
1302     }
1303
1304     if( !p_input->b_preparsing && libvlc_stats( p_input ) )
1305     {
1306 #define EXIT_COUNTER( c ) do { if( p_input->p->counters.p_##c ) \
1307                                    stats_CounterClean( p_input->p->counters.p_##c );\
1308                                p_input->p->counters.p_##c = NULL; } while(0)
1309         EXIT_COUNTER( read_bytes );
1310         EXIT_COUNTER( read_packets );
1311         EXIT_COUNTER( demux_read );
1312         EXIT_COUNTER( input_bitrate );
1313         EXIT_COUNTER( demux_bitrate );
1314         EXIT_COUNTER( demux_corrupted );
1315         EXIT_COUNTER( demux_discontinuity );
1316         EXIT_COUNTER( played_abuffers );
1317         EXIT_COUNTER( lost_abuffers );
1318         EXIT_COUNTER( displayed_pictures );
1319         EXIT_COUNTER( lost_pictures );
1320         EXIT_COUNTER( decoded_audio );
1321         EXIT_COUNTER( decoded_video );
1322         EXIT_COUNTER( decoded_sub );
1323
1324         if( p_input->p->p_sout )
1325         {
1326             EXIT_COUNTER( sout_sent_packets );
1327             EXIT_COUNTER( sout_sent_bytes );
1328             EXIT_COUNTER( sout_send_bitrate );
1329         }
1330 #undef EXIT_COUNTER
1331     }
1332
1333     /* Mark them deleted */
1334     p_input->p->input.p_demux = NULL;
1335     p_input->p->input.p_stream = NULL;
1336     p_input->p->input.p_access = NULL;
1337     p_input->p->p_es_out = NULL;
1338     p_input->p->p_sout = NULL;
1339
1340     return VLC_EGENERIC;
1341 }
1342
1343 /*****************************************************************************
1344  * End: end the input thread
1345  *****************************************************************************/
1346 static void End( input_thread_t * p_input )
1347 {
1348     int i;
1349
1350     /* We are at the end */
1351     input_ChangeState( p_input, END_S );
1352
1353     /* Clean control variables */
1354     input_ControlVarStop( p_input );
1355
1356     /* Stop es out activity */
1357     es_out_SetMode( p_input->p->p_es_out, ES_OUT_MODE_NONE );
1358
1359     /* Clean up master */
1360     InputSourceClean( &p_input->p->input );
1361
1362     /* Delete slave */
1363     for( i = 0; i < p_input->p->i_slave; i++ )
1364     {
1365         InputSourceClean( p_input->p->slave[i] );
1366         free( p_input->p->slave[i] );
1367     }
1368     free( p_input->p->slave );
1369
1370     /* Unload all modules */
1371     if( p_input->p->p_es_out )
1372         es_out_Delete( p_input->p->p_es_out );
1373     es_out_SetMode( p_input->p->p_es_out_display, ES_OUT_MODE_END );
1374
1375     if( !p_input->b_preparsing )
1376     {
1377 #define CL_CO( c ) stats_CounterClean( p_input->p->counters.p_##c ); p_input->p->counters.p_##c = NULL;
1378         if( libvlc_stats( p_input ) )
1379         {
1380             /* make sure we are up to date */
1381             stats_ComputeInputStats( p_input, p_input->p->p_item->p_stats );
1382             CL_CO( read_bytes );
1383             CL_CO( read_packets );
1384             CL_CO( demux_read );
1385             CL_CO( input_bitrate );
1386             CL_CO( demux_bitrate );
1387             CL_CO( demux_corrupted );
1388             CL_CO( demux_discontinuity );
1389             CL_CO( played_abuffers );
1390             CL_CO( lost_abuffers );
1391             CL_CO( displayed_pictures );
1392             CL_CO( lost_pictures );
1393             CL_CO( decoded_audio) ;
1394             CL_CO( decoded_video );
1395             CL_CO( decoded_sub) ;
1396         }
1397
1398         /* Close optional stream output instance */
1399         if( p_input->p->p_sout )
1400         {
1401             CL_CO( sout_sent_packets );
1402             CL_CO( sout_sent_bytes );
1403             CL_CO( sout_send_bitrate );
1404         }
1405 #undef CL_CO
1406     }
1407
1408     vlc_mutex_lock( &p_input->p->p_item->lock );
1409     if( p_input->p->i_attachment > 0 )
1410     {
1411         for( i = 0; i < p_input->p->i_attachment; i++ )
1412             vlc_input_attachment_Delete( p_input->p->attachment[i] );
1413         TAB_CLEAN( p_input->p->i_attachment, p_input->p->attachment );
1414     }
1415     vlc_mutex_unlock( &p_input->p->p_item->lock );
1416
1417     /* */
1418     input_resource_RequestSout( p_input->p->p_resource,
1419                                  p_input->p->p_sout, NULL );
1420     input_resource_SetInput( p_input->p->p_resource, NULL );
1421 }
1422
1423 /*****************************************************************************
1424  * Control
1425  *****************************************************************************/
1426 void input_ControlPush( input_thread_t *p_input,
1427                         int i_type, vlc_value_t *p_val )
1428 {
1429     vlc_mutex_lock( &p_input->p->lock_control );
1430     if( i_type == INPUT_CONTROL_SET_DIE )
1431     {
1432         /* Special case, empty the control */
1433         for( int i = 0; i < p_input->p->i_control; i++ )
1434         {
1435             input_control_t *p_ctrl = &p_input->p->control[i];
1436             ControlRelease( p_ctrl->i_type, p_ctrl->val );
1437         }
1438         p_input->p->i_control = 0;
1439     }
1440
1441     if( p_input->p->i_control >= INPUT_CONTROL_FIFO_SIZE )
1442     {
1443         msg_Err( p_input, "input control fifo overflow, trashing type=%d",
1444                  i_type );
1445         if( p_val )
1446             ControlRelease( i_type, *p_val );
1447     }
1448     else
1449     {
1450         input_control_t c;
1451         c.i_type = i_type;
1452         if( p_val )
1453             c.val = *p_val;
1454         else
1455             memset( &c.val, 0, sizeof(c.val) );
1456
1457         p_input->p->control[p_input->p->i_control++] = c;
1458     }
1459     vlc_cond_signal( &p_input->p->wait_control );
1460     vlc_mutex_unlock( &p_input->p->lock_control );
1461 }
1462
1463 static int ControlGetReducedIndexLocked( input_thread_t *p_input )
1464 {
1465     const int i_lt = p_input->p->control[0].i_type;
1466     int i;
1467     for( i = 1; i < p_input->p->i_control; i++ )
1468     {
1469         const int i_ct = p_input->p->control[i].i_type;
1470
1471         if( i_lt == i_ct &&
1472             ( i_ct == INPUT_CONTROL_SET_STATE ||
1473               i_ct == INPUT_CONTROL_SET_RATE ||
1474               i_ct == INPUT_CONTROL_SET_POSITION ||
1475               i_ct == INPUT_CONTROL_SET_TIME ||
1476               i_ct == INPUT_CONTROL_SET_PROGRAM ||
1477               i_ct == INPUT_CONTROL_SET_TITLE ||
1478               i_ct == INPUT_CONTROL_SET_SEEKPOINT ||
1479               i_ct == INPUT_CONTROL_SET_BOOKMARK ) )
1480         {
1481             continue;
1482         }
1483         else
1484         {
1485             /* TODO but that's not that important
1486                 - merge SET_X with SET_X_CMD
1487                 - ignore SET_SEEKPOINT/SET_POSITION/SET_TIME before a SET_TITLE
1488                 - ignore SET_SEEKPOINT/SET_POSITION/SET_TIME before another among them
1489                 - ?
1490                 */
1491             break;
1492         }
1493     }
1494     return i - 1;
1495 }
1496
1497
1498 static inline int ControlPop( input_thread_t *p_input,
1499                               int *pi_type, vlc_value_t *p_val,
1500                               mtime_t i_deadline, bool b_postpone_seek )
1501 {
1502     input_thread_private_t *p_sys = p_input->p;
1503
1504     vlc_mutex_lock( &p_sys->lock_control );
1505     while( p_sys->i_control <= 0 ||
1506            ( b_postpone_seek && ControlIsSeekRequest( p_sys->control[0].i_type ) ) )
1507     {
1508         if( !vlc_object_alive( p_input ) || i_deadline < 0 )
1509         {
1510             vlc_mutex_unlock( &p_sys->lock_control );
1511             return VLC_EGENERIC;
1512         }
1513
1514         if( vlc_cond_timedwait( &p_sys->wait_control, &p_sys->lock_control,
1515                                 i_deadline ) )
1516         {
1517             vlc_mutex_unlock( &p_sys->lock_control );
1518             return VLC_EGENERIC;
1519         }
1520     }
1521
1522     /* */
1523     const int i_index = ControlGetReducedIndexLocked( p_input );
1524
1525     /* */
1526     *pi_type = p_sys->control[i_index].i_type;
1527     *p_val   = p_sys->control[i_index].val;
1528
1529     p_sys->i_control -= i_index + 1;
1530     if( p_sys->i_control > 0 )
1531         memmove( &p_sys->control[0], &p_sys->control[i_index+1],
1532                  sizeof(*p_sys->control) * p_sys->i_control );
1533     vlc_mutex_unlock( &p_sys->lock_control );
1534
1535     return VLC_SUCCESS;
1536 }
1537 static bool ControlIsSeekRequest( int i_type )
1538 {
1539     switch( i_type )
1540     {
1541     case INPUT_CONTROL_SET_POSITION:
1542     case INPUT_CONTROL_SET_TIME:
1543     case INPUT_CONTROL_SET_TITLE:
1544     case INPUT_CONTROL_SET_TITLE_NEXT:
1545     case INPUT_CONTROL_SET_TITLE_PREV:
1546     case INPUT_CONTROL_SET_SEEKPOINT:
1547     case INPUT_CONTROL_SET_SEEKPOINT_NEXT:
1548     case INPUT_CONTROL_SET_SEEKPOINT_PREV:
1549     case INPUT_CONTROL_SET_BOOKMARK:
1550         return true;
1551     default:
1552         return false;
1553     }
1554 }
1555
1556 static void ControlRelease( int i_type, vlc_value_t val )
1557 {
1558     switch( i_type )
1559     {
1560     case INPUT_CONTROL_ADD_SUBTITLE:
1561     case INPUT_CONTROL_ADD_SLAVE:
1562         free( val.psz_string );
1563         break;
1564
1565     default:
1566         break;
1567     }
1568 }
1569
1570 /* Pause input */
1571 static void ControlPause( input_thread_t *p_input, mtime_t i_control_date )
1572 {
1573     int i_ret = VLC_SUCCESS;
1574     int i_state = PAUSE_S;
1575
1576     if( p_input->p->b_can_pause )
1577     {
1578         if( p_input->p->input.p_access )
1579             i_ret = access_Control( p_input->p->input.p_access,
1580                                      ACCESS_SET_PAUSE_STATE, true );
1581         else
1582             i_ret = demux_Control( p_input->p->input.p_demux,
1583                                     DEMUX_SET_PAUSE_STATE, true );
1584
1585         if( i_ret )
1586         {
1587             msg_Warn( p_input, "cannot set pause state" );
1588             return;
1589         }
1590     }
1591
1592     /* */
1593     i_ret = es_out_SetPauseState( p_input->p->p_es_out,
1594                                   p_input->p->b_can_pause, true,
1595                                   i_control_date );
1596     if( i_ret )
1597     {
1598         msg_Warn( p_input, "cannot set pause state at es_out level" );
1599         return;
1600     }
1601
1602     /* Switch to new state */
1603     input_ChangeState( p_input, i_state );
1604 }
1605
1606 static void ControlUnpause( input_thread_t *p_input, mtime_t i_control_date )
1607 {
1608     int i_ret = VLC_SUCCESS;
1609
1610     if( p_input->p->b_can_pause )
1611     {
1612         if( p_input->p->input.p_access )
1613             i_ret = access_Control( p_input->p->input.p_access,
1614                                      ACCESS_SET_PAUSE_STATE, false );
1615         else
1616             i_ret = demux_Control( p_input->p->input.p_demux,
1617                                     DEMUX_SET_PAUSE_STATE, false );
1618         if( i_ret )
1619         {
1620             /* FIXME What to do ? */
1621             msg_Warn( p_input, "cannot unset pause -> EOF" );
1622             input_ControlPush( p_input, INPUT_CONTROL_SET_DIE, NULL );
1623         }
1624     }
1625
1626     /* Switch to play */
1627     input_ChangeState( p_input, PLAYING_S );
1628
1629     /* */
1630     if( !i_ret )
1631         es_out_SetPauseState( p_input->p->p_es_out, false, false, i_control_date );
1632 }
1633
1634 static bool Control( input_thread_t *p_input,
1635                      int i_type, vlc_value_t val )
1636 {
1637     const mtime_t i_control_date = mdate();
1638     /* FIXME b_force_update is abused, it should be carefully checked */
1639     bool b_force_update = false;
1640
1641     if( !p_input )
1642         return b_force_update;
1643
1644     switch( i_type )
1645     {
1646         case INPUT_CONTROL_SET_DIE:
1647             msg_Dbg( p_input, "control: stopping input" );
1648
1649             /* Mark all submodules to die */
1650             ObjectKillChildrens( p_input, VLC_OBJECT(p_input) );
1651             break;
1652
1653         case INPUT_CONTROL_SET_POSITION:
1654         {
1655             double f_pos;
1656
1657             if( p_input->p->b_recording )
1658             {
1659                 msg_Err( p_input, "INPUT_CONTROL_SET_POSITION(_OFFSET) ignored while recording" );
1660                 break;
1661             }
1662             f_pos = val.f_float;
1663             if( i_type != INPUT_CONTROL_SET_POSITION )
1664                 f_pos += var_GetFloat( p_input, "position" );
1665             if( f_pos < 0.0 )
1666                 f_pos = 0.0;
1667             else if( f_pos > 1.0 )
1668                 f_pos = 1.0;
1669             /* Reset the decoders states and clock sync (before calling the demuxer */
1670             es_out_SetTime( p_input->p->p_es_out, -1 );
1671             if( demux_Control( p_input->p->input.p_demux, DEMUX_SET_POSITION,
1672                                 f_pos, !p_input->p->b_fast_seek ) )
1673             {
1674                 msg_Err( p_input, "INPUT_CONTROL_SET_POSITION(_OFFSET) "
1675                          "%2.1f%% failed", f_pos * 100 );
1676             }
1677             else
1678             {
1679                 if( p_input->p->i_slave > 0 )
1680                     SlaveSeek( p_input );
1681                 p_input->p->input.b_eof = false;
1682
1683                 b_force_update = true;
1684             }
1685             break;
1686         }
1687
1688         case INPUT_CONTROL_SET_TIME:
1689         {
1690             int64_t i_time;
1691             int i_ret;
1692
1693             if( p_input->p->b_recording )
1694             {
1695                 msg_Err( p_input, "INPUT_CONTROL_SET_TIME(_OFFSET) ignored while recording" );
1696                 break;
1697             }
1698
1699             i_time = val.i_time;
1700             if( i_type != INPUT_CONTROL_SET_TIME )
1701                 i_time += var_GetTime( p_input, "time" );
1702
1703             if( i_time < 0 )
1704                 i_time = 0;
1705
1706             /* Reset the decoders states and clock sync (before calling the demuxer */
1707             es_out_SetTime( p_input->p->p_es_out, -1 );
1708
1709             i_ret = demux_Control( p_input->p->input.p_demux,
1710                                    DEMUX_SET_TIME, i_time,
1711                                    !p_input->p->b_fast_seek );
1712             if( i_ret )
1713             {
1714                 int64_t i_length;
1715
1716                 /* Emulate it with a SET_POS */
1717                 if( !demux_Control( p_input->p->input.p_demux,
1718                                     DEMUX_GET_LENGTH, &i_length ) && i_length > 0 )
1719                 {
1720                     double f_pos = (double)i_time / (double)i_length;
1721                     i_ret = demux_Control( p_input->p->input.p_demux,
1722                                             DEMUX_SET_POSITION, f_pos,
1723                                             !p_input->p->b_fast_seek );
1724                 }
1725             }
1726             if( i_ret )
1727             {
1728                 msg_Warn( p_input, "INPUT_CONTROL_SET_TIME(_OFFSET) %"PRId64
1729                          " failed or not possible", i_time );
1730             }
1731             else
1732             {
1733                 if( p_input->p->i_slave > 0 )
1734                     SlaveSeek( p_input );
1735                 p_input->p->input.b_eof = false;
1736
1737                 b_force_update = true;
1738             }
1739             break;
1740         }
1741
1742         case INPUT_CONTROL_SET_STATE:
1743             if( val.i_int != PLAYING_S && val.i_int != PAUSE_S )
1744                 msg_Err( p_input, "invalid state in INPUT_CONTROL_SET_STATE" );
1745             else if( p_input->p->i_state == PAUSE_S )
1746             {
1747                 ControlUnpause( p_input, i_control_date );
1748
1749                 b_force_update = true;
1750             }
1751             else if( val.i_int == PAUSE_S && p_input->p->i_state == PLAYING_S /* &&
1752                      p_input->p->b_can_pause */ )
1753             {
1754                 ControlPause( p_input, i_control_date );
1755
1756                 b_force_update = true;
1757             }
1758             else if( val.i_int == PAUSE_S && !p_input->p->b_can_pause && 0 )
1759             {
1760                 b_force_update = true;
1761
1762                 /* Correct "state" value */
1763                 input_ChangeState( p_input, p_input->p->i_state );
1764             }
1765             break;
1766
1767         case INPUT_CONTROL_SET_RATE:
1768         case INPUT_CONTROL_SET_RATE_SLOWER:
1769         case INPUT_CONTROL_SET_RATE_FASTER:
1770         {
1771             int i_rate;
1772             int i_rate_sign;
1773
1774             /* Get rate and direction */
1775             if( i_type == INPUT_CONTROL_SET_RATE )
1776             {
1777                 i_rate = abs( val.i_int );
1778                 i_rate_sign = val.i_int < 0 ? -1 : 1;
1779             }
1780             else
1781             {
1782                 static const int ppi_factor[][2] = {
1783                     {1,64}, {1,32}, {1,16}, {1,8}, {1,4}, {1,3}, {1,2}, {2,3},
1784                     {1,1},
1785                     {3,2}, {2,1}, {3,1}, {4,1}, {8,1}, {16,1}, {32,1}, {64,1},
1786                     {0,0}
1787                 };
1788                 int i_error;
1789                 int i_idx;
1790                 int i;
1791
1792                 i_rate_sign = p_input->p->i_rate < 0 ? -1 : 1;
1793
1794                 i_error = INT_MAX;
1795                 i_idx = -1;
1796                 for( i = 0; ppi_factor[i][0] != 0; i++ )
1797                 {
1798                     const int i_test_r = INPUT_RATE_DEFAULT * ppi_factor[i][0] / ppi_factor[i][1];
1799                     const int i_test_e = abs( abs( p_input->p->i_rate ) - i_test_r );
1800                     if( i_test_e < i_error )
1801                     {
1802                         i_idx = i;
1803                         i_error = i_test_e;
1804                     }
1805                 }
1806
1807                 assert( i_idx >= 0 && ppi_factor[i_idx][0] != 0 );
1808
1809                 if( i_type == INPUT_CONTROL_SET_RATE_SLOWER )
1810                 {
1811                     if( ppi_factor[i_idx+1][0] > 0 )
1812                         i_rate = INPUT_RATE_DEFAULT * ppi_factor[i_idx+1][0] / ppi_factor[i_idx+1][1];
1813                     else
1814                         i_rate = INPUT_RATE_MAX+1;
1815                 }
1816                 else
1817                 {
1818                     assert( i_type == INPUT_CONTROL_SET_RATE_FASTER );
1819                     if( i_idx > 0 )
1820                         i_rate = INPUT_RATE_DEFAULT * ppi_factor[i_idx-1][0] / ppi_factor[i_idx-1][1];
1821                     else
1822                         i_rate = INPUT_RATE_MIN-1;
1823                 }
1824             }
1825
1826             /* Check rate bound */
1827             if( i_rate < INPUT_RATE_MIN )
1828             {
1829                 msg_Dbg( p_input, "cannot set rate faster" );
1830                 i_rate = INPUT_RATE_MIN;
1831             }
1832             else if( i_rate > INPUT_RATE_MAX )
1833             {
1834                 msg_Dbg( p_input, "cannot set rate slower" );
1835                 i_rate = INPUT_RATE_MAX;
1836             }
1837
1838             /* Apply direction */
1839             if( i_rate_sign < 0 )
1840             {
1841                 if( p_input->p->input.b_rescale_ts )
1842                 {
1843                     msg_Dbg( p_input, "cannot set negative rate" );
1844                     i_rate = p_input->p->i_rate;
1845                     assert( i_rate > 0 );
1846                 }
1847                 else
1848                 {
1849                     i_rate *= i_rate_sign;
1850                 }
1851             }
1852
1853             if( i_rate != INPUT_RATE_DEFAULT &&
1854                 ( ( !p_input->p->b_can_rate_control && !p_input->p->input.b_rescale_ts ) ||
1855                   ( p_input->p->p_sout && !p_input->p->b_out_pace_control ) ) )
1856             {
1857                 msg_Dbg( p_input, "cannot change rate" );
1858                 i_rate = INPUT_RATE_DEFAULT;
1859             }
1860             if( i_rate != p_input->p->i_rate &&
1861                 !p_input->p->b_can_pace_control && p_input->p->b_can_rate_control )
1862             {
1863                 int i_ret;
1864                 if( p_input->p->input.p_access )
1865                 {
1866                     i_ret = VLC_EGENERIC;
1867                 }
1868                 else
1869                 {
1870                     if( !p_input->p->input.b_rescale_ts )
1871                         es_out_Control( p_input->p->p_es_out, ES_OUT_RESET_PCR );
1872
1873                     i_ret = demux_Control( p_input->p->input.p_demux,
1874                                             DEMUX_SET_RATE, &i_rate );
1875                 }
1876                 if( i_ret )
1877                 {
1878                     msg_Warn( p_input, "ACCESS/DEMUX_SET_RATE failed" );
1879                     i_rate = p_input->p->i_rate;
1880                 }
1881             }
1882
1883             /* */
1884             if( i_rate != p_input->p->i_rate )
1885             {
1886                 p_input->p->i_rate = i_rate;
1887                 input_SendEventRate( p_input, i_rate );
1888
1889                 if( p_input->p->input.b_rescale_ts )
1890                 {
1891                     const int i_rate_source = (p_input->p->b_can_pace_control || p_input->p->b_can_rate_control ) ? i_rate : INPUT_RATE_DEFAULT;
1892                     es_out_SetRate( p_input->p->p_es_out, i_rate_source, i_rate );
1893                 }
1894
1895                 b_force_update = true;
1896             }
1897             break;
1898         }
1899
1900         case INPUT_CONTROL_SET_PROGRAM:
1901             /* No need to force update, es_out does it if needed */
1902             es_out_Control( p_input->p->p_es_out,
1903                             ES_OUT_SET_GROUP, val.i_int );
1904
1905             demux_Control( p_input->p->input.p_demux, DEMUX_SET_GROUP, val.i_int,
1906                             NULL );
1907             break;
1908
1909         case INPUT_CONTROL_SET_ES:
1910             /* No need to force update, es_out does it if needed */
1911             es_out_Control( p_input->p->p_es_out_display, ES_OUT_SET_ES_BY_ID, val.i_int );
1912             break;
1913
1914         case INPUT_CONTROL_RESTART_ES:
1915             es_out_Control( p_input->p->p_es_out_display, ES_OUT_RESTART_ES_BY_ID, val.i_int );
1916             break;
1917
1918         case INPUT_CONTROL_SET_AUDIO_DELAY:
1919             if( !es_out_SetDelay( p_input->p->p_es_out_display, AUDIO_ES, val.i_time ) )
1920             {
1921                 input_SendEventAudioDelay( p_input, val.i_time );
1922                 UpdatePtsDelay( p_input );
1923             }
1924             break;
1925
1926         case INPUT_CONTROL_SET_SPU_DELAY:
1927             if( !es_out_SetDelay( p_input->p->p_es_out_display, SPU_ES, val.i_time ) )
1928             {
1929                 input_SendEventSubtitleDelay( p_input, val.i_time );
1930                 UpdatePtsDelay( p_input );
1931             }
1932             break;
1933
1934         case INPUT_CONTROL_SET_TITLE:
1935         case INPUT_CONTROL_SET_TITLE_NEXT:
1936         case INPUT_CONTROL_SET_TITLE_PREV:
1937             if( p_input->p->b_recording )
1938             {
1939                 msg_Err( p_input, "INPUT_CONTROL_SET_TITLE(*) ignored while recording" );
1940                 break;
1941             }
1942             if( p_input->p->input.b_title_demux &&
1943                 p_input->p->input.i_title > 0 )
1944             {
1945                 /* TODO */
1946                 /* FIXME handle demux title */
1947                 demux_t *p_demux = p_input->p->input.p_demux;
1948                 int i_title;
1949
1950                 if( i_type == INPUT_CONTROL_SET_TITLE_PREV )
1951                     i_title = p_demux->info.i_title - 1;
1952                 else if( i_type == INPUT_CONTROL_SET_TITLE_NEXT )
1953                     i_title = p_demux->info.i_title + 1;
1954                 else
1955                     i_title = val.i_int;
1956
1957                 if( i_title >= 0 && i_title < p_input->p->input.i_title )
1958                 {
1959                     es_out_SetTime( p_input->p->p_es_out, -1 );
1960
1961                     demux_Control( p_demux, DEMUX_SET_TITLE, i_title );
1962                     input_SendEventTitle( p_input, i_title );
1963                 }
1964             }
1965             else if( p_input->p->input.i_title > 0 )
1966             {
1967                 access_t *p_access = p_input->p->input.p_access;
1968                 int i_title;
1969
1970                 if( i_type == INPUT_CONTROL_SET_TITLE_PREV )
1971                     i_title = p_access->info.i_title - 1;
1972                 else if( i_type == INPUT_CONTROL_SET_TITLE_NEXT )
1973                     i_title = p_access->info.i_title + 1;
1974                 else
1975                     i_title = val.i_int;
1976
1977                 if( i_title >= 0 && i_title < p_input->p->input.i_title )
1978                 {
1979                     es_out_SetTime( p_input->p->p_es_out, -1 );
1980
1981                     stream_Control( p_input->p->input.p_stream, STREAM_CONTROL_ACCESS,
1982                                     ACCESS_SET_TITLE, i_title );
1983                     input_SendEventTitle( p_input, i_title );
1984                 }
1985             }
1986             break;
1987         case INPUT_CONTROL_SET_SEEKPOINT:
1988         case INPUT_CONTROL_SET_SEEKPOINT_NEXT:
1989         case INPUT_CONTROL_SET_SEEKPOINT_PREV:
1990             if( p_input->p->b_recording )
1991             {
1992                 msg_Err( p_input, "INPUT_CONTROL_SET_SEEKPOINT(*) ignored while recording" );
1993                 break;
1994             }
1995
1996             if( p_input->p->input.b_title_demux &&
1997                 p_input->p->input.i_title > 0 )
1998             {
1999                 demux_t *p_demux = p_input->p->input.p_demux;
2000                 int i_seekpoint;
2001                 int64_t i_input_time;
2002                 int64_t i_seekpoint_time;
2003
2004                 if( i_type == INPUT_CONTROL_SET_SEEKPOINT_PREV )
2005                 {
2006                     i_seekpoint = p_demux->info.i_seekpoint;
2007                     i_seekpoint_time = p_input->p->input.title[p_demux->info.i_title]->seekpoint[i_seekpoint]->i_time_offset;
2008                     i_input_time = var_GetTime( p_input, "time" );
2009                     if( i_seekpoint_time >= 0 && i_input_time >= 0 )
2010                     {
2011                         if( i_input_time < i_seekpoint_time + 3000000 )
2012                             i_seekpoint--;
2013                     }
2014                     else
2015                         i_seekpoint--;
2016                 }
2017                 else if( i_type == INPUT_CONTROL_SET_SEEKPOINT_NEXT )
2018                     i_seekpoint = p_demux->info.i_seekpoint + 1;
2019                 else
2020                     i_seekpoint = val.i_int;
2021
2022                 if( i_seekpoint >= 0 && i_seekpoint <
2023                     p_input->p->input.title[p_demux->info.i_title]->i_seekpoint )
2024                 {
2025
2026                     es_out_SetTime( p_input->p->p_es_out, -1 );
2027
2028                     demux_Control( p_demux, DEMUX_SET_SEEKPOINT, i_seekpoint );
2029                     input_SendEventSeekpoint( p_input, p_demux->info.i_title, i_seekpoint );
2030                 }
2031             }
2032             else if( p_input->p->input.i_title > 0 )
2033             {
2034                 access_t *p_access = p_input->p->input.p_access;
2035                 int i_seekpoint;
2036                 int64_t i_input_time;
2037                 int64_t i_seekpoint_time;
2038
2039                 if( i_type == INPUT_CONTROL_SET_SEEKPOINT_PREV )
2040                 {
2041                     i_seekpoint = p_access->info.i_seekpoint;
2042                     i_seekpoint_time = p_input->p->input.title[p_access->info.i_title]->seekpoint[i_seekpoint]->i_time_offset;
2043                     i_input_time = var_GetTime( p_input, "time" );
2044                     if( i_seekpoint_time >= 0 && i_input_time >= 0 )
2045                     {
2046                         if( i_input_time < i_seekpoint_time + 3000000 )
2047                             i_seekpoint--;
2048                     }
2049                     else
2050                         i_seekpoint--;
2051                 }
2052                 else if( i_type == INPUT_CONTROL_SET_SEEKPOINT_NEXT )
2053                     i_seekpoint = p_access->info.i_seekpoint + 1;
2054                 else
2055                     i_seekpoint = val.i_int;
2056
2057                 if( i_seekpoint >= 0 && i_seekpoint <
2058                     p_input->p->input.title[p_access->info.i_title]->i_seekpoint )
2059                 {
2060                     es_out_SetTime( p_input->p->p_es_out, -1 );
2061
2062                     stream_Control( p_input->p->input.p_stream, STREAM_CONTROL_ACCESS,
2063                                     ACCESS_SET_SEEKPOINT, i_seekpoint );
2064                     input_SendEventSeekpoint( p_input, p_access->info.i_title, i_seekpoint );
2065                 }
2066             }
2067             break;
2068
2069         case INPUT_CONTROL_ADD_SUBTITLE:
2070             if( val.psz_string )
2071                 SubtitleAdd( p_input, val.psz_string, true );
2072             break;
2073
2074         case INPUT_CONTROL_ADD_SLAVE:
2075             if( val.psz_string )
2076             {
2077                 input_source_t *slave = InputSourceNew( p_input );
2078
2079                 if( slave && !InputSourceInit( p_input, slave, val.psz_string, NULL ) )
2080                 {
2081                     vlc_meta_t *p_meta;
2082                     int64_t i_time;
2083
2084                     /* Add the slave */
2085                     msg_Dbg( p_input, "adding %s as slave on the fly",
2086                              val.psz_string );
2087
2088                     /* Set position */
2089                     if( demux_Control( p_input->p->input.p_demux,
2090                                         DEMUX_GET_TIME, &i_time ) )
2091                     {
2092                         msg_Err( p_input, "demux doesn't like DEMUX_GET_TIME" );
2093                         InputSourceClean( slave );
2094                         free( slave );
2095                         break;
2096                     }
2097                     if( demux_Control( slave->p_demux,
2098                                        DEMUX_SET_TIME, i_time, true ) )
2099                     {
2100                         msg_Err( p_input, "seek failed for new slave" );
2101                         InputSourceClean( slave );
2102                         free( slave );
2103                         break;
2104                     }
2105
2106                     /* Get meta (access and demux) */
2107                     p_meta = vlc_meta_New();
2108                     if( p_meta )
2109                     {
2110                         access_Control( slave->p_access, ACCESS_GET_META, p_meta );
2111                         demux_Control( slave->p_demux, DEMUX_GET_META, p_meta );
2112                         InputUpdateMeta( p_input, p_meta );
2113                     }
2114
2115                     TAB_APPEND( p_input->p->i_slave, p_input->p->slave, slave );
2116                 }
2117                 else
2118                 {
2119                     free( slave );
2120                     msg_Warn( p_input, "failed to add %s as slave",
2121                               val.psz_string );
2122                 }
2123             }
2124             break;
2125
2126         case INPUT_CONTROL_SET_RECORD_STATE:
2127             if( !!p_input->p->b_recording != !!val.b_bool )
2128             {
2129                 if( p_input->p->input.b_can_stream_record )
2130                 {
2131                     if( demux_Control( p_input->p->input.p_demux,
2132                                        DEMUX_SET_RECORD_STATE, val.b_bool ) )
2133                         val.b_bool = false;
2134                 }
2135                 else
2136                 {
2137                     if( es_out_SetRecordState( p_input->p->p_es_out_display, val.b_bool ) )
2138                         val.b_bool = false;
2139                 }
2140                 p_input->p->b_recording = val.b_bool;
2141
2142                 input_SendEventRecord( p_input, val.b_bool );
2143
2144                 b_force_update = true;
2145             }
2146             break;
2147
2148         case INPUT_CONTROL_SET_FRAME_NEXT:
2149             if( p_input->p->i_state == PAUSE_S )
2150             {
2151                 es_out_SetFrameNext( p_input->p->p_es_out );
2152             }
2153             else if( p_input->p->i_state == PLAYING_S )
2154             {
2155                 ControlPause( p_input, i_control_date );
2156             }
2157             else
2158             {
2159                 msg_Err( p_input, "invalid state for frame next" );
2160             }
2161             b_force_update = true;
2162             break;
2163
2164         case INPUT_CONTROL_SET_BOOKMARK:
2165         {
2166             seekpoint_t bookmark;
2167
2168             bookmark.i_time_offset = -1;
2169             bookmark.i_byte_offset = -1;
2170
2171             vlc_mutex_lock( &p_input->p->p_item->lock );
2172             if( val.i_int >= 0 && val.i_int < p_input->p->i_bookmark )
2173             {
2174                 const seekpoint_t *p_bookmark = p_input->p->pp_bookmark[val.i_int];
2175                 bookmark.i_time_offset = p_bookmark->i_time_offset;
2176                 bookmark.i_byte_offset = p_bookmark->i_byte_offset;
2177             }
2178             vlc_mutex_unlock( &p_input->p->p_item->lock );
2179
2180             if( bookmark.i_time_offset < 0 && bookmark.i_byte_offset < 0 )
2181             {
2182                 msg_Err( p_input, "invalid bookmark %d", val.i_int );
2183                 break;
2184             }
2185
2186             if( bookmark.i_time_offset >= 0 )
2187             {
2188                 val.i_time = bookmark.i_time_offset;
2189                 b_force_update = Control( p_input, INPUT_CONTROL_SET_TIME, val );
2190             }
2191             else if( bookmark.i_byte_offset >= 0 &&
2192                      p_input->p->input.p_stream )
2193             {
2194                 const uint64_t i_size = stream_Size( p_input->p->input.p_stream );
2195                 if( i_size > 0 && bookmark.i_byte_offset <= i_size )
2196                 {
2197                     val.f_float = (double)bookmark.i_byte_offset / i_size;
2198                     b_force_update = Control( p_input, INPUT_CONTROL_SET_POSITION, val );
2199                 }
2200             }
2201             break;
2202         }
2203
2204         default:
2205             msg_Err( p_input, "not yet implemented" );
2206             break;
2207     }
2208
2209     ControlRelease( i_type, val );
2210     return b_force_update;
2211 }
2212
2213 /*****************************************************************************
2214  * UpdateTitleSeekpoint
2215  *****************************************************************************/
2216 static int UpdateTitleSeekpoint( input_thread_t *p_input,
2217                                  int i_title, int i_seekpoint )
2218 {
2219     int i_title_end = p_input->p->input.i_title_end -
2220                         p_input->p->input.i_title_offset;
2221     int i_seekpoint_end = p_input->p->input.i_seekpoint_end -
2222                             p_input->p->input.i_seekpoint_offset;
2223
2224     if( i_title_end >= 0 && i_seekpoint_end >= 0 )
2225     {
2226         if( i_title > i_title_end ||
2227             ( i_title == i_title_end && i_seekpoint > i_seekpoint_end ) )
2228             return 0;
2229     }
2230     else if( i_seekpoint_end >= 0 )
2231     {
2232         if( i_seekpoint > i_seekpoint_end )
2233             return 0;
2234     }
2235     else if( i_title_end >= 0 )
2236     {
2237         if( i_title > i_title_end )
2238             return 0;
2239     }
2240     return 1;
2241 }
2242 /*****************************************************************************
2243  * Update*FromDemux:
2244  *****************************************************************************/
2245 static int UpdateTitleSeekpointFromDemux( input_thread_t *p_input )
2246 {
2247     demux_t *p_demux = p_input->p->input.p_demux;
2248
2249     /* TODO event-like */
2250     if( p_demux->info.i_update & INPUT_UPDATE_TITLE )
2251     {
2252         input_SendEventTitle( p_input, p_demux->info.i_title );
2253
2254         p_demux->info.i_update &= ~INPUT_UPDATE_TITLE;
2255     }
2256     if( p_demux->info.i_update & INPUT_UPDATE_SEEKPOINT )
2257     {
2258         input_SendEventSeekpoint( p_input,
2259                                   p_demux->info.i_title, p_demux->info.i_seekpoint );
2260
2261         p_demux->info.i_update &= ~INPUT_UPDATE_SEEKPOINT;
2262     }
2263
2264     /* Hmmm only works with master input */
2265     if( p_input->p->input.p_demux == p_demux )
2266         return UpdateTitleSeekpoint( p_input,
2267                                      p_demux->info.i_title,
2268                                      p_demux->info.i_seekpoint );
2269     return 1;
2270 }
2271
2272 static void UpdateGenericFromDemux( input_thread_t *p_input )
2273 {
2274     demux_t *p_demux = p_input->p->input.p_demux;
2275
2276     if( p_demux->info.i_update & INPUT_UPDATE_META )
2277     {
2278         vlc_meta_t *p_meta = vlc_meta_New();
2279         if( p_meta )
2280         {
2281             demux_Control( p_input->p->input.p_demux, DEMUX_GET_META, p_meta );
2282             InputUpdateMeta( p_input, p_meta );
2283         }
2284         p_demux->info.i_update &= ~INPUT_UPDATE_META;
2285     }
2286
2287     p_demux->info.i_update &= ~INPUT_UPDATE_SIZE;
2288 }
2289
2290
2291 /*****************************************************************************
2292  * Update*FromAccess:
2293  *****************************************************************************/
2294 static int UpdateTitleSeekpointFromAccess( input_thread_t *p_input )
2295 {
2296     access_t *p_access = p_input->p->input.p_access;
2297
2298     if( p_access->info.i_update & INPUT_UPDATE_TITLE )
2299     {
2300         input_SendEventTitle( p_input, p_access->info.i_title );
2301
2302         stream_Control( p_input->p->input.p_stream, STREAM_UPDATE_SIZE );
2303
2304         p_access->info.i_update &= ~INPUT_UPDATE_TITLE;
2305     }
2306     if( p_access->info.i_update & INPUT_UPDATE_SEEKPOINT )
2307     {
2308         input_SendEventSeekpoint( p_input,
2309                                   p_access->info.i_title, p_access->info.i_seekpoint );
2310
2311         p_access->info.i_update &= ~INPUT_UPDATE_SEEKPOINT;
2312     }
2313     /* Hmmm only works with master input */
2314     if( p_input->p->input.p_access == p_access )
2315         return UpdateTitleSeekpoint( p_input,
2316                                      p_access->info.i_title,
2317                                      p_access->info.i_seekpoint );
2318     return 1;
2319 }
2320 static void UpdateGenericFromAccess( input_thread_t *p_input )
2321 {
2322     access_t *p_access = p_input->p->input.p_access;
2323
2324     if( p_access->info.i_update & INPUT_UPDATE_META )
2325     {
2326         /* TODO maybe multi - access ? */
2327         vlc_meta_t *p_meta = vlc_meta_New();
2328         if( p_meta )
2329         {
2330             access_Control( p_input->p->input.p_access, ACCESS_GET_META, p_meta );
2331             InputUpdateMeta( p_input, p_meta );
2332         }
2333         p_access->info.i_update &= ~INPUT_UPDATE_META;
2334     }
2335     if( p_access->info.i_update & INPUT_UPDATE_SIGNAL )
2336     {
2337         double f_quality;
2338         double f_strength;
2339
2340         if( access_Control( p_access, ACCESS_GET_SIGNAL, &f_quality, &f_strength ) )
2341             f_quality = f_strength = -1;
2342
2343         input_SendEventSignal( p_input, f_quality, f_strength );
2344
2345         p_access->info.i_update &= ~INPUT_UPDATE_SIGNAL;
2346     }
2347
2348     p_access->info.i_update &= ~INPUT_UPDATE_SIZE;
2349 }
2350
2351 /*****************************************************************************
2352  * InputSourceNew:
2353  *****************************************************************************/
2354 static input_source_t *InputSourceNew( input_thread_t *p_input )
2355 {
2356     VLC_UNUSED(p_input);
2357
2358     return calloc( 1,  sizeof( input_source_t ) );
2359 }
2360
2361 /*****************************************************************************
2362  * InputSourceInit:
2363  *****************************************************************************/
2364 static int InputSourceInit( input_thread_t *p_input,
2365                             input_source_t *in, const char *psz_mrl,
2366                             const char *psz_forced_demux )
2367 {
2368     const char *psz_access;
2369     const char *psz_demux;
2370     char *psz_path;
2371     char *psz_var_demux = NULL;
2372     double f_fps;
2373
2374     assert( psz_mrl );
2375     char *psz_dup = strdup( psz_mrl );
2376
2377     if( psz_dup == NULL )
2378         goto error;
2379
2380     /* Split uri */
2381     input_SplitMRL( &psz_access, &psz_demux, &psz_path, psz_dup );
2382
2383     /* FIXME: file:// handling plugins do not support URIs properly...
2384      * So we pre-decode the URI to a path for them. Note that we do not do it
2385      * for non-standard VLC-specific schemes. */
2386     if( !strcmp( psz_access, "file" ) )
2387     {
2388         if( psz_path[0] != '/'
2389 #if (DIR_SEP_CHAR != '/')
2390             /* We accept invalid URIs too. */
2391             && psz_path[0] != DIR_SEP_CHAR
2392 #endif
2393           )
2394         {   /* host specified -> only localhost is supported */
2395             static const size_t i_localhost = sizeof("localhost")-1;
2396             if( strncmp( psz_path, "localhost/", i_localhost + 1) != 0 )
2397             {
2398                 msg_Err( p_input, "cannot open remote file `%s://%s'",
2399                          psz_access, psz_path );
2400                 msg_Info( p_input, "Did you mean `%s:///%s'?",
2401                           psz_access, psz_path );
2402                 goto error;
2403             }
2404             psz_path += i_localhost;
2405         }
2406         /* Remove HTML anchor if present (not supported). */
2407         char *p = strchr( psz_path, '#' );
2408         if( p )
2409             *p = '\0';
2410         /* Then URI-decode the path. */
2411         decode_URI( psz_path );
2412 #if defined( WIN32 ) && !defined( UNDER_CE )
2413         /* Strip leading slash in front of the drive letter */
2414         psz_path++;
2415 #endif
2416 #if (DIR_SEP_CHAR != '/')
2417         /* Turn slashes into anti-slashes */
2418         for( char *s = strchr( psz_path, '/' ); s; s = strchr( s + 1, '/' ) )
2419             *s = DIR_SEP_CHAR;
2420 #endif
2421     }
2422
2423     msg_Dbg( p_input, "`%s' gives access `%s' demux `%s' path `%s'",
2424              psz_mrl, psz_access, psz_demux, psz_path );
2425     if( !p_input->b_preparsing )
2426     {
2427         /* Hack to allow udp://@:port syntax */
2428         if( !psz_access ||
2429             (strncmp( psz_access, "udp", 3 ) &&
2430              strncmp( psz_access, "rtp", 3 )) )
2431         {
2432             /* Find optional titles and seekpoints */
2433             MRLSections( p_input, psz_path, &in->i_title_start, &in->i_title_end,
2434                      &in->i_seekpoint_start, &in->i_seekpoint_end );
2435         }
2436
2437         if( psz_forced_demux && *psz_forced_demux )
2438         {
2439             psz_demux = psz_forced_demux;
2440         }
2441         else if( *psz_demux == '\0' )
2442         {
2443             /* special hack for forcing a demuxer with --demux=module
2444              * (and do nothing with a list) */
2445             psz_var_demux = var_GetNonEmptyString( p_input, "demux" );
2446
2447             if( psz_var_demux != NULL &&
2448                 !strchr(psz_var_demux, ',' ) &&
2449                 !strchr(psz_var_demux, ':' ) )
2450             {
2451                 psz_demux = psz_var_demux;
2452
2453                 msg_Dbg( p_input, "enforced demux ` %s'", psz_demux );
2454             }
2455         }
2456
2457         /* Try access_demux first */
2458         in->p_demux = demux_New( p_input, p_input, psz_access, psz_demux, psz_path,
2459                                   NULL, p_input->p->p_es_out, false );
2460     }
2461     else
2462     {
2463         /* Preparsing is only for file:// */
2464         if( *psz_demux )
2465             goto error;
2466         if( !*psz_access ) /* path without scheme:// */
2467             psz_access = "file";
2468         if( strcmp( psz_access, "file" ) )
2469             goto error;
2470         msg_Dbg( p_input, "trying to pre-parse %s",  psz_path );
2471     }
2472
2473     if( in->p_demux )
2474     {
2475         /* Get infos from access_demux */
2476         int i_ret = demux_Control( in->p_demux,
2477                                    DEMUX_GET_PTS_DELAY, &in->i_pts_delay );
2478         assert( !i_ret );
2479         in->i_pts_delay = __MAX( 0, __MIN( in->i_pts_delay, INPUT_PTS_DELAY_MAX ) );
2480
2481
2482         in->b_title_demux = true;
2483         if( demux_Control( in->p_demux, DEMUX_GET_TITLE_INFO,
2484                             &in->title, &in->i_title,
2485                             &in->i_title_offset, &in->i_seekpoint_offset ) )
2486         {
2487             TAB_INIT( in->i_title, in->title );
2488         }
2489         if( demux_Control( in->p_demux, DEMUX_CAN_CONTROL_PACE,
2490                             &in->b_can_pace_control ) )
2491             in->b_can_pace_control = false;
2492
2493         assert( in->p_demux->pf_demux != NULL || !in->b_can_pace_control );
2494
2495         if( !in->b_can_pace_control )
2496         {
2497             if( demux_Control( in->p_demux, DEMUX_CAN_CONTROL_RATE,
2498                                 &in->b_can_rate_control, &in->b_rescale_ts ) )
2499             {
2500                 in->b_can_rate_control = false;
2501                 in->b_rescale_ts = true; /* not used */
2502             }
2503         }
2504         else
2505         {
2506             in->b_can_rate_control = true;
2507             in->b_rescale_ts = true;
2508         }
2509         if( demux_Control( in->p_demux, DEMUX_CAN_PAUSE,
2510                             &in->b_can_pause ) )
2511             in->b_can_pause = false;
2512         var_SetBool( p_input, "can-pause", in->b_can_pause || !in->b_can_pace_control ); /* XXX temporary because of es_out_timeshift*/
2513         var_SetBool( p_input, "can-rate", !in->b_can_pace_control || in->b_can_rate_control ); /* XXX temporary because of es_out_timeshift*/
2514         var_SetBool( p_input, "can-rewind", !in->b_rescale_ts && !in->b_can_pace_control && in->b_can_rate_control );
2515
2516         bool b_can_seek;
2517         if( demux_Control( in->p_demux, DEMUX_CAN_SEEK, &b_can_seek ) )
2518             b_can_seek = false;
2519         var_SetBool( p_input, "can-seek", b_can_seek );
2520     }
2521     else
2522     {
2523         /* Now try a real access */
2524         in->p_access = access_New( p_input, p_input, psz_access, psz_demux, psz_path );
2525         if( in->p_access == NULL )
2526         {
2527             if( vlc_object_alive( p_input ) )
2528             {
2529                 msg_Err( p_input, "open of `%s' failed: %s", psz_mrl,
2530                                                              msg_StackMsg() );
2531                 dialog_Fatal( p_input, _("Your input can't be opened"),
2532                               _("VLC is unable to open the MRL '%s'."
2533                                 " Check the log for details."), psz_mrl );
2534             }
2535             goto error;
2536         }
2537
2538         /* Get infos from access */
2539         if( !p_input->b_preparsing )
2540         {
2541             bool b_can_seek;
2542             access_Control( in->p_access,
2543                              ACCESS_GET_PTS_DELAY, &in->i_pts_delay );
2544             in->i_pts_delay = __MAX( 0, __MIN( in->i_pts_delay, INPUT_PTS_DELAY_MAX ) );
2545
2546             in->b_title_demux = false;
2547             if( access_Control( in->p_access, ACCESS_GET_TITLE_INFO,
2548                                  &in->title, &in->i_title,
2549                                 &in->i_title_offset, &in->i_seekpoint_offset ) )
2550
2551             {
2552                 TAB_INIT( in->i_title, in->title );
2553             }
2554             access_Control( in->p_access, ACCESS_CAN_CONTROL_PACE,
2555                              &in->b_can_pace_control );
2556             in->b_can_rate_control = in->b_can_pace_control;
2557             in->b_rescale_ts = true;
2558
2559             access_Control( in->p_access, ACCESS_CAN_PAUSE, &in->b_can_pause );
2560             var_SetBool( p_input, "can-pause", in->b_can_pause || !in->b_can_pace_control ); /* XXX temporary because of es_out_timeshift*/
2561             var_SetBool( p_input, "can-rate", !in->b_can_pace_control || in->b_can_rate_control ); /* XXX temporary because of es_out_timeshift*/
2562             var_SetBool( p_input, "can-rewind", !in->b_rescale_ts && !in->b_can_pace_control );
2563
2564             access_Control( in->p_access, ACCESS_CAN_SEEK, &b_can_seek );
2565             var_SetBool( p_input, "can-seek", b_can_seek );
2566         }
2567
2568         /* */
2569         int  i_input_list;
2570         char **ppsz_input_list;
2571
2572         TAB_INIT( i_input_list, ppsz_input_list );
2573
2574         /* On master stream only, use input-list */
2575         if( &p_input->p->input == in )
2576         {
2577             char *psz_list;
2578             char *psz_parser;
2579
2580             psz_list =
2581             psz_parser = var_CreateGetNonEmptyString( p_input, "input-list" );
2582
2583             while( psz_parser && *psz_parser )
2584             {
2585                 char *p = strchr( psz_parser, ',' );
2586                 if( p )
2587                     *p++ = '\0';
2588
2589                 if( *psz_parser )
2590                 {
2591                     char *psz_name = strdup( psz_parser );
2592                     if( psz_name )
2593                         TAB_APPEND( i_input_list, ppsz_input_list, psz_name );
2594                 }
2595
2596                 psz_parser = p;
2597             }
2598             free( psz_list );
2599         }
2600         /* Autodetect extra files if none specified */
2601         if( i_input_list <= 0 )
2602         {
2603             InputGetExtraFiles( p_input, &i_input_list, &ppsz_input_list,
2604                                 psz_access, psz_path );
2605         }
2606         if( i_input_list > 0 )
2607             TAB_APPEND( i_input_list, ppsz_input_list, NULL );
2608
2609         /* Create the stream_t */
2610         in->p_stream = stream_AccessNew( in->p_access, ppsz_input_list );
2611         if( ppsz_input_list )
2612         {
2613             for( int i = 0; ppsz_input_list[i] != NULL; i++ )
2614                 free( ppsz_input_list[i] );
2615             TAB_CLEAN( i_input_list, ppsz_input_list );
2616         }
2617
2618         if( in->p_stream == NULL )
2619         {
2620             msg_Warn( p_input, "cannot create a stream_t from access" );
2621             goto error;
2622         }
2623
2624         /* Add stream filters */
2625         char *psz_stream_filter = var_GetNonEmptyString( p_input,
2626                                                          "stream-filter" );
2627         in->p_stream = stream_FilterChainNew( in->p_stream,
2628                                               psz_stream_filter,
2629                                               var_GetBool( p_input, "input-record-native" ) );
2630         free( psz_stream_filter );
2631
2632         /* Open a demuxer */
2633         if( *psz_demux == '\0' && *in->p_access->psz_demux )
2634         {
2635             psz_demux = in->p_access->psz_demux;
2636         }
2637
2638         {
2639             /* Take access/stream redirections into account */
2640             char *psz_real_path;
2641             char *psz_buf = NULL;
2642             if( in->p_stream->psz_path )
2643             {
2644                 const char *psz_a, *psz_d;
2645                 psz_buf = strdup( in->p_stream->psz_path );
2646                 input_SplitMRL( &psz_a, &psz_d, &psz_real_path, psz_buf );
2647             }
2648             else
2649             {
2650                 psz_real_path = psz_path;
2651             }
2652             in->p_demux = demux_New( p_input, p_input, psz_access, psz_demux,
2653                                       psz_real_path,
2654                                       in->p_stream, p_input->p->p_es_out,
2655                                       p_input->b_preparsing );
2656             free( psz_buf );
2657         }
2658
2659         if( in->p_demux == NULL )
2660         {
2661             if( vlc_object_alive( p_input ) )
2662             {
2663                 msg_Err( p_input, "no suitable demux module for `%s/%s://%s'",
2664                          psz_access, psz_demux, psz_path );
2665                 dialog_Fatal( VLC_OBJECT( p_input ),
2666                               _("VLC can't recognize the input's format"),
2667                               _("The format of '%s' cannot be detected. "
2668                                 "Have a look at the log for details."), psz_mrl );
2669             }
2670             goto error;
2671         }
2672         assert( in->p_demux->pf_demux != NULL );
2673
2674         /* Get title from demux */
2675         if( !p_input->b_preparsing && in->i_title <= 0 )
2676         {
2677             if( demux_Control( in->p_demux, DEMUX_GET_TITLE_INFO,
2678                                 &in->title, &in->i_title,
2679                                 &in->i_title_offset, &in->i_seekpoint_offset ))
2680             {
2681                 TAB_INIT( in->i_title, in->title );
2682             }
2683             else
2684             {
2685                 in->b_title_demux = true;
2686             }
2687         }
2688     }
2689
2690     free( psz_var_demux );
2691     free( psz_dup );
2692
2693     /* Set record capabilities */
2694     if( demux_Control( in->p_demux, DEMUX_CAN_RECORD, &in->b_can_stream_record ) )
2695         in->b_can_stream_record = false;
2696 #ifdef ENABLE_SOUT
2697     if( !var_GetBool( p_input, "input-record-native" ) )
2698         in->b_can_stream_record = false;
2699     var_SetBool( p_input, "can-record", true );
2700 #else
2701     var_SetBool( p_input, "can-record", in->b_can_stream_record );
2702 #endif
2703
2704     /* get attachment
2705      * FIXME improve for b_preparsing: move it after GET_META and check psz_arturl */
2706     if( 1 || !p_input->b_preparsing )
2707     {
2708         int i_attachment;
2709         input_attachment_t **attachment;
2710         if( !demux_Control( in->p_demux, DEMUX_GET_ATTACHMENTS,
2711                              &attachment, &i_attachment ) )
2712         {
2713             vlc_mutex_lock( &p_input->p->p_item->lock );
2714             AppendAttachment( &p_input->p->i_attachment, &p_input->p->attachment,
2715                               i_attachment, attachment );
2716             vlc_mutex_unlock( &p_input->p->p_item->lock );
2717         }
2718     }
2719     if( !demux_Control( in->p_demux, DEMUX_GET_FPS, &f_fps ) && f_fps > 0.0 )
2720     {
2721         vlc_mutex_lock( &p_input->p->p_item->lock );
2722         p_input->p->f_fps = f_fps;
2723         vlc_mutex_unlock( &p_input->p->p_item->lock );
2724     }
2725
2726     if( var_GetInteger( p_input, "clock-synchro" ) != -1 )
2727         in->b_can_pace_control = !var_GetInteger( p_input, "clock-synchro" );
2728
2729     return VLC_SUCCESS;
2730
2731 error:
2732     if( in->p_demux )
2733         demux_Delete( in->p_demux );
2734
2735     if( in->p_stream )
2736         stream_Delete( in->p_stream );
2737
2738     if( in->p_access )
2739         access_Delete( in->p_access );
2740
2741     free( psz_var_demux );
2742     free( psz_dup );
2743
2744     return VLC_EGENERIC;
2745 }
2746
2747 /*****************************************************************************
2748  * InputSourceClean:
2749  *****************************************************************************/
2750 static void InputSourceClean( input_source_t *in )
2751 {
2752     int i;
2753
2754     if( in->p_demux )
2755         demux_Delete( in->p_demux );
2756
2757     if( in->p_stream )
2758         stream_Delete( in->p_stream );
2759
2760     if( in->p_access )
2761         access_Delete( in->p_access );
2762
2763     if( in->i_title > 0 )
2764     {
2765         for( i = 0; i < in->i_title; i++ )
2766             vlc_input_title_Delete( in->title[i] );
2767         TAB_CLEAN( in->i_title, in->title );
2768     }
2769 }
2770
2771 /*****************************************************************************
2772  * InputSourceMeta:
2773  *****************************************************************************/
2774 static void InputSourceMeta( input_thread_t *p_input,
2775                              input_source_t *p_source, vlc_meta_t *p_meta )
2776 {
2777     access_t *p_access = p_source->p_access;
2778     demux_t *p_demux = p_source->p_demux;
2779
2780     /* XXX Remember that checking against p_item->p_meta->i_status & ITEM_PREPARSED
2781      * is a bad idea */
2782
2783     bool has_meta;
2784
2785     /* Read access meta */
2786     has_meta = p_access && !access_Control( p_access, ACCESS_GET_META, p_meta );
2787
2788     /* Read demux meta */
2789     has_meta |= !demux_Control( p_demux, DEMUX_GET_META, p_meta );
2790
2791     bool has_unsupported;
2792     if( demux_Control( p_demux, DEMUX_HAS_UNSUPPORTED_META, &has_unsupported ) )
2793         has_unsupported = true;
2794
2795     /* If the demux report unsupported meta data, or if we don't have meta data
2796      * try an external "meta reader" */
2797     if( has_meta && !has_unsupported )
2798         return;
2799
2800     demux_meta_t *p_demux_meta =
2801         vlc_custom_create( p_demux, sizeof( *p_demux_meta ),
2802                            VLC_OBJECT_GENERIC, "demux meta" );
2803     if( !p_demux_meta )
2804         return;
2805     vlc_object_attach( p_demux_meta, p_demux );
2806     p_demux_meta->p_demux = p_demux;
2807     p_demux_meta->p_item = p_input->p->p_item;
2808
2809     module_t *p_id3 = module_need( p_demux_meta, "meta reader", NULL, false );
2810     if( p_id3 )
2811     {
2812         if( p_demux_meta->p_meta )
2813         {
2814             vlc_meta_Merge( p_meta, p_demux_meta->p_meta );
2815             vlc_meta_Delete( p_demux_meta->p_meta );
2816         }
2817
2818         if( p_demux_meta->i_attachments > 0 )
2819         {
2820             vlc_mutex_lock( &p_input->p->p_item->lock );
2821             AppendAttachment( &p_input->p->i_attachment, &p_input->p->attachment,
2822                               p_demux_meta->i_attachments, p_demux_meta->attachments );
2823             vlc_mutex_unlock( &p_input->p->p_item->lock );
2824         }
2825         module_unneed( p_demux, p_id3 );
2826     }
2827     vlc_object_release( p_demux_meta );
2828 }
2829
2830
2831 static void SlaveDemux( input_thread_t *p_input, bool *pb_demux_polled )
2832 {
2833     int64_t i_time;
2834     int i;
2835
2836     *pb_demux_polled = false;
2837     if( demux_Control( p_input->p->input.p_demux, DEMUX_GET_TIME, &i_time ) )
2838     {
2839         msg_Err( p_input, "demux doesn't like DEMUX_GET_TIME" );
2840         return;
2841     }
2842
2843     for( i = 0; i < p_input->p->i_slave; i++ )
2844     {
2845         input_source_t *in = p_input->p->slave[i];
2846         int i_ret;
2847
2848         if( in->b_eof )
2849             continue;
2850
2851         const bool b_demux_polled = in->p_demux->pf_demux != NULL;
2852         if( !b_demux_polled )
2853             continue;
2854
2855         *pb_demux_polled = true;
2856
2857         /* Call demux_Demux until we have read enough data */
2858         if( demux_Control( in->p_demux, DEMUX_SET_NEXT_DEMUX_TIME, i_time ) )
2859         {
2860             for( ;; )
2861             {
2862                 int64_t i_stime;
2863                 if( demux_Control( in->p_demux, DEMUX_GET_TIME, &i_stime ) )
2864                 {
2865                     msg_Err( p_input, "slave[%d] doesn't like "
2866                              "DEMUX_GET_TIME -> EOF", i );
2867                     i_ret = 0;
2868                     break;
2869                 }
2870
2871                 if( i_stime >= i_time )
2872                 {
2873                     i_ret = 1;
2874                     break;
2875                 }
2876
2877                 if( ( i_ret = demux_Demux( in->p_demux ) ) <= 0 )
2878                     break;
2879             }
2880         }
2881         else
2882         {
2883             i_ret = demux_Demux( in->p_demux );
2884         }
2885
2886         if( i_ret <= 0 )
2887         {
2888             msg_Dbg( p_input, "slave %d EOF", i );
2889             in->b_eof = true;
2890         }
2891     }
2892 }
2893
2894 static void SlaveSeek( input_thread_t *p_input )
2895 {
2896     int64_t i_time;
2897     int i;
2898
2899     if( demux_Control( p_input->p->input.p_demux, DEMUX_GET_TIME, &i_time ) )
2900     {
2901         msg_Err( p_input, "demux doesn't like DEMUX_GET_TIME" );
2902         return;
2903     }
2904
2905     for( i = 0; i < p_input->p->i_slave; i++ )
2906     {
2907         input_source_t *in = p_input->p->slave[i];
2908
2909         if( demux_Control( in->p_demux, DEMUX_SET_TIME, i_time, true ) )
2910         {
2911             if( !in->b_eof )
2912                 msg_Err( p_input, "seek failed for slave %d -> EOF", i );
2913             in->b_eof = true;
2914         }
2915         else
2916         {
2917             in->b_eof = false;
2918         }
2919     }
2920 }
2921
2922 /*****************************************************************************
2923  * InputMetaUser:
2924  *****************************************************************************/
2925 static void InputMetaUser( input_thread_t *p_input, vlc_meta_t *p_meta )
2926 {
2927     static const struct { int i_meta; const char *psz_name; } p_list[] = {
2928         { vlc_meta_Title,       "meta-title" },
2929         { vlc_meta_Artist,      "meta-artist" },
2930         { vlc_meta_Genre,       "meta-genre" },
2931         { vlc_meta_Copyright,   "meta-copyright" },
2932         { vlc_meta_Description, "meta-description" },
2933         { vlc_meta_Date,        "meta-date" },
2934         { vlc_meta_URL,         "meta-url" },
2935         { 0, NULL }
2936     };
2937
2938     /* Get meta information from user */
2939     for( int i = 0; p_list[i].psz_name; i++ )
2940     {
2941         char *psz_string = var_GetNonEmptyString( p_input, p_list[i].psz_name );
2942         if( !psz_string )
2943             continue;
2944
2945         EnsureUTF8( psz_string );
2946         vlc_meta_Set( p_meta, p_list[i].i_meta, psz_string );
2947         free( psz_string );
2948     }
2949 }
2950
2951 /*****************************************************************************
2952  * InputUpdateMeta: merge p_item meta data with p_meta taking care of
2953  * arturl and locking issue.
2954  *****************************************************************************/
2955 static void InputUpdateMeta( input_thread_t *p_input, vlc_meta_t *p_meta )
2956 {
2957     es_out_ControlSetMeta( p_input->p->p_es_out, p_meta );
2958     vlc_meta_Delete( p_meta );
2959 }
2960
2961 static void AppendAttachment( int *pi_attachment, input_attachment_t ***ppp_attachment,
2962                               int i_new, input_attachment_t **pp_new )
2963 {
2964     int i_attachment = *pi_attachment;
2965     input_attachment_t **attachment = *ppp_attachment;
2966     int i;
2967
2968     attachment = xrealloc( attachment,
2969                     sizeof(input_attachment_t**) * ( i_attachment + i_new ) );
2970     for( i = 0; i < i_new; i++ )
2971         attachment[i_attachment++] = pp_new[i];
2972     free( pp_new );
2973
2974     /* */
2975     *pi_attachment = i_attachment;
2976     *ppp_attachment = attachment;
2977 }
2978 /*****************************************************************************
2979  * InputGetExtraFiles
2980  *  Autodetect extra input list
2981  *****************************************************************************/
2982 static void InputGetExtraFilesPattern( input_thread_t *p_input,
2983                                        int *pi_list, char ***pppsz_list,
2984                                        const char *psz_path,
2985                                        const char *psz_match,
2986                                        const char *psz_format,
2987                                        int i_start, int i_stop )
2988 {
2989     int i_list;
2990     char **ppsz_list;
2991
2992     TAB_INIT( i_list, ppsz_list );
2993
2994     char *psz_base = strdup( psz_path );
2995     if( !psz_base )
2996         goto exit;
2997
2998     /* Remove the extension */
2999     char *psz_end = &psz_base[strlen(psz_base)-strlen(psz_match)];
3000     assert( psz_end >= psz_base);
3001     *psz_end = '\0';
3002
3003     /* Try to list files */
3004     for( int i = i_start; i <= i_stop; i++ )
3005     {
3006         struct stat st;
3007         char *psz_file;
3008
3009         if( asprintf( &psz_file, psz_format, psz_base, i ) < 0 )
3010             break;
3011
3012         if( utf8_stat( psz_file, &st ) || !S_ISREG( st.st_mode ) || !st.st_size )
3013         {
3014             free( psz_file );
3015             break;
3016         }
3017
3018         msg_Dbg( p_input, "Detected extra file `%s'", psz_file );
3019         TAB_APPEND( i_list, ppsz_list, psz_file );
3020     }
3021     free( psz_base );
3022 exit:
3023     *pi_list = i_list;
3024     *pppsz_list = ppsz_list;
3025 }
3026
3027 static void InputGetExtraFiles( input_thread_t *p_input,
3028                                 int *pi_list, char ***pppsz_list,
3029                                 const char *psz_access, const char *psz_path )
3030 {
3031     static const struct
3032     {
3033         const char *psz_match;
3034         const char *psz_format;
3035         int i_start;
3036         int i_stop;
3037     } p_pattern[] = {
3038         /* XXX the order is important */
3039         { ".001",         "%s.%.3d",        2, 999 },
3040         { ".part1.rar",   "%s.part%.1d.rar",2, 9 },
3041         { ".part01.rar",  "%s.part%.2d.rar",2, 99, },
3042         { ".part001.rar", "%s.part%.3d.rar",2, 999 },
3043         { ".rar",         "%s.r%.2d",       0, 99 },
3044         { NULL, NULL, 0, 0 }
3045     };
3046
3047     TAB_INIT( *pi_list, *pppsz_list );
3048
3049     if( ( psz_access && *psz_access && strcmp( psz_access, "file" ) ) || !psz_path )
3050         return;
3051
3052     const size_t i_path = strlen(psz_path);
3053
3054     for( int i = 0; p_pattern[i].psz_match != NULL; i++ )
3055     {
3056         const size_t i_ext = strlen(p_pattern[i].psz_match );
3057
3058         if( i_path < i_ext )
3059             continue;
3060         if( !strcmp( &psz_path[i_path-i_ext], p_pattern[i].psz_match ) )
3061         {
3062             InputGetExtraFilesPattern( p_input, pi_list, pppsz_list,
3063                                        psz_path,
3064                                        p_pattern[i].psz_match, p_pattern[i].psz_format,
3065                                        p_pattern[i].i_start, p_pattern[i].i_stop );
3066             return;
3067         }
3068     }
3069 }
3070
3071 /* */
3072 static void input_ChangeState( input_thread_t *p_input, int i_state )
3073 {
3074     const bool b_changed = p_input->p->i_state != i_state;
3075
3076     p_input->p->i_state = i_state;
3077     if( i_state == ERROR_S )
3078         p_input->b_error = true;
3079     else if( i_state == END_S )
3080         p_input->b_eof = true;
3081
3082     if( b_changed )
3083     {
3084         input_item_SetErrorWhenReading( p_input->p->p_item, p_input->b_error );
3085         input_SendEventState( p_input, i_state );
3086     }
3087 }
3088
3089
3090 /*****************************************************************************
3091  * MRLSplit: parse the access, demux and url part of the
3092  *           Media Resource Locator.
3093  *****************************************************************************/
3094 void input_SplitMRL( const char **ppsz_access, const char **ppsz_demux, char **ppsz_path,
3095                      char *psz_dup )
3096 {
3097     char *psz_access = NULL;
3098     char *psz_demux  = NULL;
3099     char *psz_path;
3100
3101     /* Either there is an access/demux specification before ://
3102      * or we have a plain local file path. */
3103     psz_path = strstr( psz_dup, "://" );
3104     if( psz_path != NULL )
3105     {
3106         *psz_path = '\0';
3107         psz_path += 3; /* skips "://" */
3108
3109         /* Separate access from demux (<access>/<demux>://<path>) */
3110         psz_access = psz_dup;
3111         psz_demux = strchr( psz_access, '/' );
3112         if( psz_demux )
3113             *psz_demux++ = '\0';
3114
3115         /* We really don't want module name substitution here! */
3116         if( psz_access[0] == '$' )
3117             psz_access++;
3118         if( psz_demux && psz_demux[0] == '$' )
3119             psz_demux++;
3120     }
3121     else
3122     {
3123         psz_path = psz_dup;
3124     }
3125     *ppsz_access = psz_access ? psz_access : "";
3126     *ppsz_demux = psz_demux ? psz_demux : "";
3127     *ppsz_path = psz_path;
3128 }
3129
3130 static inline bool next(char ** src)
3131 {
3132     char *end;
3133     errno = 0;
3134     long result = strtol( *src, &end, 0 );
3135     if( errno != 0 || result >= LONG_MAX || result <= LONG_MIN ||
3136         end == *src )
3137     {
3138         return false;
3139     }
3140     *src = end;
3141     return true;
3142 }
3143
3144 /*****************************************************************************
3145  * MRLSections: parse title and seekpoint info from the Media Resource Locator.
3146  *
3147  * Syntax:
3148  * [url][@[title-start][:chapter-start][-[title-end][:chapter-end]]]
3149  *****************************************************************************/
3150 static void MRLSections( input_thread_t *p_input, char *psz_source,
3151                          int *pi_title_start, int *pi_title_end,
3152                          int *pi_chapter_start, int *pi_chapter_end )
3153 {
3154     char *psz, *psz_end, *psz_next, *psz_check;
3155
3156     *pi_title_start = *pi_title_end = -1;
3157     *pi_chapter_start = *pi_chapter_end = -1;
3158
3159     /* Start by parsing titles and chapters */
3160     if( !psz_source || !( psz = strrchr( psz_source, '@' ) ) ) return;
3161
3162
3163     /* Check we are really dealing with a title/chapter section */
3164     psz_check = psz + 1;
3165     if( !*psz_check ) return;
3166     if( isdigit(*psz_check) )
3167         if(!next(&psz_check)) return;
3168     if( *psz_check != ':' && *psz_check != '-' && *psz_check ) return;
3169     if( *psz_check == ':' && ++psz_check )
3170     {
3171         if( isdigit(*psz_check) )
3172             if(!next(&psz_check)) return;
3173     }
3174     if( *psz_check != '-' && *psz_check ) return;
3175     if( *psz_check == '-' && ++psz_check )
3176     {
3177         if( isdigit(*psz_check) )
3178             if(!next(&psz_check)) return;
3179     }
3180     if( *psz_check != ':' && *psz_check ) return;
3181     if( *psz_check == ':' && ++psz_check )
3182     {
3183         if( isdigit(*psz_check) )
3184             if(!next(&psz_check)) return;
3185     }
3186     if( *psz_check ) return;
3187
3188     /* Separate start and end */
3189     *psz++ = 0;
3190     if( ( psz_end = strchr( psz, '-' ) ) ) *psz_end++ = 0;
3191
3192     /* Look for the start title */
3193     *pi_title_start = strtol( psz, &psz_next, 0 );
3194     if( !*pi_title_start && psz == psz_next ) *pi_title_start = -1;
3195     *pi_title_end = *pi_title_start;
3196     psz = psz_next;
3197
3198     /* Look for the start chapter */
3199     if( *psz ) psz++;
3200     *pi_chapter_start = strtol( psz, &psz_next, 0 );
3201     if( !*pi_chapter_start && psz == psz_next ) *pi_chapter_start = -1;
3202     *pi_chapter_end = *pi_chapter_start;
3203
3204     if( psz_end )
3205     {
3206         /* Look for the end title */
3207         *pi_title_end = strtol( psz_end, &psz_next, 0 );
3208         if( !*pi_title_end && psz_end == psz_next ) *pi_title_end = -1;
3209         psz_end = psz_next;
3210
3211         /* Look for the end chapter */
3212         if( *psz_end ) psz_end++;
3213         *pi_chapter_end = strtol( psz_end, &psz_next, 0 );
3214         if( !*pi_chapter_end && psz_end == psz_next ) *pi_chapter_end = -1;
3215     }
3216
3217     msg_Dbg( p_input, "source=`%s' title=%d/%d seekpoint=%d/%d",
3218              psz_source, *pi_title_start, *pi_chapter_start,
3219              *pi_title_end, *pi_chapter_end );
3220 }
3221
3222 /*****************************************************************************
3223  * input_AddSubtitles: add a subtitles file and enable it
3224  *****************************************************************************/
3225 static void SubtitleAdd( input_thread_t *p_input, char *psz_subtitle, bool b_forced )
3226 {
3227     input_source_t *sub;
3228     vlc_value_t count;
3229     vlc_value_t list;
3230     char *psz_path, *psz_extension;
3231
3232     /* if we are provided a subtitle.sub file,
3233      * see if we don't have a subtitle.idx and use it instead */
3234     psz_path = strdup( psz_subtitle );
3235     if( psz_path )
3236     {
3237         psz_extension = strrchr( psz_path, '.');
3238         if( psz_extension && strcmp( psz_extension, ".sub" ) == 0 )
3239         {
3240             struct stat st;
3241
3242             strcpy( psz_extension, ".idx" );
3243
3244             if( !utf8_stat( psz_path, &st ) && S_ISREG( st.st_mode ) )
3245             {
3246                 msg_Dbg( p_input, "using %s subtitles file instead of %s",
3247                          psz_path, psz_subtitle );
3248                 strcpy( psz_subtitle, psz_path );
3249             }
3250         }
3251         free( psz_path );
3252     }
3253
3254     var_Change( p_input, "spu-es", VLC_VAR_CHOICESCOUNT, &count, NULL );
3255
3256     sub = InputSourceNew( p_input );
3257     if( !sub || InputSourceInit( p_input, sub, psz_subtitle, "subtitle" ) )
3258     {
3259         free( sub );
3260         return;
3261     }
3262     TAB_APPEND( p_input->p->i_slave, p_input->p->slave, sub );
3263
3264     /* Select the ES */
3265     if( b_forced && !var_Change( p_input, "spu-es", VLC_VAR_GETLIST, &list, NULL ) )
3266     {
3267         if( count.i_int == 0 )
3268             count.i_int++;
3269         /* if it was first one, there is disable too */
3270
3271         if( count.i_int < list.p_list->i_count )
3272         {
3273             const int i_id = list.p_list->p_values[count.i_int].i_int;
3274
3275             es_out_Control( p_input->p->p_es_out_display, ES_OUT_SET_ES_DEFAULT_BY_ID, i_id );
3276             es_out_Control( p_input->p->p_es_out_display, ES_OUT_SET_ES_BY_ID, i_id );
3277         }
3278         var_FreeList( &list, NULL );
3279     }
3280 }
3281
3282 /*****************************************************************************
3283  * Statistics
3284  *****************************************************************************/
3285 void input_UpdateStatistic( input_thread_t *p_input,
3286                             input_statistic_t i_type, int i_delta )
3287 {
3288     assert( p_input->p->i_state != INIT_S );
3289
3290     vlc_mutex_lock( &p_input->p->counters.counters_lock);
3291     switch( i_type )
3292     {
3293 #define I(c) stats_UpdateInteger( p_input, p_input->p->counters.c, i_delta, NULL )
3294     case INPUT_STATISTIC_DECODED_VIDEO:
3295         I(p_decoded_video);
3296         break;
3297     case INPUT_STATISTIC_DECODED_AUDIO:
3298         I(p_decoded_audio);
3299         break;
3300     case INPUT_STATISTIC_DECODED_SUBTITLE:
3301         I(p_decoded_sub);
3302         break;
3303     case INPUT_STATISTIC_SENT_PACKET:
3304         I(p_sout_sent_packets);
3305         break;
3306 #undef I
3307     case INPUT_STATISTIC_SENT_BYTE:
3308     {
3309         int i_bytes; /* That's pretty stupid to define it as an integer, it will overflow
3310                         really fast ... */
3311         if( !stats_UpdateInteger( p_input, p_input->p->counters.p_sout_sent_bytes, i_delta, &i_bytes ) )
3312             stats_UpdateFloat( p_input, p_input->p->counters.p_sout_send_bitrate, i_bytes, NULL );
3313         break;
3314     }
3315     default:
3316         msg_Err( p_input, "Invalid statistic type %d (internal error)", i_type );
3317         break;
3318     }
3319     vlc_mutex_unlock( &p_input->p->counters.counters_lock);
3320 }
3321
3322 /**/
3323 /* TODO FIXME nearly the same logic that snapshot code */
3324 char *input_CreateFilename( vlc_object_t *p_obj, const char *psz_path, const char *psz_prefix, const char *psz_extension )
3325 {
3326     char *psz_file;
3327     DIR *path;
3328
3329     path = utf8_opendir( psz_path );
3330     if( path )
3331     {
3332         closedir( path );
3333
3334         char *psz_tmp = str_format( p_obj, psz_prefix );
3335         if( !psz_tmp )
3336             return NULL;
3337
3338         char *psz_tmp2 = filename_sanitize( psz_tmp );
3339         free( psz_tmp );
3340
3341         if( !psz_tmp2 ||
3342             asprintf( &psz_file, "%s"DIR_SEP"%s%s%s",
3343                       psz_path, psz_tmp2,
3344                       psz_extension ? "." : "",
3345                       psz_extension ? psz_extension : "" ) < 0 )
3346             psz_file = NULL;
3347         free( psz_tmp2 );
3348         return psz_file;
3349     }
3350     else
3351     {
3352         psz_file = str_format( p_obj, psz_path );
3353         path_sanitize( psz_file );
3354         return psz_file;
3355     }
3356 }
3357