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