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