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