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