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