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