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