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