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