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