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