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