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