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