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