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