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