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