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