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