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