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