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