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