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