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