9371a0c3c2ebdaf095a17ba7ef4b277bb08bf3ee
[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 static inline int ControlPopNoLock( input_thread_t *p_input,
1402                                     int *pi_type, vlc_value_t *p_val,
1403                                     mtime_t i_deadline )
1404 {
1405
1406     while( p_input->p->i_control <= 0 )
1407     {
1408         if( !vlc_object_alive( p_input ) )
1409             return VLC_EGENERIC;
1410
1411         if( i_deadline < 0 )
1412             return VLC_EGENERIC;
1413
1414         if( vlc_cond_timedwait( &p_input->p->wait_control, &p_input->p->lock_control, i_deadline ) )
1415             return VLC_EGENERIC;
1416     }
1417
1418     *pi_type = p_input->p->control[0].i_type;
1419     *p_val   = p_input->p->control[0].val;
1420
1421     p_input->p->i_control--;
1422     if( p_input->p->i_control > 0 )
1423     {
1424         int i;
1425
1426         for( i = 0; i < p_input->p->i_control; i++ )
1427         {
1428             p_input->p->control[i].i_type = p_input->p->control[i+1].i_type;
1429             p_input->p->control[i].val    = p_input->p->control[i+1].val;
1430         }
1431     }
1432
1433     return VLC_SUCCESS;
1434 }
1435
1436 static void ControlReduce( input_thread_t *p_input )
1437 {
1438     int i;
1439
1440     if( !p_input )
1441         return;
1442
1443     for( i = 1; i < p_input->p->i_control; i++ )
1444     {
1445         const int i_lt = p_input->p->control[i-1].i_type;
1446         const int i_ct = p_input->p->control[i].i_type;
1447
1448         /* XXX We can't merge INPUT_CONTROL_SET_ES */
1449 /*        msg_Dbg( p_input, "[%d/%d] l=%d c=%d", i, p_input->p->i_control,
1450                  i_lt, i_ct );
1451 */
1452         if( i_lt == i_ct &&
1453             ( i_ct == INPUT_CONTROL_SET_STATE ||
1454               i_ct == INPUT_CONTROL_SET_RATE ||
1455               i_ct == INPUT_CONTROL_SET_POSITION ||
1456               i_ct == INPUT_CONTROL_SET_TIME ||
1457               i_ct == INPUT_CONTROL_SET_PROGRAM ||
1458               i_ct == INPUT_CONTROL_SET_TITLE ||
1459               i_ct == INPUT_CONTROL_SET_SEEKPOINT ||
1460               i_ct == INPUT_CONTROL_SET_BOOKMARK ) )
1461         {
1462             int j;
1463 //            msg_Dbg( p_input, "merged at %d", i );
1464             /* Remove the i-1 */
1465             for( j = i; j <  p_input->p->i_control; j++ )
1466                 p_input->p->control[j-1] = p_input->p->control[j];
1467             p_input->p->i_control--;
1468         }
1469         else
1470         {
1471             /* TODO but that's not that important
1472                 - merge SET_X with SET_X_CMD
1473                 - remove SET_SEEKPOINT/SET_POSITION/SET_TIME before a SET_TITLE
1474                 - remove SET_SEEKPOINT/SET_POSITION/SET_TIME before another among them
1475                 - ?
1476                 */
1477         }
1478     }
1479 }
1480 /* Pause input */
1481 static void ControlPause( input_thread_t *p_input, mtime_t i_control_date )
1482 {
1483     int i_ret = VLC_SUCCESS;
1484     int i_state = PAUSE_S;
1485
1486     if( p_input->p->b_can_pause )
1487     {
1488         if( p_input->p->input.p_access )
1489             i_ret = access_Control( p_input->p->input.p_access,
1490                                      ACCESS_SET_PAUSE_STATE, true );
1491         else
1492             i_ret = demux_Control( p_input->p->input.p_demux,
1493                                     DEMUX_SET_PAUSE_STATE, true );
1494
1495         if( i_ret )
1496         {
1497             msg_Warn( p_input, "cannot set pause state" );
1498             i_state = p_input->i_state;
1499         }
1500     }
1501
1502     /* */
1503     if( !i_ret )
1504     {
1505         i_ret = es_out_SetPauseState( p_input->p->p_es_out, p_input->p->b_can_pause, true, i_control_date );
1506         if( i_ret )
1507         {
1508             msg_Warn( p_input, "cannot set pause state at es_out level" );
1509             i_state = p_input->i_state;
1510         }
1511     }
1512
1513     /* Switch to new state */
1514     input_ChangeState( p_input, i_state );
1515
1516 }
1517
1518 static void ControlUnpause( input_thread_t *p_input, mtime_t i_control_date )
1519 {
1520     int i_ret = VLC_SUCCESS;
1521
1522     if( p_input->p->b_can_pause )
1523     {
1524         if( p_input->p->input.p_access )
1525             i_ret = access_Control( p_input->p->input.p_access,
1526                                      ACCESS_SET_PAUSE_STATE, false );
1527         else
1528             i_ret = demux_Control( p_input->p->input.p_demux,
1529                                     DEMUX_SET_PAUSE_STATE, false );
1530         if( i_ret )
1531         {
1532             /* FIXME What to do ? */
1533             msg_Warn( p_input, "cannot unset pause -> EOF" );
1534             vlc_mutex_unlock( &p_input->p->lock_control );
1535             input_ControlPush( p_input, INPUT_CONTROL_SET_DIE, NULL );
1536             vlc_mutex_lock( &p_input->p->lock_control );
1537         }
1538     }
1539
1540     /* Switch to play */
1541     input_ChangeState( p_input, PLAYING_S );
1542
1543     /* */
1544     if( !i_ret )
1545         es_out_SetPauseState( p_input->p->p_es_out, false, false, i_control_date );
1546 }
1547
1548 static bool Control( input_thread_t *p_input, int i_type,
1549                            vlc_value_t val )
1550 {
1551     const mtime_t i_control_date = mdate();
1552     /* FIXME b_force_update is abused, it should be carefully checked */
1553     bool b_force_update = false;
1554
1555     if( !p_input )
1556         return b_force_update;
1557
1558     switch( i_type )
1559     {
1560         case INPUT_CONTROL_SET_DIE:
1561             msg_Dbg( p_input, "control: stopping input" );
1562
1563             /* Mark all submodules to die */
1564             ObjectKillChildrens( p_input, VLC_OBJECT(p_input) );
1565             break;
1566
1567         case INPUT_CONTROL_SET_POSITION:
1568         case INPUT_CONTROL_SET_POSITION_OFFSET:
1569         {
1570             double f_pos;
1571
1572             if( p_input->p->b_recording )
1573             {
1574                 msg_Err( p_input, "INPUT_CONTROL_SET_POSITION(_OFFSET) ignored while recording" );
1575                 break;
1576             }
1577             if( i_type == INPUT_CONTROL_SET_POSITION )
1578             {
1579                 f_pos = val.f_float;
1580             }
1581             else
1582             {
1583                 /* Should not fail */
1584                 demux_Control( p_input->p->input.p_demux,
1585                                 DEMUX_GET_POSITION, &f_pos );
1586                 f_pos += val.f_float;
1587             }
1588             if( f_pos < 0.0 ) f_pos = 0.0;
1589             if( f_pos > 1.0 ) f_pos = 1.0;
1590             /* Reset the decoders states and clock sync (before calling the demuxer */
1591             es_out_SetTime( p_input->p->p_es_out, -1 );
1592             if( demux_Control( p_input->p->input.p_demux, DEMUX_SET_POSITION,
1593                                 f_pos ) )
1594             {
1595                 msg_Err( p_input, "INPUT_CONTROL_SET_POSITION(_OFFSET) "
1596                          "%2.1f%% failed", f_pos * 100 );
1597             }
1598             else
1599             {
1600                 if( p_input->p->i_slave > 0 )
1601                     SlaveSeek( p_input );
1602                 p_input->p->input.b_eof = false;
1603
1604                 b_force_update = true;
1605             }
1606             break;
1607         }
1608
1609         case INPUT_CONTROL_SET_TIME:
1610         case INPUT_CONTROL_SET_TIME_OFFSET:
1611         {
1612             int64_t i_time;
1613             int i_ret;
1614
1615             if( p_input->p->b_recording )
1616             {
1617                 msg_Err( p_input, "INPUT_CONTROL_SET_TIME(_OFFSET) ignored while recording" );
1618                 break;
1619             }
1620
1621             if( i_type == INPUT_CONTROL_SET_TIME )
1622             {
1623                 i_time = val.i_time;
1624             }
1625             else
1626             {
1627                 /* Should not fail */
1628                 demux_Control( p_input->p->input.p_demux,
1629                                 DEMUX_GET_TIME, &i_time );
1630                 i_time += val.i_time;
1631             }
1632             if( i_time < 0 ) i_time = 0;
1633
1634             /* Reset the decoders states and clock sync (before calling the demuxer */
1635             es_out_SetTime( p_input->p->p_es_out, -1 );
1636
1637             i_ret = demux_Control( p_input->p->input.p_demux,
1638                                     DEMUX_SET_TIME, i_time );
1639             if( i_ret )
1640             {
1641                 int64_t i_length;
1642
1643                 /* Emulate it with a SET_POS */
1644                 demux_Control( p_input->p->input.p_demux,
1645                                 DEMUX_GET_LENGTH, &i_length );
1646                 if( i_length > 0 )
1647                 {
1648                     double f_pos = (double)i_time / (double)i_length;
1649                     i_ret = demux_Control( p_input->p->input.p_demux,
1650                                             DEMUX_SET_POSITION, f_pos );
1651                 }
1652             }
1653             if( i_ret )
1654             {
1655                 msg_Warn( p_input, "INPUT_CONTROL_SET_TIME(_OFFSET) %"PRId64
1656                          " failed or not possible", i_time );
1657             }
1658             else
1659             {
1660                 if( p_input->p->i_slave > 0 )
1661                     SlaveSeek( p_input );
1662                 p_input->p->input.b_eof = false;
1663
1664                 b_force_update = true;
1665             }
1666             break;
1667         }
1668
1669         case INPUT_CONTROL_SET_STATE:
1670             if( ( val.i_int == PLAYING_S && p_input->i_state == PAUSE_S ) ||
1671                 ( val.i_int == PAUSE_S && p_input->i_state == PAUSE_S ) )
1672             {
1673                 ControlUnpause( p_input, i_control_date );
1674
1675                 b_force_update = true;
1676             }
1677             else if( val.i_int == PAUSE_S && p_input->i_state == PLAYING_S /* &&
1678                      p_input->p->b_can_pause */ )
1679             {
1680                 ControlPause( p_input, i_control_date );
1681
1682                 b_force_update = true;
1683             }
1684             else if( val.i_int == PAUSE_S && !p_input->p->b_can_pause && 0 )
1685             {
1686                 b_force_update = true;
1687
1688                 /* Correct "state" value */
1689                 input_ChangeState( p_input, p_input->i_state );
1690             }
1691             else if( val.i_int != PLAYING_S && val.i_int != PAUSE_S )
1692             {
1693                 msg_Err( p_input, "invalid state in INPUT_CONTROL_SET_STATE" );
1694             }
1695             break;
1696
1697         case INPUT_CONTROL_SET_RATE:
1698         case INPUT_CONTROL_SET_RATE_SLOWER:
1699         case INPUT_CONTROL_SET_RATE_FASTER:
1700         {
1701             int i_rate;
1702             int i_rate_sign;
1703
1704             /* Get rate and direction */
1705             if( i_type == INPUT_CONTROL_SET_RATE )
1706             {
1707                 i_rate = abs( val.i_int );
1708                 i_rate_sign = val.i_int < 0 ? -1 : 1;
1709             }
1710             else
1711             {
1712                 static const int ppi_factor[][2] = {
1713                     {1,64}, {1,32}, {1,16}, {1,8}, {1,4}, {1,3}, {1,2}, {2,3},
1714                     {1,1},
1715                     {3,2}, {2,1}, {3,1}, {4,1}, {8,1}, {16,1}, {32,1}, {64,1},
1716                     {0,0}
1717                 };
1718                 int i_error;
1719                 int i_idx;
1720                 int i;
1721
1722                 i_rate_sign = p_input->p->i_rate < 0 ? -1 : 1;
1723
1724                 i_error = INT_MAX;
1725                 i_idx = -1;
1726                 for( i = 0; ppi_factor[i][0] != 0; i++ )
1727                 {
1728                     const int i_test_r = INPUT_RATE_DEFAULT * ppi_factor[i][0] / ppi_factor[i][1];
1729                     const int i_test_e = abs( abs( p_input->p->i_rate ) - i_test_r );
1730                     if( i_test_e < i_error )
1731                     {
1732                         i_idx = i;
1733                         i_error = i_test_e;
1734                     }
1735                 }
1736
1737                 assert( i_idx >= 0 && ppi_factor[i_idx][0] != 0 );
1738
1739                 if( i_type == INPUT_CONTROL_SET_RATE_SLOWER )
1740                 {
1741                     if( ppi_factor[i_idx+1][0] > 0 )
1742                         i_rate = INPUT_RATE_DEFAULT * ppi_factor[i_idx+1][0] / ppi_factor[i_idx+1][1];
1743                     else
1744                         i_rate = INPUT_RATE_MAX+1;
1745                 }
1746                 else
1747                 {
1748                     assert( i_type == INPUT_CONTROL_SET_RATE_FASTER );
1749                     if( i_idx > 0 )
1750                         i_rate = INPUT_RATE_DEFAULT * ppi_factor[i_idx-1][0] / ppi_factor[i_idx-1][1];
1751                     else
1752                         i_rate = INPUT_RATE_MIN-1;
1753                 }
1754             }
1755
1756             /* Check rate bound */
1757             if( i_rate < INPUT_RATE_MIN )
1758             {
1759                 msg_Dbg( p_input, "cannot set rate faster" );
1760                 i_rate = INPUT_RATE_MIN;
1761             }
1762             else if( i_rate > INPUT_RATE_MAX )
1763             {
1764                 msg_Dbg( p_input, "cannot set rate slower" );
1765                 i_rate = INPUT_RATE_MAX;
1766             }
1767
1768             /* Apply direction */
1769             if( i_rate_sign < 0 )
1770             {
1771                 if( p_input->p->input.b_rescale_ts )
1772                 {
1773                     msg_Dbg( p_input, "cannot set negative rate" );
1774                     i_rate = p_input->p->i_rate;
1775                     assert( i_rate > 0 );
1776                 }
1777                 else
1778                 {
1779                     i_rate *= i_rate_sign;
1780                 }
1781             }
1782
1783             if( i_rate != INPUT_RATE_DEFAULT &&
1784                 ( ( !p_input->p->b_can_rate_control && !p_input->p->input.b_rescale_ts ) ||
1785                   ( p_input->p->p_sout && !p_input->p->b_out_pace_control ) ) )
1786             {
1787                 msg_Dbg( p_input, "cannot change rate" );
1788                 i_rate = INPUT_RATE_DEFAULT;
1789             }
1790             if( i_rate != p_input->p->i_rate &&
1791                 !p_input->b_can_pace_control && p_input->p->b_can_rate_control )
1792             {
1793                 int i_ret;
1794                 if( p_input->p->input.p_access )
1795                 {
1796                     i_ret = VLC_EGENERIC;
1797                 }
1798                 else
1799                 {
1800                     if( !p_input->p->input.b_rescale_ts )
1801                         es_out_Control( p_input->p->p_es_out, ES_OUT_RESET_PCR );
1802
1803                     i_ret = demux_Control( p_input->p->input.p_demux,
1804                                             DEMUX_SET_RATE, &i_rate );
1805                 }
1806                 if( i_ret )
1807                 {
1808                     msg_Warn( p_input, "ACCESS/DEMUX_SET_RATE failed" );
1809                     i_rate = p_input->p->i_rate;
1810                 }
1811             }
1812
1813             /* */
1814             if( i_rate != p_input->p->i_rate )
1815             {
1816                 p_input->p->i_rate = i_rate;
1817                 input_SendEventRate( p_input, i_rate );
1818
1819                 if( p_input->p->input.b_rescale_ts )
1820                 {
1821                     const int i_rate_source = (p_input->b_can_pace_control || p_input->p->b_can_rate_control ) ? i_rate : INPUT_RATE_DEFAULT;
1822                     es_out_SetRate( p_input->p->p_es_out, i_rate_source, i_rate );
1823                 }
1824
1825                 b_force_update = true;
1826             }
1827             break;
1828         }
1829
1830         case INPUT_CONTROL_SET_PROGRAM:
1831             /* No need to force update, es_out does it if needed */
1832             es_out_Control( p_input->p->p_es_out,
1833                             ES_OUT_SET_GROUP, val.i_int );
1834
1835             demux_Control( p_input->p->input.p_demux, DEMUX_SET_GROUP, val.i_int,
1836                             NULL );
1837             break;
1838
1839         case INPUT_CONTROL_SET_ES:
1840             /* No need to force update, es_out does it if needed */
1841             es_out_Control( p_input->p->p_es_out_display, ES_OUT_SET_ES_BY_ID, val.i_int );
1842             break;
1843
1844         case INPUT_CONTROL_RESTART_ES:
1845             es_out_Control( p_input->p->p_es_out_display, ES_OUT_RESTART_ES_BY_ID, val.i_int );
1846             break;
1847
1848         case INPUT_CONTROL_SET_AUDIO_DELAY:
1849             if( !es_out_SetDelay( p_input->p->p_es_out_display, AUDIO_ES, val.i_time ) )
1850                 input_SendEventAudioDelay( p_input, val.i_time );
1851             break;
1852
1853         case INPUT_CONTROL_SET_SPU_DELAY:
1854             if( !es_out_SetDelay( p_input->p->p_es_out_display, SPU_ES, val.i_time ) )
1855                 input_SendEventSubtitleDelay( p_input, val.i_time );
1856             break;
1857
1858         case INPUT_CONTROL_SET_TITLE:
1859         case INPUT_CONTROL_SET_TITLE_NEXT:
1860         case INPUT_CONTROL_SET_TITLE_PREV:
1861             if( p_input->p->b_recording )
1862             {
1863                 msg_Err( p_input, "INPUT_CONTROL_SET_TITLE(*) ignored while recording" );
1864                 break;
1865             }
1866             if( p_input->p->input.b_title_demux &&
1867                 p_input->p->input.i_title > 0 )
1868             {
1869                 /* TODO */
1870                 /* FIXME handle demux title */
1871                 demux_t *p_demux = p_input->p->input.p_demux;
1872                 int i_title;
1873
1874                 if( i_type == INPUT_CONTROL_SET_TITLE_PREV )
1875                     i_title = p_demux->info.i_title - 1;
1876                 else if( i_type == INPUT_CONTROL_SET_TITLE_NEXT )
1877                     i_title = p_demux->info.i_title + 1;
1878                 else
1879                     i_title = val.i_int;
1880
1881                 if( i_title >= 0 && i_title < p_input->p->input.i_title )
1882                 {
1883                     es_out_SetTime( p_input->p->p_es_out, -1 );
1884
1885                     demux_Control( p_demux, DEMUX_SET_TITLE, i_title );
1886                     input_ControlVarTitle( p_input, i_title );
1887                 }
1888             }
1889             else if( p_input->p->input.i_title > 0 )
1890             {
1891                 access_t *p_access = p_input->p->input.p_access;
1892                 int i_title;
1893
1894                 if( i_type == INPUT_CONTROL_SET_TITLE_PREV )
1895                     i_title = p_access->info.i_title - 1;
1896                 else if( i_type == INPUT_CONTROL_SET_TITLE_NEXT )
1897                     i_title = p_access->info.i_title + 1;
1898                 else
1899                     i_title = val.i_int;
1900
1901                 if( i_title >= 0 && i_title < p_input->p->input.i_title )
1902                 {
1903                     es_out_SetTime( p_input->p->p_es_out, -1 );
1904
1905                     access_Control( p_access, ACCESS_SET_TITLE, i_title );
1906                     stream_AccessReset( p_input->p->input.p_stream );
1907                 }
1908             }
1909             break;
1910         case INPUT_CONTROL_SET_SEEKPOINT:
1911         case INPUT_CONTROL_SET_SEEKPOINT_NEXT:
1912         case INPUT_CONTROL_SET_SEEKPOINT_PREV:
1913             if( p_input->p->b_recording )
1914             {
1915                 msg_Err( p_input, "INPUT_CONTROL_SET_SEEKPOINT(*) ignored while recording" );
1916                 break;
1917             }
1918
1919             if( p_input->p->input.b_title_demux &&
1920                 p_input->p->input.i_title > 0 )
1921             {
1922                 demux_t *p_demux = p_input->p->input.p_demux;
1923                 int i_seekpoint;
1924                 int64_t i_input_time;
1925                 int64_t i_seekpoint_time;
1926
1927                 if( i_type == INPUT_CONTROL_SET_SEEKPOINT_PREV )
1928                 {
1929                     i_seekpoint = p_demux->info.i_seekpoint;
1930                     i_seekpoint_time = p_input->p->input.title[p_demux->info.i_title]->seekpoint[i_seekpoint]->i_time_offset;
1931                     if( i_seekpoint_time >= 0 &&
1932                          !demux_Control( p_demux,
1933                                           DEMUX_GET_TIME, &i_input_time ) )
1934                     {
1935                         if( i_input_time < i_seekpoint_time + 3000000 )
1936                             i_seekpoint--;
1937                     }
1938                     else
1939                         i_seekpoint--;
1940                 }
1941                 else if( i_type == INPUT_CONTROL_SET_SEEKPOINT_NEXT )
1942                     i_seekpoint = p_demux->info.i_seekpoint + 1;
1943                 else
1944                     i_seekpoint = val.i_int;
1945
1946                 if( i_seekpoint >= 0 && i_seekpoint <
1947                     p_input->p->input.title[p_demux->info.i_title]->i_seekpoint )
1948                 {
1949
1950                     es_out_SetTime( p_input->p->p_es_out, -1 );
1951
1952                     demux_Control( p_demux, DEMUX_SET_SEEKPOINT, i_seekpoint );
1953                 }
1954             }
1955             else if( p_input->p->input.i_title > 0 )
1956             {
1957                 demux_t *p_demux = p_input->p->input.p_demux;
1958                 access_t *p_access = p_input->p->input.p_access;
1959                 int i_seekpoint;
1960                 int64_t i_input_time;
1961                 int64_t i_seekpoint_time;
1962
1963                 if( i_type == INPUT_CONTROL_SET_SEEKPOINT_PREV )
1964                 {
1965                     i_seekpoint = p_access->info.i_seekpoint;
1966                     i_seekpoint_time = p_input->p->input.title[p_access->info.i_title]->seekpoint[i_seekpoint]->i_time_offset;
1967                     if( i_seekpoint_time >= 0 &&
1968                         demux_Control( p_demux,
1969                                         DEMUX_GET_TIME, &i_input_time ) )
1970                     {
1971                         if( i_input_time < i_seekpoint_time + 3000000 )
1972                             i_seekpoint--;
1973                     }
1974                     else
1975                         i_seekpoint--;
1976                 }
1977                 else if( i_type == INPUT_CONTROL_SET_SEEKPOINT_NEXT )
1978                     i_seekpoint = p_access->info.i_seekpoint + 1;
1979                 else
1980                     i_seekpoint = val.i_int;
1981
1982                 if( i_seekpoint >= 0 && i_seekpoint <
1983                     p_input->p->input.title[p_access->info.i_title]->i_seekpoint )
1984                 {
1985                     es_out_SetTime( p_input->p->p_es_out, -1 );
1986
1987                     access_Control( p_access, ACCESS_SET_SEEKPOINT,
1988                                     i_seekpoint );
1989                     stream_AccessReset( p_input->p->input.p_stream );
1990                 }
1991             }
1992             break;
1993
1994         case INPUT_CONTROL_ADD_SUBTITLE:
1995             if( val.psz_string )
1996             {
1997                 SubtitleAdd( p_input, val.psz_string, true );
1998                 free( val.psz_string );
1999             }
2000             break;
2001
2002         case INPUT_CONTROL_ADD_SLAVE:
2003             if( val.psz_string )
2004             {
2005                 input_source_t *slave = InputSourceNew( p_input );
2006
2007                 if( !InputSourceInit( p_input, slave, val.psz_string, NULL ) )
2008                 {
2009                     vlc_meta_t *p_meta;
2010                     int64_t i_time;
2011
2012                     /* Add the slave */
2013                     msg_Dbg( p_input, "adding %s as slave on the fly",
2014                              val.psz_string );
2015
2016                     /* Set position */
2017                     if( demux_Control( p_input->p->input.p_demux,
2018                                         DEMUX_GET_TIME, &i_time ) )
2019                     {
2020                         msg_Err( p_input, "demux doesn't like DEMUX_GET_TIME" );
2021                         InputSourceClean( slave );
2022                         free( slave );
2023                         break;
2024                     }
2025                     if( demux_Control( slave->p_demux,
2026                                        DEMUX_SET_TIME, i_time ) )
2027                     {
2028                         msg_Err( p_input, "seek failed for new slave" );
2029                         InputSourceClean( slave );
2030                         free( slave );
2031                         break;
2032                     }
2033
2034                     /* Get meta (access and demux) */
2035                     p_meta = vlc_meta_New();
2036                     access_Control( slave->p_access, ACCESS_GET_META,
2037                                      p_meta );
2038                     demux_Control( slave->p_demux, DEMUX_GET_META, p_meta );
2039                     InputUpdateMeta( p_input, p_meta );
2040
2041                     TAB_APPEND( p_input->p->i_slave, p_input->p->slave, slave );
2042                 }
2043                 else
2044                 {
2045                     free( slave );
2046                     msg_Warn( p_input, "failed to add %s as slave",
2047                               val.psz_string );
2048                 }
2049
2050                 free( val.psz_string );
2051             }
2052             break;
2053
2054         case INPUT_CONTROL_SET_RECORD_STATE:
2055             if( !!p_input->p->b_recording != !!val.b_bool )
2056             {
2057                 if( p_input->p->input.b_can_stream_record )
2058                 {
2059                     if( demux_Control( p_input->p->input.p_demux,
2060                                        DEMUX_SET_RECORD_STATE, val.b_bool ) )
2061                         val.b_bool = false;
2062                 }
2063                 else
2064                 {
2065                     if( es_out_SetRecordState( p_input->p->p_es_out_display, val.b_bool ) )
2066                         val.b_bool = false;
2067                 }
2068                 p_input->p->b_recording = val.b_bool;
2069
2070                 input_SendEventRecord( p_input, val.b_bool );
2071
2072                 b_force_update = true;
2073             }
2074             break;
2075
2076         case INPUT_CONTROL_SET_FRAME_NEXT:
2077             if( p_input->i_state == PAUSE_S )
2078             {
2079                 es_out_SetFrameNext( p_input->p->p_es_out );
2080             }
2081             else if( p_input->i_state == PLAYING_S )
2082             {
2083                 ControlPause( p_input, i_control_date );
2084             }
2085             else
2086             {
2087                 msg_Err( p_input, "invalid state for frame next" );
2088             }
2089             b_force_update = true;
2090             break;
2091
2092         case INPUT_CONTROL_SET_BOOKMARK:
2093         default:
2094             msg_Err( p_input, "not yet implemented" );
2095             break;
2096     }
2097
2098     return b_force_update;
2099 }
2100
2101 /*****************************************************************************
2102  * UpdateFromDemux:
2103  *****************************************************************************/
2104 static int UpdateTitleSeekpoint( input_thread_t *p_input,
2105                                  int i_title, int i_seekpoint )
2106 {
2107     int i_title_end = p_input->p->input.i_title_end -
2108                         p_input->p->input.i_title_offset;
2109     int i_seekpoint_end = p_input->p->input.i_seekpoint_end -
2110                             p_input->p->input.i_seekpoint_offset;
2111
2112     if( i_title_end >= 0 && i_seekpoint_end >= 0 )
2113     {
2114         if( i_title > i_title_end ||
2115             ( i_title == i_title_end && i_seekpoint > i_seekpoint_end ) )
2116             return 0;
2117     }
2118     else if( i_seekpoint_end >= 0 )
2119     {
2120         if( i_seekpoint > i_seekpoint_end )
2121             return 0;
2122     }
2123     else if( i_title_end >= 0 )
2124     {
2125         if( i_title > i_title_end )
2126             return 0;
2127     }
2128     return 1;
2129 }
2130 static int UpdateFromDemux( input_thread_t *p_input )
2131 {
2132     demux_t *p_demux = p_input->p->input.p_demux;
2133
2134     /* TODO event-like */
2135     if( p_demux->info.i_update & INPUT_UPDATE_TITLE )
2136     {
2137         input_SendEventTitle( p_input, p_demux->info.i_title );
2138
2139         p_demux->info.i_update &= ~INPUT_UPDATE_TITLE;
2140     }
2141     if( p_demux->info.i_update & INPUT_UPDATE_SEEKPOINT )
2142     {
2143         input_SendEventSeekpoint( p_input,
2144                                   p_demux->info.i_title, p_demux->info.i_seekpoint );
2145
2146         p_demux->info.i_update &= ~INPUT_UPDATE_SEEKPOINT;
2147     }
2148     p_demux->info.i_update &= ~INPUT_UPDATE_SIZE;
2149
2150     /* Hmmm only works with master input */
2151     if( p_input->p->input.p_demux == p_demux )
2152         return UpdateTitleSeekpoint( p_input,
2153                                      p_demux->info.i_title,
2154                                      p_demux->info.i_seekpoint );
2155     return 1;
2156 }
2157
2158 /*****************************************************************************
2159  * UpdateFromAccess:
2160  *****************************************************************************/
2161 static int UpdateFromAccess( input_thread_t *p_input )
2162 {
2163     access_t *p_access = p_input->p->input.p_access;
2164
2165     if( p_access->info.i_update & INPUT_UPDATE_TITLE )
2166     {
2167         input_SendEventTitle( p_input, p_access->info.i_title );
2168
2169         stream_AccessUpdate( p_input->p->input.p_stream );
2170
2171         p_access->info.i_update &= ~INPUT_UPDATE_TITLE;
2172     }
2173     if( p_access->info.i_update & INPUT_UPDATE_SEEKPOINT )
2174     {
2175         input_SendEventSeekpoint( p_input,
2176                                   p_access->info.i_title, p_access->info.i_seekpoint );
2177
2178         p_access->info.i_update &= ~INPUT_UPDATE_SEEKPOINT;
2179     }
2180     if( p_access->info.i_update & INPUT_UPDATE_META )
2181     {
2182         /* TODO maybe multi - access ? */
2183         vlc_meta_t *p_meta = vlc_meta_New();
2184         access_Control( p_input->p->input.p_access,ACCESS_GET_META, p_meta );
2185         InputUpdateMeta( p_input, p_meta );
2186         p_access->info.i_update &= ~INPUT_UPDATE_META;
2187     }
2188     if( p_access->info.i_update & INPUT_UPDATE_SIGNAL )
2189     {
2190         double f_quality;
2191         double f_strength;
2192
2193         if( access_Control( p_access, ACCESS_GET_SIGNAL, &f_quality, &f_strength ) )
2194             f_quality = f_strength = -1;
2195
2196         input_SendEventSignal( p_input, f_quality, f_strength );
2197
2198         p_access->info.i_update &= ~INPUT_UPDATE_SIGNAL;
2199     }
2200
2201     p_access->info.i_update &= ~INPUT_UPDATE_SIZE;
2202
2203     /* Hmmm only works with master input */
2204     if( p_input->p->input.p_access == p_access )
2205         return UpdateTitleSeekpoint( p_input,
2206                                      p_access->info.i_title,
2207                                      p_access->info.i_seekpoint );
2208     return 1;
2209 }
2210
2211 /*****************************************************************************
2212  * InputSourceNew:
2213  *****************************************************************************/
2214 static input_source_t *InputSourceNew( input_thread_t *p_input )
2215 {
2216     VLC_UNUSED(p_input);
2217     input_source_t *in = malloc( sizeof( input_source_t ) );
2218     if( in )
2219         memset( in, 0, sizeof( input_source_t ) );
2220     return in;
2221 }
2222
2223 /*****************************************************************************
2224  * InputSourceInit:
2225  *****************************************************************************/
2226 static int InputSourceInit( input_thread_t *p_input,
2227                             input_source_t *in, const char *psz_mrl,
2228                             const char *psz_forced_demux )
2229 {
2230     const bool b_master = in == &p_input->p->input;
2231
2232     char psz_dup[strlen(psz_mrl) + 1];
2233     const char *psz_access;
2234     const char *psz_demux;
2235     char *psz_path;
2236     char *psz_tmp;
2237     char *psz;
2238     vlc_value_t val;
2239     double f_fps;
2240
2241     strcpy( psz_dup, psz_mrl );
2242
2243     if( !in ) return VLC_EGENERIC;
2244     if( !p_input ) return VLC_EGENERIC;
2245
2246     /* Split uri */
2247     input_SplitMRL( &psz_access, &psz_demux, &psz_path, psz_dup );
2248
2249     msg_Dbg( p_input, "`%s' gives access `%s' demux `%s' path `%s'",
2250              psz_mrl, psz_access, psz_demux, psz_path );
2251     if( !p_input->b_preparsing )
2252     {
2253         /* Hack to allow udp://@:port syntax */
2254         if( !psz_access ||
2255             (strncmp( psz_access, "udp", 3 ) &&
2256              strncmp( psz_access, "rtp", 3 )) )
2257         {
2258             /* Find optional titles and seekpoints */
2259             MRLSections( p_input, psz_path, &in->i_title_start, &in->i_title_end,
2260                      &in->i_seekpoint_start, &in->i_seekpoint_end );
2261         }
2262
2263         if( psz_forced_demux && *psz_forced_demux )
2264         {
2265             psz_demux = psz_forced_demux;
2266         }
2267         else if( *psz_demux == '\0' )
2268         {
2269             /* special hack for forcing a demuxer with --demux=module
2270              * (and do nothing with a list) */
2271             char *psz_var_demux = var_GetNonEmptyString( p_input, "demux" );
2272
2273             if( psz_var_demux != NULL &&
2274                 !strchr(psz_var_demux, ',' ) &&
2275                 !strchr(psz_var_demux, ':' ) )
2276             {
2277                 psz_demux = psz_var_demux;
2278
2279                 msg_Dbg( p_input, "enforced demux ` %s'", psz_demux );
2280             }
2281         }
2282
2283         /* Try access_demux first */
2284         in->p_demux = demux_New( p_input, psz_access, psz_demux, psz_path,
2285                                   NULL, p_input->p->p_es_out, false );
2286     }
2287     else
2288     {
2289         /* Preparsing is only for file:// */
2290         if( *psz_demux )
2291             goto error;
2292         if( !*psz_access ) /* path without scheme:// */
2293             psz_access = "file";
2294         if( strcmp( psz_access, "file" ) )
2295             goto error;
2296         msg_Dbg( p_input, "trying to pre-parse %s",  psz_path );
2297     }
2298
2299     if( in->p_demux )
2300     {
2301         int64_t i_pts_delay;
2302
2303         /* Get infos from access_demux */
2304         demux_Control( in->p_demux,
2305                         DEMUX_GET_PTS_DELAY, &i_pts_delay );
2306         p_input->i_pts_delay = __MAX( p_input->i_pts_delay, i_pts_delay );
2307
2308         in->b_title_demux = true;
2309         if( demux_Control( in->p_demux, DEMUX_GET_TITLE_INFO,
2310                             &in->title, &in->i_title,
2311                             &in->i_title_offset, &in->i_seekpoint_offset ) )
2312         {
2313             TAB_INIT( in->i_title, in->title );
2314         }
2315         if( demux_Control( in->p_demux, DEMUX_CAN_CONTROL_PACE,
2316                             &in->b_can_pace_control ) )
2317             in->b_can_pace_control = false;
2318
2319         if( !in->b_can_pace_control )
2320         {
2321             if( demux_Control( in->p_demux, DEMUX_CAN_CONTROL_RATE,
2322                                 &in->b_can_rate_control, &in->b_rescale_ts ) )
2323             {
2324                 in->b_can_rate_control = false;
2325                 in->b_rescale_ts = true; /* not used */
2326             }
2327         }
2328         else
2329         {
2330             in->b_can_rate_control = true;
2331             in->b_rescale_ts = true;
2332         }
2333         if( demux_Control( in->p_demux, DEMUX_CAN_PAUSE,
2334                             &in->b_can_pause ) )
2335             in->b_can_pause = false;
2336         var_SetBool( p_input, "can-pause", in->b_can_pause || !in->b_can_pace_control ); /* XXX temporary because of es_out_timeshift*/
2337         var_SetBool( p_input, "can-rate", !in->b_can_pace_control || in->b_can_rate_control ); /* XXX temporary because of es_out_timeshift*/
2338         var_SetBool( p_input, "can-rewind", !in->b_rescale_ts && !in->b_can_pace_control );
2339
2340         int ret = demux_Control( in->p_demux, DEMUX_CAN_SEEK,
2341                         &val.b_bool );
2342         if( ret != VLC_SUCCESS )
2343             val.b_bool = false;
2344         var_Set( p_input, "seekable", val );
2345     }
2346     else
2347     {
2348         int64_t i_pts_delay;
2349
2350         if( b_master )
2351             input_ChangeState( p_input, OPENING_S );
2352
2353         /* Now try a real access */
2354         in->p_access = access_New( p_input, psz_access, psz_demux, psz_path );
2355
2356         /* Access failed, URL encoded ? */
2357         if( in->p_access == NULL && strchr( psz_path, '%' ) )
2358         {
2359             decode_URI( psz_path );
2360
2361             msg_Dbg( p_input, "retrying with access `%s' demux `%s' path `%s'",
2362                      psz_access, psz_demux, psz_path );
2363
2364             in->p_access = access_New( p_input,
2365                                         psz_access, psz_demux, psz_path );
2366         }
2367         if( in->p_access == NULL )
2368         {
2369             msg_Err( p_input, "open of `%s' failed: %s", psz_mrl,
2370                                                          msg_StackMsg() );
2371             intf_UserFatal( VLC_OBJECT( p_input), false,
2372                             _("Your input can't be opened"),
2373                             _("VLC is unable to open the MRL '%s'."
2374                             " Check the log for details."), psz_mrl );
2375             goto error;
2376         }
2377
2378         /* */
2379         psz_tmp = psz = var_GetNonEmptyString( p_input, "access-filter" );
2380         while( psz && *psz )
2381         {
2382             access_t *p_access = in->p_access;
2383             char *end = strchr( psz, ':' );
2384
2385             if( end )
2386                 *end++ = '\0';
2387
2388             in->p_access = access_FilterNew( in->p_access, psz );
2389             if( in->p_access == NULL )
2390             {
2391                 in->p_access = p_access;
2392                 msg_Warn( p_input, "failed to insert access filter %s",
2393                           psz );
2394             }
2395
2396             psz = end;
2397         }
2398         free( psz_tmp );
2399
2400         /* Get infos from access */
2401         if( !p_input->b_preparsing )
2402         {
2403             access_Control( in->p_access,
2404                              ACCESS_GET_PTS_DELAY, &i_pts_delay );
2405             p_input->i_pts_delay = __MAX( p_input->i_pts_delay, i_pts_delay );
2406
2407             in->b_title_demux = false;
2408             if( access_Control( in->p_access, ACCESS_GET_TITLE_INFO,
2409                                  &in->title, &in->i_title,
2410                                 &in->i_title_offset, &in->i_seekpoint_offset ) )
2411
2412             {
2413                 TAB_INIT( in->i_title, in->title );
2414             }
2415             access_Control( in->p_access, ACCESS_CAN_CONTROL_PACE,
2416                              &in->b_can_pace_control );
2417             in->b_can_rate_control = in->b_can_pace_control;
2418             in->b_rescale_ts = true;
2419
2420             access_Control( in->p_access, ACCESS_CAN_PAUSE,
2421                              &in->b_can_pause );
2422             var_SetBool( p_input, "can-pause", in->b_can_pause || !in->b_can_pace_control ); /* XXX temporary because of es_out_timeshift*/
2423             var_SetBool( p_input, "can-rate", !in->b_can_pace_control || in->b_can_rate_control ); /* XXX temporary because of es_out_timeshift*/
2424             var_SetBool( p_input, "can-rewind", !in->b_rescale_ts && !in->b_can_pace_control );
2425
2426             access_Control( in->p_access, ACCESS_CAN_SEEK,
2427                              &val.b_bool );
2428             var_Set( p_input, "seekable", val );
2429         }
2430
2431         if( b_master )
2432             input_ChangeState( p_input, BUFFERING_S );
2433
2434         /* Autodetect extra files if none specified */
2435         char *psz_input_list = var_CreateGetNonEmptyString( p_input, "input-list" );
2436         if( !psz_input_list )
2437         {
2438             char *psz_extra_files = InputGetExtraFiles( p_input, psz_access, psz_path );
2439             if( psz_extra_files )
2440                 var_SetString( p_input, "input-list", psz_extra_files );
2441             free( psz_extra_files );
2442         }
2443
2444         /* Create the stream_t */
2445         in->p_stream = stream_AccessNew( in->p_access, p_input->b_preparsing );
2446
2447         /* Restor old value */
2448         if( !psz_input_list )
2449             var_SetString( p_input, "input-list", "" );
2450         free( psz_input_list );
2451
2452         if( in->p_stream == NULL )
2453         {
2454             msg_Warn( p_input, "cannot create a stream_t from access" );
2455             goto error;
2456         }
2457
2458         /* Open a demuxer */
2459         if( *psz_demux == '\0' && *in->p_access->psz_demux )
2460         {
2461             psz_demux = in->p_access->psz_demux;
2462         }
2463
2464         {
2465             /* Take access redirections into account */
2466             char *psz_real_path;
2467             char *psz_buf = NULL;
2468             if( in->p_access->psz_path )
2469             {
2470                 const char *psz_a, *psz_d;
2471                 psz_buf = strdup( in->p_access->psz_path );
2472                 input_SplitMRL( &psz_a, &psz_d, &psz_real_path, psz_buf );
2473             }
2474             else
2475             {
2476                 psz_real_path = psz_path;
2477             }
2478             in->p_demux = demux_New( p_input, psz_access, psz_demux,
2479                                       psz_real_path,
2480                                       in->p_stream, p_input->p->p_es_out,
2481                                       p_input->b_preparsing );
2482             free( psz_buf );
2483         }
2484
2485         if( in->p_demux == NULL )
2486         {
2487             msg_Err( p_input, "no suitable demux module for `%s/%s://%s'",
2488                      psz_access, psz_demux, psz_path );
2489             intf_UserFatal( VLC_OBJECT( p_input ), false,
2490                             _("VLC can't recognize the input's format"),
2491                             _("The format of '%s' cannot be detected. "
2492                             "Have a look at the log for details."), psz_mrl );
2493             goto error;
2494         }
2495
2496         /* Get title from demux */
2497         if( !p_input->b_preparsing && in->i_title <= 0 )
2498         {
2499             if( demux_Control( in->p_demux, DEMUX_GET_TITLE_INFO,
2500                                 &in->title, &in->i_title,
2501                                 &in->i_title_offset, &in->i_seekpoint_offset ))
2502             {
2503                 TAB_INIT( in->i_title, in->title );
2504             }
2505             else
2506             {
2507                 in->b_title_demux = true;
2508             }
2509         }
2510     }
2511
2512     /* Set record capabilities */
2513     if( demux_Control( in->p_demux, DEMUX_CAN_RECORD, &in->b_can_stream_record ) )
2514         in->b_can_stream_record = false;
2515 #ifdef ENABLE_SOUT
2516     if( !var_CreateGetBool( p_input, "input-record-native" ) )
2517         in->b_can_stream_record = false;
2518     var_SetBool( p_input, "can-record", true );
2519 #else
2520     var_SetBool( p_input, "can-record", in->b_can_stream_record );
2521 #endif
2522
2523     /* get attachment
2524      * FIXME improve for b_preparsing: move it after GET_META and check psz_arturl */
2525     if( 1 || !p_input->b_preparsing )
2526     {
2527         int i_attachment;
2528         input_attachment_t **attachment;
2529         if( !demux_Control( in->p_demux, DEMUX_GET_ATTACHMENTS,
2530                              &attachment, &i_attachment ) )
2531         {
2532             vlc_mutex_lock( &p_input->p->input.p_item->lock );
2533             AppendAttachment( &p_input->p->i_attachment, &p_input->p->attachment,
2534                               i_attachment, attachment );
2535             vlc_mutex_unlock( &p_input->p->input.p_item->lock );
2536         }
2537     }
2538     if( !demux_Control( in->p_demux, DEMUX_GET_FPS, &f_fps ) )
2539     {
2540         vlc_mutex_lock( &p_input->p->input.p_item->lock );
2541         in->f_fps = f_fps;
2542         vlc_mutex_unlock( &p_input->p->input.p_item->lock );
2543     }
2544
2545     if( var_GetInteger( p_input, "clock-synchro" ) != -1 )
2546         in->b_can_pace_control = !var_GetInteger( p_input, "clock-synchro" );
2547
2548     return VLC_SUCCESS;
2549
2550 error:
2551     if( b_master )
2552         input_ChangeState( p_input, ERROR_S );
2553
2554     if( in->p_demux )
2555         demux_Delete( in->p_demux );
2556
2557     if( in->p_stream )
2558         stream_Delete( in->p_stream );
2559
2560     if( in->p_access )
2561         access_Delete( in->p_access );
2562
2563     return VLC_EGENERIC;
2564 }
2565
2566 /*****************************************************************************
2567  * InputSourceClean:
2568  *****************************************************************************/
2569 static void InputSourceClean( input_source_t *in )
2570 {
2571     int i;
2572
2573     if( in->p_demux )
2574         demux_Delete( in->p_demux );
2575
2576     if( in->p_stream )
2577         stream_Delete( in->p_stream );
2578
2579     if( in->p_access )
2580         access_Delete( in->p_access );
2581
2582     if( in->i_title > 0 )
2583     {
2584         for( i = 0; i < in->i_title; i++ )
2585             vlc_input_title_Delete( in->title[i] );
2586         TAB_CLEAN( in->i_title, in->title );
2587     }
2588 }
2589
2590 static void SlaveDemux( input_thread_t *p_input )
2591 {
2592     int64_t i_time;
2593     int i;
2594     bool b_set_time = true;
2595
2596     if( demux_Control( p_input->p->input.p_demux, DEMUX_GET_TIME, &i_time ) )
2597     {
2598         /* msg_Err( p_input, "demux doesn't like DEMUX_GET_TIME" ); */
2599         b_set_time = false;
2600     }
2601
2602     for( i = 0; i < p_input->p->i_slave; i++ )
2603     {
2604         input_source_t *in = p_input->p->slave[i];
2605         int i_ret = 1;
2606
2607         if( in->b_eof )
2608             continue;
2609
2610         if( b_set_time && demux_Control( in->p_demux, DEMUX_SET_NEXT_DEMUX_TIME, i_time ) )
2611         {
2612             for( ;; )
2613             {
2614                 int64_t i_stime;
2615                 if( demux_Control( in->p_demux, DEMUX_GET_TIME, &i_stime ) )
2616                 {
2617                     msg_Err( p_input, "slave[%d] doesn't like "
2618                              "DEMUX_GET_TIME -> EOF", i );
2619                     i_ret = 0;
2620                     break;
2621                 }
2622
2623                 if( i_stime >= i_time )
2624                     break;
2625
2626                 if( ( i_ret = in->p_demux->pf_demux( in->p_demux ) ) <= 0 )
2627                     break;
2628             }
2629         }
2630         else
2631         {
2632             i_ret = in->p_demux->pf_demux( in->p_demux );
2633         }
2634
2635         if( i_ret <= 0 )
2636         {
2637             msg_Dbg( p_input, "slave %d EOF", i );
2638             in->b_eof = true;
2639         }
2640     }
2641 }
2642
2643 static void SlaveSeek( input_thread_t *p_input )
2644 {
2645     int64_t i_time;
2646     int i;
2647
2648     if( !p_input ) return;
2649
2650     if( demux_Control( p_input->p->input.p_demux, DEMUX_GET_TIME, &i_time ) )
2651     {
2652         msg_Err( p_input, "demux doesn't like DEMUX_GET_TIME" );
2653         return;
2654     }
2655
2656     for( i = 0; i < p_input->p->i_slave; i++ )
2657     {
2658         input_source_t *in = p_input->p->slave[i];
2659
2660         if( demux_Control( in->p_demux, DEMUX_SET_TIME, i_time ) )
2661         {
2662             if( !in->b_eof )
2663                 msg_Err( p_input, "seek failed for slave %d -> EOF", i );
2664             in->b_eof = true;
2665         }
2666         else
2667         {
2668             in->b_eof = false;
2669         }
2670     }
2671 }
2672
2673 /*****************************************************************************
2674  * InputMetaUser:
2675  *****************************************************************************/
2676 static void InputMetaUser( input_thread_t *p_input, vlc_meta_t *p_meta )
2677 {
2678     vlc_value_t val;
2679
2680     if( !p_meta ) return;
2681
2682     /* Get meta information from user */
2683 #define GET_META( field, s ) \
2684     var_Get( p_input, (s), &val );  \
2685     if( *val.psz_string ) \
2686         vlc_meta_Set( p_meta, vlc_meta_ ## field, val.psz_string ); \
2687     free( val.psz_string )
2688
2689     GET_META( Title, "meta-title" );
2690     GET_META( Artist, "meta-artist" );
2691     GET_META( Genre, "meta-genre" );
2692     GET_META( Copyright, "meta-copyright" );
2693     GET_META( Description, "meta-description" );
2694     GET_META( Date, "meta-date" );
2695     GET_META( URL, "meta-url" );
2696 #undef GET_META
2697 }
2698
2699 /*****************************************************************************
2700  * InputGetExtraFiles
2701  *  Autodetect extra input list
2702  *****************************************************************************/
2703 static char *InputGetExtraFiles( input_thread_t *p_input,
2704                                  const char *psz_access, const char *psz_path )
2705 {
2706     char *psz_list = NULL;
2707
2708     if( ( psz_access && *psz_access && strcmp( psz_access, "file" ) ) || !psz_path )
2709         return NULL;
2710
2711
2712     const char *psz_ext = strrchr( psz_path, '.' );
2713     if( !psz_ext || strcmp( psz_ext, ".001" ) )
2714         return NULL;
2715
2716     char *psz_file = strdup( psz_path );
2717     if( !psz_file )
2718         return NULL;
2719
2720     /* Try to list .xyz files */
2721     for( int i = 2; i < 999; i++ )
2722     {
2723         char *psz_ext = strrchr( psz_file, '.' );
2724         struct stat st;
2725
2726         snprintf( psz_ext, 5, ".%.3d", i );
2727
2728         if( utf8_stat( psz_file, &st )
2729          || !S_ISREG( st.st_mode ) || !st.st_size )
2730             continue;
2731
2732         msg_Dbg( p_input, "Detected extra file `%s'", psz_file );
2733
2734         if( psz_list )
2735         {
2736             char *psz_old = psz_list;
2737             /* FIXME how to handle file with ',' ?*/
2738             if( asprintf( &psz_list, "%s,%s", psz_old, psz_file ) < 0 )
2739             {
2740                 psz_list = psz_old;
2741                 break;
2742             }
2743         }
2744         else
2745         {
2746             psz_list = strdup( psz_file );
2747         }
2748     }
2749     free( psz_file );
2750
2751     return psz_list;
2752 }
2753
2754 /*****************************************************************************
2755  * InputUpdateMeta: merge p_item meta data with p_meta taking care of
2756  * arturl and locking issue.
2757  *****************************************************************************/
2758 static void InputUpdateMeta( input_thread_t *p_input, vlc_meta_t *p_meta )
2759 {
2760     input_item_t *p_item = p_input->p->input.p_item;
2761     char * psz_arturl = NULL;
2762     char *psz_title = NULL;
2763
2764     if( !p_meta )
2765         return;
2766
2767     psz_arturl = input_item_GetArtURL( p_item );
2768
2769     vlc_mutex_lock( &p_item->lock );
2770
2771     if( vlc_meta_Get( p_meta, vlc_meta_Title ) && !p_item->b_fixed_name )
2772         psz_title = strdup( vlc_meta_Get( p_meta, vlc_meta_Title ) );
2773
2774     vlc_meta_Merge( p_item->p_meta, p_meta );
2775
2776     vlc_meta_Delete( p_meta );
2777
2778     if( psz_arturl && *psz_arturl )
2779     {
2780         vlc_meta_Set( p_item->p_meta, vlc_meta_ArtworkURL, psz_arturl );
2781
2782         if( !strncmp( psz_arturl, "attachment://", strlen("attachment") ) )
2783         {
2784             /* Don't look for art cover if sout
2785              * XXX It can change when sout has meta data support */
2786             if( p_input->p->p_sout && !p_input->b_preparsing )
2787                 vlc_meta_Set( p_item->p_meta, vlc_meta_ArtworkURL, "" );
2788             else
2789                 input_ExtractAttachmentAndCacheArt( p_input );
2790         }
2791     }
2792     free( psz_arturl );
2793
2794     vlc_mutex_unlock( &p_item->lock );
2795
2796     if( psz_title )
2797     {
2798         input_item_SetName( p_item, psz_title );
2799         free( psz_title );
2800     }
2801     input_item_SetPreparsed( p_item, true );
2802
2803     input_SendEventMeta( p_input );
2804
2805     /** \todo handle sout meta */
2806 }
2807
2808
2809 static void AppendAttachment( int *pi_attachment, input_attachment_t ***ppp_attachment,
2810                               int i_new, input_attachment_t **pp_new )
2811 {
2812     int i_attachment = *pi_attachment;
2813     input_attachment_t **attachment = *ppp_attachment;
2814     int i;
2815
2816     attachment = realloc( attachment,
2817                           sizeof(input_attachment_t**) * ( i_attachment + i_new ) );
2818     for( i = 0; i < i_new; i++ )
2819         attachment[i_attachment++] = pp_new[i];
2820     free( pp_new );
2821
2822     /* */
2823     *pi_attachment = i_attachment;
2824     *ppp_attachment = attachment;
2825 }
2826
2827 static void AccessMeta( input_thread_t * p_input, vlc_meta_t *p_meta )
2828 {
2829     int i;
2830
2831     if( p_input->b_preparsing )
2832         return;
2833
2834     if( p_input->p->input.p_access )
2835         access_Control( p_input->p->input.p_access, ACCESS_GET_META,
2836                          p_meta );
2837
2838     /* Get meta data from slave input */
2839     for( i = 0; i < p_input->p->i_slave; i++ )
2840     {
2841         DemuxMeta( p_input, p_meta, p_input->p->slave[i]->p_demux );
2842         if( p_input->p->slave[i]->p_access )
2843         {
2844             access_Control( p_input->p->slave[i]->p_access,
2845                              ACCESS_GET_META, p_meta );
2846         }
2847     }
2848 }
2849
2850 static void DemuxMeta( input_thread_t *p_input, vlc_meta_t *p_meta, demux_t *p_demux )
2851 {
2852     bool b_bool;
2853     module_t *p_id3;
2854
2855 #if 0
2856     /* XXX I am not sure it is a great idea, besides, there is more than that
2857      * if we want to do it right */
2858     vlc_mutex_lock( &p_item->lock );
2859     if( p_item->p_meta && (p_item->p_meta->i_status & ITEM_PREPARSED ) )
2860     {
2861         vlc_mutex_unlock( &p_item->lock );
2862         return;
2863     }
2864     vlc_mutex_unlock( &p_item->lock );
2865 #endif
2866
2867     demux_Control( p_demux, DEMUX_GET_META, p_meta );
2868     if( demux_Control( p_demux, DEMUX_HAS_UNSUPPORTED_META, &b_bool ) )
2869         return;
2870     if( !b_bool )
2871         return;
2872
2873     p_demux->p_private = malloc( sizeof( demux_meta_t ) );
2874     if(! p_demux->p_private )
2875         return;
2876
2877     p_id3 = module_need( p_demux, "meta reader", NULL, 0 );
2878     if( p_id3 )
2879     {
2880         demux_meta_t *p_demux_meta = (demux_meta_t *)p_demux->p_private;
2881
2882         if( p_demux_meta->p_meta )
2883         {
2884             vlc_meta_Merge( p_meta, p_demux_meta->p_meta );
2885             vlc_meta_Delete( p_demux_meta->p_meta );
2886         }
2887
2888         if( p_demux_meta->i_attachments > 0 )
2889         {
2890             vlc_mutex_lock( &p_input->p->input.p_item->lock );
2891             AppendAttachment( &p_input->p->i_attachment, &p_input->p->attachment,
2892                               p_demux_meta->i_attachments, p_demux_meta->attachments );
2893             vlc_mutex_unlock( &p_input->p->input.p_item->lock );
2894         }
2895         module_unneed( p_demux, p_id3 );
2896     }
2897     free( p_demux->p_private );
2898 }
2899
2900 static void input_ChangeState( input_thread_t *p_input, int i_state )
2901 {
2902     const bool b_changed = p_input->i_state != i_state;
2903
2904     p_input->i_state = i_state;
2905     if( i_state == ERROR_S )
2906         p_input->b_error = true;
2907     else if( i_state == END_S )
2908         p_input->b_eof = true;
2909
2910     if( b_changed )
2911     {
2912         input_item_SetErrorWhenReading( p_input->p->input.p_item, p_input->b_error );
2913         input_SendEventState( p_input, i_state );
2914     }
2915 }
2916
2917
2918 /*****************************************************************************
2919  * MRLSplit: parse the access, demux and url part of the
2920  *           Media Resource Locator.
2921  *****************************************************************************/
2922 void input_SplitMRL( const char **ppsz_access, const char **ppsz_demux, char **ppsz_path,
2923                      char *psz_dup )
2924 {
2925     char *psz_access = NULL;
2926     char *psz_demux  = NULL;
2927     char *psz_path;
2928
2929     /* Either there is an access/demux specification before ://
2930      * or we have a plain local file path. */
2931     psz_path = strstr( psz_dup, "://" );
2932     if( psz_path != NULL )
2933     {
2934         *psz_path = '\0';
2935         psz_path += 3; /* skips "://" */
2936
2937         /* Separate access from demux (<access>/<demux>://<path>) */
2938         psz_access = psz_dup;
2939         psz_demux = strchr( psz_access, '/' );
2940         if( psz_demux )
2941             *psz_demux++ = '\0';
2942
2943         /* We really don't want module name substitution here! */
2944         if( psz_access[0] == '$' )
2945             psz_access++;
2946         if( psz_demux && psz_demux[0] == '$' )
2947             psz_demux++;
2948     }
2949     else
2950     {
2951         psz_path = psz_dup;
2952     }
2953     *ppsz_access = psz_access ? psz_access : (char*)"";
2954     *ppsz_demux = psz_demux ? psz_demux : (char*)"";
2955     *ppsz_path = psz_path;
2956 }
2957
2958 static inline bool next(char ** src)
2959 {
2960     char *end;
2961     errno = 0;
2962     long result = strtol( *src, &end, 0 );
2963     if( errno != 0 || result >= LONG_MAX || result <= LONG_MIN ||
2964         end == *src )
2965     {
2966         return false;
2967     }
2968     *src = end;
2969     return true;
2970 }
2971
2972 /*****************************************************************************
2973  * MRLSections: parse title and seekpoint info from the Media Resource Locator.
2974  *
2975  * Syntax:
2976  * [url][@[title-start][:chapter-start][-[title-end][:chapter-end]]]
2977  *****************************************************************************/
2978 static void MRLSections( input_thread_t *p_input, char *psz_source,
2979                          int *pi_title_start, int *pi_title_end,
2980                          int *pi_chapter_start, int *pi_chapter_end )
2981 {
2982     char *psz, *psz_end, *psz_next, *psz_check;
2983
2984     *pi_title_start = *pi_title_end = -1;
2985     *pi_chapter_start = *pi_chapter_end = -1;
2986
2987     /* Start by parsing titles and chapters */
2988     if( !psz_source || !( psz = strrchr( psz_source, '@' ) ) ) return;
2989
2990
2991     /* Check we are really dealing with a title/chapter section */
2992     psz_check = psz + 1;
2993     if( !*psz_check ) return;
2994     if( isdigit(*psz_check) )
2995         if(!next(&psz_check)) return;
2996     if( *psz_check != ':' && *psz_check != '-' && *psz_check ) return;
2997     if( *psz_check == ':' && ++psz_check )
2998     {
2999         if( isdigit(*psz_check) )
3000             if(!next(&psz_check)) return;
3001     }
3002     if( *psz_check != '-' && *psz_check ) return;
3003     if( *psz_check == '-' && ++psz_check )
3004     {
3005         if( isdigit(*psz_check) )
3006             if(!next(&psz_check)) return;
3007     }
3008     if( *psz_check != ':' && *psz_check ) return;
3009     if( *psz_check == ':' && ++psz_check )
3010     {
3011         if( isdigit(*psz_check) )
3012             if(!next(&psz_check)) return;
3013     }
3014     if( *psz_check ) return;
3015
3016     /* Separate start and end */
3017     *psz++ = 0;
3018     if( ( psz_end = strchr( psz, '-' ) ) ) *psz_end++ = 0;
3019
3020     /* Look for the start title */
3021     *pi_title_start = strtol( psz, &psz_next, 0 );
3022     if( !*pi_title_start && psz == psz_next ) *pi_title_start = -1;
3023     *pi_title_end = *pi_title_start;
3024     psz = psz_next;
3025
3026     /* Look for the start chapter */
3027     if( *psz ) psz++;
3028     *pi_chapter_start = strtol( psz, &psz_next, 0 );
3029     if( !*pi_chapter_start && psz == psz_next ) *pi_chapter_start = -1;
3030     *pi_chapter_end = *pi_chapter_start;
3031
3032     if( psz_end )
3033     {
3034         /* Look for the end title */
3035         *pi_title_end = strtol( psz_end, &psz_next, 0 );
3036         if( !*pi_title_end && psz_end == psz_next ) *pi_title_end = -1;
3037         psz_end = psz_next;
3038
3039         /* Look for the end chapter */
3040         if( *psz_end ) psz_end++;
3041         *pi_chapter_end = strtol( psz_end, &psz_next, 0 );
3042         if( !*pi_chapter_end && psz_end == psz_next ) *pi_chapter_end = -1;
3043     }
3044
3045     msg_Dbg( p_input, "source=`%s' title=%d/%d seekpoint=%d/%d",
3046              psz_source, *pi_title_start, *pi_chapter_start,
3047              *pi_title_end, *pi_chapter_end );
3048 }
3049
3050 /*****************************************************************************
3051  * input_AddSubtitles: add a subtitles file and enable it
3052  *****************************************************************************/
3053 static void SubtitleAdd( input_thread_t *p_input, char *psz_subtitle, bool b_forced )
3054 {
3055     input_source_t *sub;
3056     vlc_value_t count;
3057     vlc_value_t list;
3058     char *psz_path, *psz_extension;
3059
3060     /* if we are provided a subtitle.sub file,
3061      * see if we don't have a subtitle.idx and use it instead */
3062     psz_path = strdup( psz_subtitle );
3063     if( psz_path )
3064     {
3065         psz_extension = strrchr( psz_path, '.');
3066         if( psz_extension && strcmp( psz_extension, ".sub" ) == 0 )
3067         {
3068             struct stat st;
3069
3070             strcpy( psz_extension, ".idx" );
3071
3072             if( !utf8_stat( psz_path, &st ) && S_ISREG( st.st_mode ) )
3073             {
3074                 msg_Dbg( p_input, "using %s subtitles file instead of %s",
3075                          psz_path, psz_subtitle );
3076                 strcpy( psz_subtitle, psz_path );
3077             }
3078         }
3079         free( psz_path );
3080     }
3081
3082     var_Change( p_input, "spu-es", VLC_VAR_CHOICESCOUNT, &count, NULL );
3083
3084     sub = InputSourceNew( p_input );
3085     if( InputSourceInit( p_input, sub, psz_subtitle, "subtitle" ) )
3086     {
3087         free( sub );
3088         return;
3089     }
3090     TAB_APPEND( p_input->p->i_slave, p_input->p->slave, sub );
3091
3092     /* Select the ES */
3093     if( b_forced && !var_Change( p_input, "spu-es", VLC_VAR_GETLIST, &list, NULL ) )
3094     {
3095         if( count.i_int == 0 )
3096             count.i_int++;
3097         /* if it was first one, there is disable too */
3098
3099         if( count.i_int < list.p_list->i_count )
3100         {
3101             const int i_id = list.p_list->p_values[count.i_int].i_int;
3102
3103             es_out_Control( p_input->p->p_es_out_display, ES_OUT_SET_ES_DEFAULT_BY_ID, i_id );
3104             es_out_Control( p_input->p->p_es_out_display, ES_OUT_SET_ES_BY_ID, i_id );
3105         }
3106         var_Change( p_input, "spu-es", VLC_VAR_FREELIST, &list, NULL );
3107     }
3108 }
3109
3110 bool input_AddSubtitles( input_thread_t *p_input, char *psz_subtitle,
3111                                bool b_check_extension )
3112 {
3113     vlc_value_t val;
3114
3115     if( b_check_extension && !subtitles_Filter( psz_subtitle ) )
3116         return false;
3117
3118     assert( psz_subtitle != NULL );
3119
3120     val.psz_string = strdup( psz_subtitle );
3121     if( val.psz_string )
3122         input_ControlPush( p_input, INPUT_CONTROL_ADD_SUBTITLE, &val );
3123     return true;
3124 }
3125
3126 /*****************************************************************************
3127  * input_get_event_manager
3128  *****************************************************************************/
3129 vlc_event_manager_t *input_get_event_manager( input_thread_t *p_input )
3130 {
3131     return &p_input->p->event_manager;
3132 }
3133
3134 /**/
3135 /* TODO FIXME nearly the same logic that snapshot code */
3136 char *input_CreateFilename( vlc_object_t *p_obj, const char *psz_path, const char *psz_prefix, const char *psz_extension )
3137 {
3138     char *psz_file;
3139     DIR *path;
3140
3141     path = utf8_opendir( psz_path );
3142     if( path )
3143     {
3144         closedir( path );
3145
3146         char *psz_tmp = str_format( p_obj, psz_prefix );
3147         if( !psz_tmp )
3148             return NULL;
3149
3150         filename_sanitize( psz_tmp );
3151         if( asprintf( &psz_file, "%s"DIR_SEP"%s%s%s",
3152                       psz_path, psz_tmp,
3153                       psz_extension ? "." : "",
3154                       psz_extension ? psz_extension : "" ) < 0 )
3155             psz_file = NULL;
3156         free( psz_tmp );
3157         return psz_file;
3158     }
3159     else
3160     {
3161         psz_file = str_format( p_obj, psz_path );
3162         path_sanitize( psz_file );
3163         return psz_file;
3164     }
3165 }
3166