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