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