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