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