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