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