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