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