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