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