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