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