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