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