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