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