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