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