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