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