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