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