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