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