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