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