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