]> git.sesse.net Git - vlc/blob - src/input/stream.c
The msleep in stream.c is useless as access MUST wait themselves.
[vlc] / src / input / stream.c
1 /*****************************************************************************
2  * stream.c
3  *****************************************************************************
4  * Copyright (C) 1999-2004 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27
28 #include <dirent.h>
29
30 #include <vlc_common.h>
31 #include <vlc_strings.h>
32 #include <vlc_osd.h>
33 #include <vlc_charset.h>
34
35 #include <assert.h>
36
37 #include "input_internal.h"
38
39 #undef STREAM_DEBUG
40
41 /* TODO:
42  *  - tune the 2 methods (block/stream)
43  *  - compute cost for seek
44  *  - improve stream mode seeking with closest segments
45  *  - ...
46  *  - Maybe remove (block/stream) in favour of immediate
47  */
48
49 /* Two methods:
50  *  - using pf_block
51  *      One linked list of data read
52  *  - using pf_read
53  *      More complex scheme using mutliple track to avoid seeking
54  *  - using directly the access (only indirection for peeking).
55  *      This method is known to introduce much less latency.
56  *      It should probably defaulted (instead of the stream method (2)).
57  */
58
59 /* How many tracks we have, currently only used for stream mode */
60 #ifdef OPTIMIZE_MEMORY
61 #   define STREAM_CACHE_TRACK 1
62     /* Max size of our cache 128Ko per track */
63 #   define STREAM_CACHE_SIZE  (STREAM_CACHE_TRACK*1024*128)
64 #else
65 #   define STREAM_CACHE_TRACK 3
66     /* Max size of our cache 4Mo per track */
67 #   define STREAM_CACHE_SIZE  (4*STREAM_CACHE_TRACK*1024*1024)
68 #endif
69
70 /* How many data we try to prebuffer */
71 #define STREAM_CACHE_PREBUFFER_SIZE (32767)
72 /* Maximum time we take to pre-buffer */
73 #define STREAM_CACHE_PREBUFFER_LENGTH (100*1000)
74
75 /* Method1: Simple, for pf_block.
76  *  We get blocks and put them in the linked list.
77  *  We release blocks once the total size is bigger than CACHE_BLOCK_SIZE
78  */
79
80 /* Method2: A bit more complex, for pf_read
81  *  - We use ring buffers, only one if unseekable, all if seekable
82  *  - Upon seek date current ring, then search if one ring match the pos,
83  *      yes: switch to it, seek the access to match the end of the ring
84  *      no: search the ring with i_end the closer to i_pos,
85  *          if close enough, read data and use this ring
86  *          else use the oldest ring, seek and use it.
87  *
88  *  TODO: - with access non seekable: use all space available for only one ring, but
89  *          we have to support seekable/non-seekable switch on the fly.
90  *        - compute a good value for i_read_size
91  *        - ?
92  */
93 #define STREAM_READ_ATONCE 32767
94 #define STREAM_CACHE_TRACK_SIZE (STREAM_CACHE_SIZE/STREAM_CACHE_TRACK)
95
96 typedef struct
97 {
98     int64_t i_date;
99
100     int64_t i_start;
101     int64_t i_end;
102
103     uint8_t *p_buffer;
104
105 } stream_track_t;
106
107 typedef struct
108 {
109     char     *psz_path;
110     int64_t  i_size;
111
112 } access_entry_t;
113
114 typedef enum stream_read_method_t
115 {
116     STREAM_METHOD_IMMEDIATE,
117     STREAM_METHOD_BLOCK,
118     STREAM_METHOD_STREAM
119 } stream_read_method_t;
120
121 struct stream_sys_t
122 {
123     access_t    *p_access;
124
125     stream_read_method_t   method;    /* method to use */
126
127     int64_t     i_pos;      /* Current reading offset */
128
129     /* Method 1: pf_block */
130     struct
131     {
132         int64_t i_start;        /* Offset of block for p_first */
133         int64_t i_offset;       /* Offset for data in p_current */
134         block_t *p_current;     /* Current block */
135
136         int     i_size;         /* Total amount of data in the list */
137         block_t *p_first;
138         block_t **pp_last;
139
140     } block;
141
142     /* Method 2: for pf_read */
143     struct
144     {
145         int i_offset;   /* Buffer offset in the current track */
146         int i_tk;       /* Current track */
147         stream_track_t tk[STREAM_CACHE_TRACK];
148
149         /* Global buffer */
150         uint8_t *p_buffer;
151
152         /* */
153         int i_used; /* Used since last read */
154         int i_read_size;
155
156     } stream;
157
158     /* Method 3: for pf_read */
159     struct
160     {
161         int64_t i_end;
162         uint8_t *p_buffer;
163     } immediate;
164
165     /* Peek temporary buffer */
166     unsigned int i_peek;
167     uint8_t *p_peek;
168
169     /* Stat for both method */
170     struct
171     {
172         bool b_fastseek;  /* From access */
173
174         /* Stat about reading data */
175         int64_t i_read_count;
176         int64_t i_bytes;
177         int64_t i_read_time;
178
179         /* Stat about seek */
180         int     i_seek_count;
181         int64_t i_seek_time;
182
183     } stat;
184
185     /* Streams list */
186     int            i_list;
187     access_entry_t **list;
188     int            i_list_index;
189     access_t       *p_list_access;
190
191     /* Preparse mode ? */
192     bool      b_quick;
193
194     /* */
195     struct
196     {
197         bool b_active;
198
199         FILE *f;        /* TODO it could be replaced by access_output_t one day */
200         bool b_error;
201     } record;
202 };
203
204 /* Method 1: */
205 static int  AStreamReadBlock( stream_t *s, void *p_read, unsigned int i_read );
206 static int  AStreamPeekBlock( stream_t *s, const uint8_t **p_peek, unsigned int i_read );
207 static int  AStreamSeekBlock( stream_t *s, int64_t i_pos );
208 static void AStreamPrebufferBlock( stream_t *s );
209 static block_t *AReadBlock( stream_t *s, bool *pb_eof );
210
211 /* Method 2 */
212 static int  AStreamReadStream( stream_t *s, void *p_read, unsigned int i_read );
213 static int  AStreamPeekStream( stream_t *s, const uint8_t **pp_peek, unsigned int i_read );
214 static int  AStreamSeekStream( stream_t *s, int64_t i_pos );
215 static void AStreamPrebufferStream( stream_t *s );
216 static int  AReadStream( stream_t *s, void *p_read, unsigned int i_read );
217
218 /* Method 3 */
219 static int  AStreamReadImmediate( stream_t *s, void *p_read, unsigned int i_read );
220 static int  AStreamPeekImmediate( stream_t *s, const uint8_t **pp_peek, unsigned int i_read );
221 static int  AStreamSeekImmediate( stream_t *s, int64_t i_pos );
222
223 /* Common */
224 static int AStreamControl( stream_t *s, int i_query, va_list );
225 static void AStreamDestroy( stream_t *s );
226 static void UStreamDestroy( stream_t *s );
227 static int  ASeek( stream_t *s, int64_t i_pos );
228 static int  ARecordSetState( stream_t *s, bool b_record, const char *psz_extension );
229 static void ARecordWrite( stream_t *s, const uint8_t *p_buffer, size_t i_buffer );
230
231 /****************************************************************************
232  * Method 3 helpers:
233  ****************************************************************************/
234
235 static inline int64_t stream_buffered_size( stream_t *s )
236 {
237     return s->p_sys->immediate.i_end;
238 }
239
240 static inline void stream_buffer_empty( stream_t *s, int length )
241 {
242     length = __MAX( stream_buffered_size( s ), length );
243     if( length )
244     {
245         memmove( s->p_sys->immediate.p_buffer,
246                  s->p_sys->immediate.p_buffer + length,
247                  stream_buffered_size( s ) - length );
248     }
249     s->p_sys->immediate.i_end -= length;
250 }
251
252 static inline void stream_buffer_fill( stream_t *s, int length )
253 {
254     s->p_sys->immediate.i_end += length;
255 }
256
257 static inline uint8_t * stream_buffer( stream_t *s )
258 {
259     return s->p_sys->immediate.p_buffer;
260 }
261
262 /****************************************************************************
263  * stream_UrlNew: create a stream from a access
264  ****************************************************************************/
265 stream_t *__stream_UrlNew( vlc_object_t *p_parent, const char *psz_url )
266 {
267     const char *psz_access, *psz_demux;
268     char *psz_path;
269     access_t *p_access;
270     stream_t *p_res;
271
272     if( !psz_url )
273         return NULL;
274
275     char psz_dup[strlen( psz_url ) + 1];
276     strcpy( psz_dup, psz_url );
277     input_SplitMRL( &psz_access, &psz_demux, &psz_path, psz_dup );
278
279     /* Now try a real access */
280     p_access = access_New( p_parent, psz_access, psz_demux, psz_path );
281
282     if( p_access == NULL )
283     {
284         msg_Err( p_parent, "no suitable access module for `%s'", psz_url );
285         return NULL;
286     }
287
288     if( !( p_res = stream_AccessNew( p_access, true ) ) )
289     {
290         access_Delete( p_access );
291         return NULL;
292     }
293
294     p_res->pf_destroy = UStreamDestroy;
295     return p_res;
296 }
297
298 stream_t *stream_AccessNew( access_t *p_access, bool b_quick )
299 {
300     stream_t *s = vlc_stream_create( VLC_OBJECT(p_access) );
301     stream_sys_t *p_sys;
302     char *psz_list = NULL;
303
304     if( !s ) return NULL;
305
306     /* Attach it now, needed for b_die */
307     vlc_object_attach( s, p_access );
308
309     s->pf_read   = NULL;    /* Set up later */
310     s->pf_peek   = NULL;
311     s->pf_control = AStreamControl;
312     s->pf_destroy = AStreamDestroy;
313
314     s->p_sys = p_sys = malloc( sizeof( stream_sys_t ) );
315     if( p_sys == NULL )
316         goto error;
317
318     /* UTF16 and UTF32 text file conversion */
319     s->i_char_width = 1;
320     s->b_little_endian = false;
321     s->conv = (vlc_iconv_t)(-1);
322
323     /* Common field */
324     p_sys->p_access = p_access;
325     if( p_access->pf_block )
326         p_sys->method = STREAM_METHOD_BLOCK;
327     else if( var_CreateGetBool( s, "use-stream-immediate" ) )
328         p_sys->method = STREAM_METHOD_IMMEDIATE;
329     else
330         p_sys->method = STREAM_METHOD_STREAM;
331
332     p_sys->record.b_active = false;
333
334     p_sys->i_pos = p_access->info.i_pos;
335
336     /* Stats */
337     access_Control( p_access, ACCESS_CAN_FASTSEEK, &p_sys->stat.b_fastseek );
338     p_sys->stat.i_bytes = 0;
339     p_sys->stat.i_read_time = 0;
340     p_sys->stat.i_read_count = 0;
341     p_sys->stat.i_seek_count = 0;
342     p_sys->stat.i_seek_time = 0;
343
344     p_sys->i_list = 0;
345     p_sys->list = 0;
346     p_sys->i_list_index = 0;
347     p_sys->p_list_access = 0;
348
349     p_sys->b_quick = b_quick;
350
351     /* Get the additional list of inputs if any (for concatenation) */
352     if( (psz_list = var_CreateGetString( s, "input-list" )) && *psz_list )
353     {
354         access_entry_t *p_entry = malloc( sizeof(access_entry_t) );
355         if( p_entry == NULL )
356             goto error;
357         char *psz_name, *psz_parser = psz_name = psz_list;
358
359         p_sys->p_list_access = p_access;
360         p_entry->i_size = p_access->info.i_size;
361         p_entry->psz_path = strdup( p_access->psz_path );
362         if( p_entry->psz_path == NULL )
363         {
364             free( p_entry );
365             goto error;
366         }
367         TAB_APPEND( p_sys->i_list, p_sys->list, p_entry );
368         msg_Dbg( p_access, "adding file `%s', (%"PRId64" bytes)",
369                  p_entry->psz_path, p_access->info.i_size );
370
371         while( psz_name && *psz_name )
372         {
373             psz_parser = strchr( psz_name, ',' );
374             if( psz_parser ) *psz_parser = 0;
375
376             psz_name = strdup( psz_name );
377             if( psz_name )
378             {
379                 access_t *p_tmp = access_New( p_access, p_access->psz_access,
380                                                "", psz_name );
381
382                 if( !p_tmp )
383                 {
384                     psz_name = psz_parser;
385                     if( psz_name ) psz_name++;
386                     continue;
387                 }
388
389                 msg_Dbg( p_access, "adding file `%s', (%"PRId64" bytes)",
390                          psz_name, p_tmp->info.i_size );
391
392                 p_entry = malloc( sizeof(access_entry_t) );
393                 if( p_entry == NULL )
394                     goto error;
395                 p_entry->i_size = p_tmp->info.i_size;
396                 p_entry->psz_path = psz_name;
397                 TAB_APPEND( p_sys->i_list, p_sys->list, p_entry );
398
399                 access_Delete( p_tmp );
400             }
401
402             psz_name = psz_parser;
403             if( psz_name ) psz_name++;
404         }
405     }
406     FREENULL( psz_list );
407
408     /* Peek */
409     p_sys->i_peek = 0;
410     p_sys->p_peek = NULL;
411
412     if( p_sys->method == STREAM_METHOD_BLOCK )
413     {
414         msg_Dbg( s, "Using AStream*Block" );
415         s->pf_read = AStreamReadBlock;
416         s->pf_peek = AStreamPeekBlock;
417
418         /* Init all fields of p_sys->block */
419         p_sys->block.i_start = p_sys->i_pos;
420         p_sys->block.i_offset = 0;
421         p_sys->block.p_current = NULL;
422         p_sys->block.i_size = 0;
423         p_sys->block.p_first = NULL;
424         p_sys->block.pp_last = &p_sys->block.p_first;
425
426         /* Do the prebuffering */
427         AStreamPrebufferBlock( s );
428
429         if( p_sys->block.i_size <= 0 )
430         {
431             msg_Err( s, "cannot pre fill buffer" );
432             goto error;
433         }
434     }
435     else if( p_sys->method == STREAM_METHOD_IMMEDIATE )
436     {
437         msg_Dbg( s, "Using AStream*Immediate" );
438
439         s->pf_read = AStreamReadImmediate;
440         s->pf_peek = AStreamPeekImmediate;
441
442         /* Allocate/Setup our tracks (useful to peek)*/
443         p_sys->immediate.i_end = 0;
444         p_sys->immediate.p_buffer = malloc( STREAM_CACHE_SIZE );
445
446         msg_Dbg( s, "p_buffer %p-%p",
447                  p_sys->immediate.p_buffer,
448                  &p_sys->immediate.p_buffer[STREAM_CACHE_SIZE] );
449
450         if( p_sys->immediate.p_buffer == NULL )
451         {
452             msg_Err( s, "Out of memory when allocating stream cache (%d bytes)",
453                         STREAM_CACHE_SIZE );
454             goto error;
455         }
456     }
457     else
458     {
459         int i;
460
461         assert( p_sys->method == STREAM_METHOD_STREAM );
462
463         msg_Dbg( s, "Using AStream*Stream" );
464
465         s->pf_read = AStreamReadStream;
466         s->pf_peek = AStreamPeekStream;
467
468         /* Allocate/Setup our tracks */
469         p_sys->stream.i_offset = 0;
470         p_sys->stream.i_tk     = 0;
471         p_sys->stream.p_buffer = malloc( STREAM_CACHE_SIZE );
472         if( p_sys->stream.p_buffer == NULL )
473         {
474             msg_Err( s, "Out of memory when allocating stream cache (%d bytes)",
475                         STREAM_CACHE_SIZE );
476             goto error;
477         }
478         p_sys->stream.i_used   = 0;
479         access_Control( p_access, ACCESS_GET_MTU,
480                          &p_sys->stream.i_read_size );
481         if( p_sys->stream.i_read_size <= 0 )
482             p_sys->stream.i_read_size = STREAM_READ_ATONCE;
483         else if( p_sys->stream.i_read_size <= 256 )
484             p_sys->stream.i_read_size = 256;
485
486         for( i = 0; i < STREAM_CACHE_TRACK; i++ )
487         {
488             p_sys->stream.tk[i].i_date  = 0;
489             p_sys->stream.tk[i].i_start = p_sys->i_pos;
490             p_sys->stream.tk[i].i_end   = p_sys->i_pos;
491             p_sys->stream.tk[i].p_buffer=
492                 &p_sys->stream.p_buffer[i * STREAM_CACHE_TRACK_SIZE];
493         }
494
495         /* Do the prebuffering */
496         AStreamPrebufferStream( s );
497
498         if( p_sys->stream.tk[p_sys->stream.i_tk].i_end <= 0 )
499         {
500             msg_Err( s, "cannot pre fill buffer" );
501             goto error;
502         }
503     }
504
505     return s;
506
507 error:
508     if( p_sys->method == STREAM_METHOD_BLOCK )
509     {
510         /* Nothing yet */
511     }
512     else
513     {
514         free( p_sys->stream.p_buffer );
515     }
516     while( p_sys->i_list > 0 )
517         free( p_sys->list[--(p_sys->i_list)] );
518     free( p_sys->list );
519     free( psz_list );
520     free( s->p_sys );
521     vlc_object_detach( s );
522     vlc_object_release( s );
523     return NULL;
524 }
525
526 /****************************************************************************
527  * AStreamDestroy:
528  ****************************************************************************/
529 static void AStreamDestroy( stream_t *s )
530 {
531     stream_sys_t *p_sys = s->p_sys;
532
533     vlc_object_detach( s );
534
535     if( p_sys->record.b_active )
536         ARecordSetState( s, false, NULL );
537
538     if( p_sys->method == STREAM_METHOD_BLOCK )
539         block_ChainRelease( p_sys->block.p_first );
540     else if( p_sys->method == STREAM_METHOD_IMMEDIATE )
541         free( p_sys->immediate.p_buffer );
542     else
543         free( p_sys->stream.p_buffer );
544
545     free( p_sys->p_peek );
546
547     if( p_sys->p_list_access && p_sys->p_list_access != p_sys->p_access )
548         access_Delete( p_sys->p_list_access );
549
550     while( p_sys->i_list-- )
551     {
552         free( p_sys->list[p_sys->i_list]->psz_path );
553         free( p_sys->list[p_sys->i_list] );
554     }
555
556     free( p_sys->list );
557     free( p_sys );
558
559     vlc_object_release( s );
560 }
561
562 static void UStreamDestroy( stream_t *s )
563 {
564     access_t *p_access = (access_t *)s->p_parent;
565     AStreamDestroy( s );
566     access_Delete( p_access );
567 }
568
569 /****************************************************************************
570  * stream_AccessReset:
571  ****************************************************************************/
572 void stream_AccessReset( stream_t *s )
573 {
574     stream_sys_t *p_sys = s->p_sys;
575
576     p_sys->i_pos = p_sys->p_access->info.i_pos;
577
578     if( p_sys->method == STREAM_METHOD_BLOCK )
579     {
580         block_ChainRelease( p_sys->block.p_first );
581
582         /* Init all fields of p_sys->block */
583         p_sys->block.i_start = p_sys->i_pos;
584         p_sys->block.i_offset = 0;
585         p_sys->block.p_current = NULL;
586         p_sys->block.i_size = 0;
587         p_sys->block.p_first = NULL;
588         p_sys->block.pp_last = &p_sys->block.p_first;
589
590         /* Do the prebuffering */
591         AStreamPrebufferBlock( s );
592     }
593     else if( p_sys->method == STREAM_METHOD_IMMEDIATE )
594     {
595         stream_buffer_empty( s, stream_buffered_size( s ) );
596     }
597     else
598     {
599         int i;
600
601         assert( p_sys->method == STREAM_METHOD_STREAM );
602
603         /* Setup our tracks */
604         p_sys->stream.i_offset = 0;
605         p_sys->stream.i_tk     = 0;
606         p_sys->stream.i_used   = 0;
607
608         for( i = 0; i < STREAM_CACHE_TRACK; i++ )
609         {
610             p_sys->stream.tk[i].i_date  = 0;
611             p_sys->stream.tk[i].i_start = p_sys->i_pos;
612             p_sys->stream.tk[i].i_end   = p_sys->i_pos;
613         }
614
615         /* Do the prebuffering */
616         AStreamPrebufferStream( s );
617     }
618 }
619
620 /****************************************************************************
621  * stream_AccessUpdate:
622  ****************************************************************************/
623 void stream_AccessUpdate( stream_t *s )
624 {
625     stream_sys_t *p_sys = s->p_sys;
626
627     p_sys->i_pos = p_sys->p_access->info.i_pos;
628
629     if( p_sys->i_list )
630     {
631         int i;
632         for( i = 0; i < p_sys->i_list_index; i++ )
633         {
634             p_sys->i_pos += p_sys->list[i]->i_size;
635         }
636     }
637 }
638
639 /****************************************************************************
640  * AStreamControl:
641  ****************************************************************************/
642 static int AStreamControl( stream_t *s, int i_query, va_list args )
643 {
644     stream_sys_t *p_sys = s->p_sys;
645     access_t     *p_access = p_sys->p_access;
646
647     bool *p_bool;
648     bool b_bool;
649     const char *psz_string;
650     int64_t    *pi_64, i_64;
651     int        i_int;
652
653     switch( i_query )
654     {
655         case STREAM_GET_SIZE:
656             pi_64 = (int64_t*)va_arg( args, int64_t * );
657             if( s->p_sys->i_list )
658             {
659                 int i;
660                 *pi_64 = 0;
661                 for( i = 0; i < s->p_sys->i_list; i++ )
662                     *pi_64 += s->p_sys->list[i]->i_size;
663                 break;
664             }
665             *pi_64 = p_access->info.i_size;
666             break;
667
668         case STREAM_CAN_SEEK:
669             p_bool = (bool*)va_arg( args, bool * );
670             access_Control( p_access, ACCESS_CAN_SEEK, p_bool );
671             break;
672
673         case STREAM_CAN_FASTSEEK:
674             p_bool = (bool*)va_arg( args, bool * );
675             access_Control( p_access, ACCESS_CAN_FASTSEEK, p_bool );
676             break;
677
678         case STREAM_GET_POSITION:
679             pi_64 = (int64_t*)va_arg( args, int64_t * );
680             *pi_64 = p_sys->i_pos;
681             break;
682
683         case STREAM_SET_POSITION:
684             i_64 = (int64_t)va_arg( args, int64_t );
685             switch( p_sys->method )
686             {
687             case STREAM_METHOD_BLOCK:
688                 return AStreamSeekBlock( s, i_64 );
689             case STREAM_METHOD_IMMEDIATE:
690                 return AStreamSeekImmediate( s, i_64 );
691             case STREAM_METHOD_STREAM:
692                 return AStreamSeekStream( s, i_64 );
693             default:
694                 assert(0);
695                 return VLC_EGENERIC;
696             }
697
698         case STREAM_GET_MTU:
699             return VLC_EGENERIC;
700
701         case STREAM_CONTROL_ACCESS:
702             i_int = (int) va_arg( args, int );
703             if( i_int != ACCESS_SET_PRIVATE_ID_STATE &&
704                 i_int != ACCESS_SET_PRIVATE_ID_CA &&
705                 i_int != ACCESS_GET_PRIVATE_ID_STATE )
706             {
707                 msg_Err( s, "Hey, what are you thinking ?"
708                             "DON'T USE STREAM_CONTROL_ACCESS !!!" );
709                 return VLC_EGENERIC;
710             }
711             return access_vaControl( p_access, i_int, args );
712
713         case STREAM_GET_CONTENT_TYPE:
714             return access_Control( p_access, ACCESS_GET_CONTENT_TYPE,
715                                     va_arg( args, char ** ) );
716         case STREAM_SET_RECORD_STATE:
717             b_bool = (bool)va_arg( args, int );
718             psz_string = NULL;
719             if( b_bool )
720                 psz_string = (const char*)va_arg( args, const char* );
721             return ARecordSetState( s, b_bool, psz_string );
722
723         default:
724             msg_Err( s, "invalid stream_vaControl query=0x%x", i_query );
725             return VLC_EGENERIC;
726     }
727     return VLC_SUCCESS;
728 }
729
730 /****************************************************************************
731  * ARecord*: record stream functions
732  ****************************************************************************/
733 static int  ARecordStart( stream_t *s, const char *psz_extension )
734 {
735     stream_sys_t *p_sys = s->p_sys;
736
737     char *psz_file;
738     FILE *f;
739
740     /* */
741     if( !psz_extension )
742         psz_extension = "dat";
743
744     /* Retreive path */
745     char *psz_path = var_CreateGetString( s, "input-record-path" );
746     if( !psz_path || *psz_path == '\0' )
747     {
748         free( psz_path );
749         psz_path = strdup( config_GetHomeDir() );
750     }
751
752     if( !psz_path )
753         return VLC_ENOMEM;
754
755     /* Create file name
756      * TODO allow prefix configuration */
757     psz_file = input_CreateFilename( VLC_OBJECT(s), psz_path, INPUT_RECORD_PREFIX, psz_extension );
758
759     free( psz_path );
760
761     if( !psz_file )
762         return VLC_ENOMEM;
763
764     f = utf8_fopen( psz_file, "wb" );
765     if( !f )
766     {
767         free( psz_file );
768         return VLC_EGENERIC;
769     }
770     msg_Dbg( s, "Recording into %s", psz_file );
771     free( psz_file );
772
773     /* */
774     p_sys->record.f = f;
775     p_sys->record.b_active = true;
776     p_sys->record.b_error = false;
777     return VLC_SUCCESS;
778 }
779 static int  ARecordStop( stream_t *s )
780 {
781     stream_sys_t *p_sys = s->p_sys;
782
783     assert( p_sys->record.b_active );
784
785     msg_Dbg( s, "Recording completed" );
786     fclose( p_sys->record.f );
787     p_sys->record.b_active = false;
788     return VLC_SUCCESS;
789 }
790
791 static int  ARecordSetState( stream_t *s, bool b_record, const char *psz_extension )
792 {
793     stream_sys_t *p_sys = s->p_sys;
794
795     if( !!p_sys->record.b_active == !!b_record )
796         return VLC_SUCCESS;
797
798     if( b_record )
799         return ARecordStart( s, psz_extension );
800     else
801         return ARecordStop( s );
802 }
803 static void ARecordWrite( stream_t *s, const uint8_t *p_buffer, size_t i_buffer )
804 {
805     stream_sys_t *p_sys = s->p_sys;
806
807     assert( p_sys->record.b_active );
808
809     if( i_buffer > 0 )
810     {
811         const bool b_previous_error = p_sys->record.b_error;
812         const size_t i_written = fwrite( p_buffer, 1, i_buffer, p_sys->record.f );
813
814         p_sys->record.b_error = i_written != i_buffer;
815
816         /* TODO maybe a intf_UserError or something like that ? */
817         if( p_sys->record.b_error && !b_previous_error )
818             msg_Err( s, "Failed to record data (begin)" );
819         else if( !p_sys->record.b_error && b_previous_error )
820             msg_Err( s, "Failed to record data (end)" );
821     }
822 }
823
824 /****************************************************************************
825  * Method 1:
826  ****************************************************************************/
827 static void AStreamPrebufferBlock( stream_t *s )
828 {
829     stream_sys_t *p_sys = s->p_sys;
830     access_t     *p_access = p_sys->p_access;
831
832     int64_t i_first = 0;
833     int64_t i_start;
834
835     msg_Dbg( s, "pre buffering" );
836     i_start = mdate();
837     for( ;; )
838     {
839         int64_t i_date = mdate();
840         bool b_eof;
841         block_t *b;
842
843         if( s->b_die || p_sys->block.i_size > STREAM_CACHE_PREBUFFER_SIZE ||
844             ( i_first > 0 && i_first + STREAM_CACHE_PREBUFFER_LENGTH < i_date ) )
845         {
846             int64_t i_byterate;
847
848             /* Update stat */
849             p_sys->stat.i_bytes = p_sys->block.i_size;
850             p_sys->stat.i_read_time = i_date - i_start;
851             i_byterate = ( INT64_C(1000000) * p_sys->stat.i_bytes ) /
852                          (p_sys->stat.i_read_time + 1);
853
854             msg_Dbg( s, "prebuffering done %"PRId64" bytes in %"PRId64"s - "
855                      "%"PRId64" kbytes/s",
856                      p_sys->stat.i_bytes,
857                      p_sys->stat.i_read_time / INT64_C(1000000),
858                      i_byterate / 1024 );
859             break;
860         }
861
862         /* Fetch a block */
863         if( ( b = AReadBlock( s, &b_eof ) ) == NULL )
864         {
865             if( b_eof )
866                 break;
867             continue;
868         }
869
870         while( b )
871         {
872             /* Append the block */
873             p_sys->block.i_size += b->i_buffer;
874             *p_sys->block.pp_last = b;
875             p_sys->block.pp_last = &b->p_next;
876
877             p_sys->stat.i_read_count++;
878             b = b->p_next;
879         }
880
881         if( p_access->info.b_prebuffered )
882         {
883             /* Access has already prebufferred - update stats and exit */
884             p_sys->stat.i_bytes = p_sys->block.i_size;
885             p_sys->stat.i_read_time = mdate() - i_start;
886             break;
887         }
888
889         if( i_first == 0 )
890         {
891             i_first = mdate();
892             msg_Dbg( s, "received first data for our buffer");
893         }
894
895     }
896
897     p_sys->block.p_current = p_sys->block.p_first;
898 }
899
900 static int AStreamRefillBlock( stream_t *s );
901
902 static int AStreamReadBlock( stream_t *s, void *p_read, unsigned int i_read )
903 {
904     stream_sys_t *p_sys = s->p_sys;
905
906     uint8_t *p_data = p_read;
907     uint8_t *p_record = p_data;
908     unsigned int i_data = 0;
909
910     /* It means EOF */
911     if( p_sys->block.p_current == NULL )
912         return 0;
913
914     if( p_sys->record.b_active && !p_data )
915         p_record = p_data = malloc( i_read );
916
917     if( p_data == NULL )
918     {
919         /* seek within this stream if possible, else use plain old read and discard */
920         stream_sys_t *p_sys = s->p_sys;
921         access_t     *p_access = p_sys->p_access;
922         bool   b_aseek;
923         access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
924         if( b_aseek )
925             return AStreamSeekBlock( s, p_sys->i_pos + i_read ) ? 0 : i_read;
926     }
927
928     while( i_data < i_read )
929     {
930         int i_current =
931             p_sys->block.p_current->i_buffer - p_sys->block.i_offset;
932         unsigned int i_copy = __MIN( (unsigned int)__MAX(i_current,0), i_read - i_data);
933
934         /* Copy data */
935         if( p_data )
936         {
937             memcpy( p_data,
938                     &p_sys->block.p_current->p_buffer[p_sys->block.i_offset],
939                     i_copy );
940             p_data += i_copy;
941         }
942         i_data += i_copy;
943
944         p_sys->block.i_offset += i_copy;
945         if( p_sys->block.i_offset >= p_sys->block.p_current->i_buffer )
946         {
947             /* Current block is now empty, switch to next */
948             if( p_sys->block.p_current )
949             {
950                 p_sys->block.i_offset = 0;
951                 p_sys->block.p_current = p_sys->block.p_current->p_next;
952             }
953             /*Get a new block if needed */
954             if( !p_sys->block.p_current && AStreamRefillBlock( s ) )
955             {
956                 break;
957             }
958         }
959     }
960
961     if( p_sys->record.b_active )
962     {
963         if( i_data > 0 && p_record != NULL)
964             ARecordWrite( s, p_record, i_data );
965         if( !p_read )
966             free( p_record );
967     }
968
969     p_sys->i_pos += i_data;
970     return i_data;
971 }
972
973 static int AStreamPeekBlock( stream_t *s, const uint8_t **pp_peek, unsigned int i_read )
974 {
975     stream_sys_t *p_sys = s->p_sys;
976     uint8_t *p_data;
977     unsigned int i_data = 0;
978     block_t *b;
979     unsigned int i_offset;
980
981     if( p_sys->block.p_current == NULL ) return 0; /* EOF */
982
983     /* We can directly give a pointer over our buffer */
984     if( i_read <= p_sys->block.p_current->i_buffer - p_sys->block.i_offset )
985     {
986         *pp_peek = &p_sys->block.p_current->p_buffer[p_sys->block.i_offset];
987         return i_read;
988     }
989
990     /* We need to create a local copy */
991     if( p_sys->i_peek < i_read )
992     {
993         p_sys->p_peek = realloc( p_sys->p_peek, i_read );
994         if( !p_sys->p_peek )
995         {
996             p_sys->i_peek = 0;
997             return 0;
998         }
999         p_sys->i_peek = i_read;
1000     }
1001
1002     /* Fill enough data */
1003     while( p_sys->block.i_size - (p_sys->i_pos - p_sys->block.i_start)
1004            < i_read )
1005     {
1006         block_t **pp_last = p_sys->block.pp_last;
1007
1008         if( AStreamRefillBlock( s ) ) break;
1009
1010         /* Our buffer are probably filled enough, don't try anymore */
1011         if( pp_last == p_sys->block.pp_last ) break;
1012     }
1013
1014     /* Copy what we have */
1015     b = p_sys->block.p_current;
1016     i_offset = p_sys->block.i_offset;
1017     p_data = p_sys->p_peek;
1018
1019     while( b && i_data < i_read )
1020     {
1021         unsigned int i_current = __MAX(b->i_buffer - i_offset,0);
1022         int i_copy = __MIN( i_current, i_read - i_data );
1023
1024         memcpy( p_data, &b->p_buffer[i_offset], i_copy );
1025         i_data += i_copy;
1026         p_data += i_copy;
1027         i_offset += i_copy;
1028
1029         if( i_offset >= b->i_buffer )
1030         {
1031             i_offset = 0;
1032             b = b->p_next;
1033         }
1034     }
1035
1036     *pp_peek = p_sys->p_peek;
1037     return i_data;
1038 }
1039
1040 static int AStreamSeekBlock( stream_t *s, int64_t i_pos )
1041 {
1042     stream_sys_t *p_sys = s->p_sys;
1043     access_t   *p_access = p_sys->p_access;
1044     int64_t    i_offset = i_pos - p_sys->block.i_start;
1045     bool b_seek;
1046
1047     /* We already have thoses data, just update p_current/i_offset */
1048     if( i_offset >= 0 && i_offset < p_sys->block.i_size )
1049     {
1050         block_t *b = p_sys->block.p_first;
1051         int i_current = 0;
1052
1053         while( i_current + b->i_buffer < i_offset )
1054         {
1055             i_current += b->i_buffer;
1056             b = b->p_next;
1057         }
1058
1059         p_sys->block.p_current = b;
1060         p_sys->block.i_offset = i_offset - i_current;
1061
1062         p_sys->i_pos = i_pos;
1063
1064         return VLC_SUCCESS;
1065     }
1066
1067     /* We may need to seek or to read data */
1068     if( i_offset < 0 )
1069     {
1070         bool b_aseek;
1071         access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
1072
1073         if( !b_aseek )
1074         {
1075             msg_Err( s, "backward seeking impossible (access not seekable)" );
1076             return VLC_EGENERIC;
1077         }
1078
1079         b_seek = true;
1080     }
1081     else
1082     {
1083         bool b_aseek, b_aseekfast;
1084
1085         access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
1086         access_Control( p_access, ACCESS_CAN_FASTSEEK, &b_aseekfast );
1087
1088         if( !b_aseek )
1089         {
1090             b_seek = false;
1091             msg_Warn( s, "%"PRId64" bytes need to be skipped "
1092                       "(access non seekable)",
1093                       i_offset - p_sys->block.i_size );
1094         }
1095         else
1096         {
1097             int64_t i_skip = i_offset - p_sys->block.i_size;
1098
1099             /* Avg bytes per packets */
1100             int i_avg = p_sys->stat.i_bytes / p_sys->stat.i_read_count;
1101             /* TODO compute a seek cost instead of fixed threshold */
1102             int i_th = b_aseekfast ? 1 : 5;
1103
1104             if( i_skip <= i_th * i_avg &&
1105                 i_skip < STREAM_CACHE_SIZE )
1106                 b_seek = false;
1107             else
1108                 b_seek = true;
1109
1110             msg_Dbg( s, "b_seek=%d th*avg=%d skip=%"PRId64,
1111                      b_seek, i_th*i_avg, i_skip );
1112         }
1113     }
1114
1115     if( b_seek )
1116     {
1117         int64_t i_start, i_end;
1118         /* Do the access seek */
1119         i_start = mdate();
1120         if( ASeek( s, i_pos ) ) return VLC_EGENERIC;
1121         i_end = mdate();
1122
1123         /* Release data */
1124         block_ChainRelease( p_sys->block.p_first );
1125
1126         /* Reinit */
1127         p_sys->block.i_start = p_sys->i_pos = i_pos;
1128         p_sys->block.i_offset = 0;
1129         p_sys->block.p_current = NULL;
1130         p_sys->block.i_size = 0;
1131         p_sys->block.p_first = NULL;
1132         p_sys->block.pp_last = &p_sys->block.p_first;
1133
1134         /* Refill a block */
1135         if( AStreamRefillBlock( s ) )
1136             return VLC_EGENERIC;
1137
1138         /* Update stat */
1139         p_sys->stat.i_seek_time += i_end - i_start;
1140         p_sys->stat.i_seek_count++;
1141         return VLC_SUCCESS;
1142     }
1143     else
1144     {
1145         do
1146         {
1147             /* Read and skip enough data */
1148             if( AStreamRefillBlock( s ) )
1149                 return VLC_EGENERIC;
1150
1151             while( p_sys->block.p_current &&
1152                    p_sys->i_pos + p_sys->block.p_current->i_buffer - p_sys->block.i_offset < i_pos )
1153             {
1154                 p_sys->i_pos += p_sys->block.p_current->i_buffer - p_sys->block.i_offset;
1155                 p_sys->block.p_current = p_sys->block.p_current->p_next;
1156                 p_sys->block.i_offset = 0;
1157             }
1158         }
1159         while( p_sys->block.i_start + p_sys->block.i_size < i_pos );
1160
1161         p_sys->block.i_offset = i_pos - p_sys->i_pos;
1162         p_sys->i_pos = i_pos;
1163
1164         return VLC_SUCCESS;
1165     }
1166
1167     return VLC_EGENERIC;
1168 }
1169
1170 static int AStreamRefillBlock( stream_t *s )
1171 {
1172     stream_sys_t *p_sys = s->p_sys;
1173     int64_t      i_start, i_stop;
1174     block_t      *b;
1175
1176     /* Release data */
1177     while( p_sys->block.i_size >= STREAM_CACHE_SIZE &&
1178            p_sys->block.p_first != p_sys->block.p_current )
1179     {
1180         block_t *b = p_sys->block.p_first;
1181
1182         p_sys->block.i_start += b->i_buffer;
1183         p_sys->block.i_size  -= b->i_buffer;
1184         p_sys->block.p_first  = b->p_next;
1185
1186         block_Release( b );
1187     }
1188     if( p_sys->block.i_size >= STREAM_CACHE_SIZE &&
1189         p_sys->block.p_current == p_sys->block.p_first &&
1190         p_sys->block.p_current->p_next )    /* At least 2 packets */
1191     {
1192         /* Enough data, don't read more */
1193         return VLC_SUCCESS;
1194     }
1195
1196     /* Now read a new block */
1197     i_start = mdate();
1198     for( ;; )
1199     {
1200         bool b_eof;
1201
1202         if( s->b_die )
1203             return VLC_EGENERIC;
1204
1205         /* Fetch a block */
1206         if( ( b = AReadBlock( s, &b_eof ) ) )
1207             break;
1208         if( b_eof )
1209             return VLC_EGENERIC;
1210     }
1211
1212     while( b )
1213     {
1214         i_stop = mdate();
1215
1216         /* Append the block */
1217         p_sys->block.i_size += b->i_buffer;
1218         *p_sys->block.pp_last = b;
1219         p_sys->block.pp_last = &b->p_next;
1220
1221         /* Fix p_current */
1222         if( p_sys->block.p_current == NULL )
1223             p_sys->block.p_current = b;
1224
1225         /* Update stat */
1226         p_sys->stat.i_bytes += b->i_buffer;
1227         p_sys->stat.i_read_time += i_stop - i_start;
1228         p_sys->stat.i_read_count++;
1229
1230         b = b->p_next;
1231         i_start = mdate();
1232     }
1233     return VLC_SUCCESS;
1234 }
1235
1236
1237 /****************************************************************************
1238  * Method 2:
1239  ****************************************************************************/
1240 static int AStreamRefillStream( stream_t *s );
1241
1242 static int AStreamReadStream( stream_t *s, void *p_read, unsigned int i_read )
1243 {
1244     stream_sys_t *p_sys = s->p_sys;
1245     stream_track_t *tk = &p_sys->stream.tk[p_sys->stream.i_tk];
1246
1247     uint8_t *p_data = (uint8_t *)p_read;
1248     uint8_t *p_record = p_data;
1249     unsigned int i_data = 0;
1250
1251     if( tk->i_start >= tk->i_end )
1252         return 0; /* EOF */
1253
1254     if( p_sys->record.b_active && !p_data )
1255         p_record = p_data = malloc( i_read );
1256
1257     if( p_data == NULL )
1258     {
1259         /* seek within this stream if possible, else use plain old read and discard */
1260         stream_sys_t *p_sys = s->p_sys;
1261         access_t     *p_access = p_sys->p_access;
1262
1263         /* seeking after EOF is not what we want */
1264         if( !( p_access->info.b_eof ) )
1265         {
1266             bool   b_aseek;
1267             access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
1268             if( b_aseek )
1269                 return AStreamSeekStream( s, p_sys->i_pos + i_read ) ? 0 : i_read;
1270         }
1271     }
1272
1273 #ifdef STREAM_DEBUG
1274     msg_Dbg( s, "AStreamReadStream: %d pos=%"PRId64" tk=%d start=%"PRId64
1275              " offset=%d end=%"PRId64,
1276              i_read, p_sys->i_pos, p_sys->stream.i_tk,
1277              tk->i_start, p_sys->stream.i_offset, tk->i_end );
1278 #endif
1279
1280     while( i_data < i_read )
1281     {
1282         int i_off = (tk->i_start + p_sys->stream.i_offset) %
1283                     STREAM_CACHE_TRACK_SIZE;
1284         unsigned int i_current =
1285             __MAX(0,__MIN( tk->i_end - tk->i_start - p_sys->stream.i_offset,
1286                    STREAM_CACHE_TRACK_SIZE - i_off ));
1287         int i_copy = __MIN( i_current, i_read - i_data );
1288
1289         if( i_copy <= 0 ) break; /* EOF */
1290
1291         /* Copy data */
1292         /* msg_Dbg( s, "AStreamReadStream: copy %d", i_copy ); */
1293         if( p_data )
1294         {
1295             memcpy( p_data, &tk->p_buffer[i_off], i_copy );
1296             p_data += i_copy;
1297         }
1298         i_data += i_copy;
1299         p_sys->stream.i_offset += i_copy;
1300
1301         /* Update pos now */
1302         p_sys->i_pos += i_copy;
1303
1304         /* */
1305         p_sys->stream.i_used += i_copy;
1306         if( tk->i_start + p_sys->stream.i_offset >= tk->i_end ||
1307             p_sys->stream.i_used >= p_sys->stream.i_read_size )
1308         {
1309             if( AStreamRefillStream( s ) )
1310             {
1311                 /* EOF */
1312                 if( tk->i_start >= tk->i_end ) break;
1313             }
1314         }
1315     }
1316
1317     if( p_sys->record.b_active )
1318     {
1319         if( i_data > 0 && p_record != NULL)
1320             ARecordWrite( s, p_record, i_data );
1321         if( !p_read )
1322             free( p_record );
1323     }
1324
1325     return i_data;
1326 }
1327
1328 static int AStreamPeekStream( stream_t *s, const uint8_t **pp_peek, unsigned int i_read )
1329 {
1330     stream_sys_t *p_sys = s->p_sys;
1331     stream_track_t *tk = &p_sys->stream.tk[p_sys->stream.i_tk];
1332     int64_t i_off;
1333
1334     if( tk->i_start >= tk->i_end ) return 0; /* EOF */
1335
1336 #ifdef STREAM_DEBUG
1337     msg_Dbg( s, "AStreamPeekStream: %d pos=%"PRId64" tk=%d "
1338              "start=%"PRId64" offset=%d end=%"PRId64,
1339              i_read, p_sys->i_pos, p_sys->stream.i_tk,
1340              tk->i_start, p_sys->stream.i_offset, tk->i_end );
1341 #endif
1342
1343     /* Avoid problem, but that should *never* happen */
1344     if( i_read > STREAM_CACHE_TRACK_SIZE / 2 )
1345         i_read = STREAM_CACHE_TRACK_SIZE / 2;
1346
1347     while( tk->i_end - tk->i_start - p_sys->stream.i_offset < i_read )
1348     {
1349         if( p_sys->stream.i_used <= 1 )
1350         {
1351             /* Be sure we will read something */
1352             p_sys->stream.i_used += i_read -
1353                 (tk->i_end - tk->i_start - p_sys->stream.i_offset);
1354         }
1355         if( AStreamRefillStream( s ) ) break;
1356     }
1357
1358     if( tk->i_end - tk->i_start - p_sys->stream.i_offset < i_read )
1359         i_read = tk->i_end - tk->i_start - p_sys->stream.i_offset;
1360
1361     /* Now, direct pointer or a copy ? */
1362     i_off = (tk->i_start + p_sys->stream.i_offset) % STREAM_CACHE_TRACK_SIZE;
1363     if( i_off + i_read <= STREAM_CACHE_TRACK_SIZE )
1364     {
1365         *pp_peek = &tk->p_buffer[i_off];
1366         return i_read;
1367     }
1368
1369     if( p_sys->i_peek < i_read )
1370     {
1371         p_sys->p_peek = realloc( p_sys->p_peek, i_read );
1372         if( !p_sys->p_peek )
1373         {
1374             p_sys->i_peek = 0;
1375             return 0;
1376         }
1377         p_sys->i_peek = i_read;
1378     }
1379
1380     memcpy( p_sys->p_peek, &tk->p_buffer[i_off],
1381             STREAM_CACHE_TRACK_SIZE - i_off );
1382     memcpy( &p_sys->p_peek[STREAM_CACHE_TRACK_SIZE - i_off],
1383             &tk->p_buffer[0], i_read - (STREAM_CACHE_TRACK_SIZE - i_off) );
1384
1385     *pp_peek = p_sys->p_peek;
1386     return i_read;
1387 }
1388
1389 static int AStreamSeekStream( stream_t *s, int64_t i_pos )
1390 {
1391     stream_sys_t *p_sys = s->p_sys;
1392     access_t     *p_access = p_sys->p_access;
1393     bool   b_aseek;
1394     bool   b_afastseek;
1395     int i_maxth;
1396     int i_new;
1397     int i;
1398
1399 #ifdef STREAM_DEBUG
1400     msg_Dbg( s, "AStreamSeekStream: to %"PRId64" pos=%"PRId64
1401              " tk=%d start=%"PRId64" offset=%d end=%"PRId64,
1402              i_pos, p_sys->i_pos, p_sys->stream.i_tk,
1403              p_sys->stream.tk[p_sys->stream.i_tk].i_start,
1404              p_sys->stream.i_offset,
1405              p_sys->stream.tk[p_sys->stream.i_tk].i_end );
1406 #endif
1407
1408
1409     /* Seek in our current track ? */
1410     if( i_pos >= p_sys->stream.tk[p_sys->stream.i_tk].i_start &&
1411         i_pos < p_sys->stream.tk[p_sys->stream.i_tk].i_end )
1412     {
1413         stream_track_t *tk = &p_sys->stream.tk[p_sys->stream.i_tk];
1414 #ifdef STREAM_DEBUG
1415         msg_Dbg( s, "AStreamSeekStream: current track" );
1416 #endif
1417         p_sys->i_pos = i_pos;
1418         p_sys->stream.i_offset = i_pos - tk->i_start;
1419
1420         /* If there is not enough data left in the track, refill  */
1421         /* \todo How to get a correct value for
1422          *    - refilling threshold
1423          *    - how much to refill
1424          */
1425         if( (tk->i_end - tk->i_start ) - p_sys->stream.i_offset <
1426                                              p_sys->stream.i_read_size )
1427         {
1428             if( p_sys->stream.i_used < STREAM_READ_ATONCE / 2  )
1429             {
1430                 p_sys->stream.i_used = STREAM_READ_ATONCE / 2 ;
1431                 AStreamRefillStream( s );
1432             }
1433         }
1434         return VLC_SUCCESS;
1435     }
1436
1437     access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
1438     if( !b_aseek )
1439     {
1440         /* We can't do nothing */
1441         msg_Dbg( s, "AStreamSeekStream: can't seek" );
1442         return VLC_EGENERIC;
1443     }
1444
1445     /* Date the current track */
1446     p_sys->stream.tk[p_sys->stream.i_tk].i_date = mdate();
1447
1448     /* Try to reuse already read data */
1449     for( i = 0; i < STREAM_CACHE_TRACK; i++ )
1450     {
1451         stream_track_t *tk = &p_sys->stream.tk[i];
1452
1453         if( i_pos >= tk->i_start && i_pos <= tk->i_end )
1454         {
1455 #ifdef STREAM_DEBUG
1456             msg_Dbg( s, "AStreamSeekStream: reusing %d start=%"PRId64
1457                      " end=%"PRId64, i, tk->i_start, tk->i_end );
1458 #endif
1459
1460             /* Seek at the end of the buffer */
1461             if( ASeek( s, tk->i_end ) ) return VLC_EGENERIC;
1462
1463             /* That's it */
1464             p_sys->i_pos = i_pos;
1465             p_sys->stream.i_tk = i;
1466             p_sys->stream.i_offset = i_pos - tk->i_start;
1467
1468             if( p_sys->stream.i_used < 1024 )
1469                 p_sys->stream.i_used = 1024;
1470
1471             if( AStreamRefillStream( s ) && i_pos == tk->i_end )
1472                 return VLC_EGENERIC;
1473
1474             return VLC_SUCCESS;
1475         }
1476     }
1477
1478     access_Control( p_access, ACCESS_CAN_SEEK, &b_afastseek );
1479     /* FIXME compute seek cost (instead of static 'stupid' value) */
1480     i_maxth = __MIN( p_sys->stream.i_read_size, STREAM_READ_ATONCE / 2 );
1481     if( !b_afastseek )
1482         i_maxth *= 3;
1483
1484     /* FIXME TODO */
1485 #if 0
1486     /* Search closest segment TODO */
1487     for( i = 0; i < STREAM_CACHE_TRACK; i++ )
1488     {
1489         stream_track_t *tk = &p_sys->stream.tk[i];
1490
1491         if( i_pos + i_maxth >= tk->i_start )
1492         {
1493             msg_Dbg( s, "good segment before current pos, TODO" );
1494         }
1495         if( i_pos - i_maxth <= tk->i_end )
1496         {
1497             msg_Dbg( s, "good segment after current pos, TODO" );
1498         }
1499     }
1500 #endif
1501
1502     /* Nothing good, seek and choose oldest segment */
1503     if( ASeek( s, i_pos ) ) return VLC_EGENERIC;
1504     p_sys->i_pos = i_pos;
1505
1506     i_new = 0;
1507     for( i = 1; i < STREAM_CACHE_TRACK; i++ )
1508     {
1509         if( p_sys->stream.tk[i].i_date < p_sys->stream.tk[i_new].i_date )
1510             i_new = i;
1511     }
1512
1513     /* Reset the segment */
1514     p_sys->stream.i_tk     = i_new;
1515     p_sys->stream.i_offset =  0;
1516     p_sys->stream.tk[i_new].i_start = i_pos;
1517     p_sys->stream.tk[i_new].i_end   = i_pos;
1518
1519     /* Read data */
1520     if( p_sys->stream.i_used < STREAM_READ_ATONCE / 2 )
1521         p_sys->stream.i_used = STREAM_READ_ATONCE / 2;
1522
1523     if( AStreamRefillStream( s ) )
1524         return VLC_EGENERIC;
1525
1526     return VLC_SUCCESS;
1527 }
1528
1529 static int AStreamRefillStream( stream_t *s )
1530 {
1531     stream_sys_t *p_sys = s->p_sys;
1532     stream_track_t *tk = &p_sys->stream.tk[p_sys->stream.i_tk];
1533
1534     /* We read but won't increase i_start after initial start + offset */
1535     int i_toread =
1536         __MIN( p_sys->stream.i_used, STREAM_CACHE_TRACK_SIZE -
1537                (tk->i_end - tk->i_start - p_sys->stream.i_offset) );
1538     bool b_read = false;
1539     int64_t i_start, i_stop;
1540
1541     if( i_toread <= 0 ) return VLC_EGENERIC; /* EOF */
1542
1543 #ifdef STREAM_DEBUG
1544     msg_Dbg( s, "AStreamRefillStream: used=%d toread=%d",
1545                  p_sys->stream.i_used, i_toread );
1546 #endif
1547
1548     i_start = mdate();
1549     while( i_toread > 0 )
1550     {
1551         int i_off = tk->i_end % STREAM_CACHE_TRACK_SIZE;
1552         int i_read;
1553
1554         if( s->b_die )
1555             return VLC_EGENERIC;
1556
1557         i_read = __MIN( i_toread, STREAM_CACHE_TRACK_SIZE - i_off );
1558         i_read = AReadStream( s, &tk->p_buffer[i_off], i_read );
1559
1560         /* msg_Dbg( s, "AStreamRefillStream: read=%d", i_read ); */
1561         if( i_read <  0 )
1562         {
1563             continue;
1564         }
1565         else if( i_read == 0 )
1566         {
1567             if( !b_read )
1568                 return VLC_EGENERIC;
1569             return VLC_SUCCESS;
1570         }
1571         b_read = true;
1572
1573         /* Update end */
1574         tk->i_end += i_read;
1575
1576         /* Windows of STREAM_CACHE_TRACK_SIZE */
1577         if( tk->i_end - tk->i_start > STREAM_CACHE_TRACK_SIZE )
1578         {
1579             int i_invalid = tk->i_end - tk->i_start - STREAM_CACHE_TRACK_SIZE;
1580
1581             tk->i_start += i_invalid;
1582             p_sys->stream.i_offset -= i_invalid;
1583         }
1584
1585         i_toread -= i_read;
1586         p_sys->stream.i_used -= i_read;
1587
1588         p_sys->stat.i_bytes += i_read;
1589         p_sys->stat.i_read_count++;
1590     }
1591     i_stop = mdate();
1592
1593     p_sys->stat.i_read_time += i_stop - i_start;
1594
1595     return VLC_SUCCESS;
1596 }
1597
1598 static void AStreamPrebufferStream( stream_t *s )
1599 {
1600     stream_sys_t *p_sys = s->p_sys;
1601     access_t     *p_access = p_sys->p_access;
1602
1603     int64_t i_first = 0;
1604     int64_t i_start;
1605     int64_t i_prebuffer = p_sys->b_quick ? STREAM_CACHE_TRACK_SIZE /100 :
1606         ( (p_access->info.i_title > 1 || p_access->info.i_seekpoint > 1) ?
1607           STREAM_CACHE_PREBUFFER_SIZE : STREAM_CACHE_TRACK_SIZE / 3 );
1608
1609     msg_Dbg( s, "pre-buffering..." );
1610     i_start = mdate();
1611     for( ;; )
1612     {
1613         stream_track_t *tk = &p_sys->stream.tk[p_sys->stream.i_tk];
1614
1615         int64_t i_date = mdate();
1616         int i_read;
1617
1618         if( s->b_die || tk->i_end >= i_prebuffer ||
1619             (i_first > 0 && i_first + STREAM_CACHE_PREBUFFER_LENGTH < i_date) )
1620         {
1621             int64_t i_byterate;
1622
1623             /* Update stat */
1624             p_sys->stat.i_bytes = tk->i_end - tk->i_start;
1625             p_sys->stat.i_read_time = i_date - i_start;
1626             i_byterate = ( INT64_C(1000000) * p_sys->stat.i_bytes ) /
1627                          (p_sys->stat.i_read_time+1);
1628
1629             msg_Dbg( s, "pre-buffering done %"PRId64" bytes in %"PRId64"s - "
1630                      "%"PRId64" kbytes/s",
1631                      p_sys->stat.i_bytes,
1632                      p_sys->stat.i_read_time / INT64_C(1000000),
1633                      i_byterate / 1024 );
1634             break;
1635         }
1636
1637         /* */
1638         i_read = STREAM_CACHE_TRACK_SIZE - tk->i_end;
1639         i_read = __MIN( p_sys->stream.i_read_size, i_read );
1640         i_read = AReadStream( s, &tk->p_buffer[tk->i_end], i_read );
1641         if( i_read <  0 )
1642             continue;
1643         else if( i_read == 0 )
1644             break;  /* EOF */
1645
1646         if( i_first == 0 )
1647         {
1648             i_first = mdate();
1649             msg_Dbg( s, "received first data for our buffer");
1650         }
1651
1652         tk->i_end += i_read;
1653
1654         p_sys->stat.i_read_count++;
1655     }
1656 }
1657
1658 /****************************************************************************
1659  * Method 3:
1660  ****************************************************************************/
1661
1662 static int AStreamReadImmediate( stream_t *s, void *p_read, unsigned int i_read )
1663 {
1664     stream_sys_t *p_sys = s->p_sys;
1665     uint8_t *p_data= (uint8_t*)p_read;
1666     uint8_t *p_record = p_data;
1667     unsigned int i_data;
1668
1669 #ifdef STREAM_DEBUG
1670     msg_Dbg( s, "AStreamReadImmediate p_read=%p i_read=%d",
1671              p_read, i_read );
1672 #endif
1673
1674     if( p_sys->record.b_active && !p_data )
1675         p_record = p_data = malloc( i_read );
1676
1677     /* First, check if we already have some data in the buffer,
1678      * that we could copy directly */
1679     i_data = __MIN( stream_buffered_size( s ), i_read );
1680     if( i_data > 0 )
1681     {
1682 #ifdef STREAM_DEBUG
1683         msg_Dbg( s, "AStreamReadImmediate: copy %u from %p", i_data, stream_buffer( s ) );
1684 #endif
1685
1686         assert( i_data <= STREAM_CACHE_SIZE );
1687
1688         if( p_data )
1689         {
1690             memcpy( p_data, stream_buffer( s ), i_data );
1691             p_data += i_data;
1692         }
1693     }
1694
1695     /* Now that we've read our buffer we don't need its i_copy bytes */
1696     stream_buffer_empty( s, i_data );
1697
1698     /* Now check if we have still to really read some data */
1699     while( i_data < i_read )
1700     {
1701         const unsigned int i_to_read = i_read - i_data;
1702         int i_result;
1703
1704         if( p_data )
1705         {
1706             i_result = AReadStream( s, p_data, i_to_read );
1707         }
1708         else
1709         {
1710             void *p_dummy = malloc( i_to_read );
1711
1712             if( !p_dummy )
1713                 break;
1714
1715             i_result = AReadStream( s, p_dummy, i_to_read );
1716
1717             free( p_dummy );
1718         }
1719         if( i_result <= 0 )
1720             break;
1721
1722         p_sys->i_pos += i_data;
1723         if( p_data )
1724             p_data += i_result;
1725         i_data += i_result;
1726     }
1727
1728     if( p_sys->record.b_active )
1729     {
1730         if( i_data > 0 && p_record != NULL)
1731             ARecordWrite( s, p_record, i_data );
1732         if( !p_read )
1733             free( p_record );
1734     }
1735     return i_data;
1736 }
1737
1738 static int AStreamPeekImmediate( stream_t *s, const uint8_t **pp_peek, unsigned int i_read )
1739 {
1740 #ifdef STREAM_DEBUG
1741     msg_Dbg( s, "AStreamPeekImmediate: %d  size=%"PRId64,
1742              i_read, size_buffered_size( s ) );
1743 #endif
1744
1745     /* Avoid problem, but that shouldn't happen
1746      * FIXME yes it can */
1747     if( i_read > STREAM_CACHE_SIZE / 2 )
1748         i_read = STREAM_CACHE_SIZE / 2;
1749
1750     int i_to_read = i_read - stream_buffered_size( s );
1751     if( i_to_read > 0 )
1752     {
1753 #ifdef STREAM_DEBUG
1754         msg_Dbg( s, "AStreamPeekImmediate: Reading %d",
1755              i_to_read );
1756 #endif
1757         i_to_read = AReadStream( s, stream_buffer( s ) + stream_buffered_size( s ),
1758                                  i_to_read );
1759
1760         if( i_to_read > 0 )
1761             stream_buffer_fill( s, i_to_read );
1762     }
1763
1764     *pp_peek = stream_buffer( s );
1765
1766     return __MIN( stream_buffered_size( s ), i_read );
1767 }
1768
1769 static int AStreamSeekImmediate( stream_t *s, int64_t i_pos )
1770 {
1771     stream_sys_t *p_sys = s->p_sys;
1772     access_t     *p_access = p_sys->p_access;
1773     bool   b_aseek;
1774
1775 #ifdef STREAM_DEBUG
1776     msg_Dbg( s, "AStreamSeekImmediate to %"PRId64" pos=%"PRId64
1777              i_pos, p_sys->i_pos );
1778 #endif
1779
1780     access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
1781     if( !b_aseek )
1782     {
1783         /* We can't do nothing */
1784         msg_Dbg( s, "AStreamSeekImmediate: can't seek" );
1785         return VLC_EGENERIC;
1786     }
1787
1788     /* Just reset our buffer */
1789     stream_buffer_empty( s, stream_buffered_size( s ) );
1790
1791     if( ASeek( s, i_pos ) )
1792         return VLC_EGENERIC;
1793
1794     return VLC_SUCCESS;
1795 }
1796
1797 /****************************************************************************
1798  * stream_ReadLine:
1799  ****************************************************************************/
1800 /**
1801  * Read from the stream untill first newline.
1802  * \param s Stream handle to read from
1803  * \return A pointer to the allocated output string. You need to free this when you are done.
1804  */
1805 #define STREAM_PROBE_LINE 2048
1806 #define STREAM_LINE_MAX (2048*100)
1807 char *stream_ReadLine( stream_t *s )
1808 {
1809     char *p_line = NULL;
1810     int i_line = 0, i_read = 0;
1811
1812     while( i_read < STREAM_LINE_MAX )
1813     {
1814         char *psz_eol;
1815         const uint8_t *p_data;
1816         int i_data;
1817         int64_t i_pos;
1818
1819         /* Probe new data */
1820         i_data = stream_Peek( s, &p_data, STREAM_PROBE_LINE );
1821         if( i_data <= 0 ) break; /* No more data */
1822
1823         /* BOM detection */
1824         i_pos = stream_Tell( s );
1825         if( i_pos == 0 && i_data >= 3 )
1826         {
1827             int i_bom_size = 0;
1828             const char *psz_encoding = NULL;
1829
1830             if( !memcmp( p_data, "\xEF\xBB\xBF", 3 ) )
1831             {
1832                 psz_encoding = "UTF-8";
1833                 i_bom_size = 3;
1834             }
1835             else if( !memcmp( p_data, "\xFF\xFE", 2 ) )
1836             {
1837                 psz_encoding = "UTF-16LE";
1838                 s->b_little_endian = true;
1839                 s->i_char_width = 2;
1840                 i_bom_size = 2;
1841             }
1842             else if( !memcmp( p_data, "\xFE\xFF", 2 ) )
1843             {
1844                 psz_encoding = "UTF-16BE";
1845                 s->i_char_width = 2;
1846                 i_bom_size = 2;
1847             }
1848
1849             /* Seek past the BOM */
1850             if( i_bom_size )
1851             {
1852                 stream_Seek( s, i_bom_size );
1853                 p_data += i_bom_size;
1854                 i_data -= i_bom_size;
1855             }
1856
1857             /* Open the converter if we need it */
1858             if( psz_encoding != NULL )
1859             {
1860                 input_thread_t *p_input;
1861                 msg_Dbg( s, "%s BOM detected", psz_encoding );
1862                 p_input = (input_thread_t *)vlc_object_find( s, VLC_OBJECT_INPUT, FIND_PARENT );
1863                 if( s->i_char_width > 1 )
1864                 {
1865                     s->conv = vlc_iconv_open( "UTF-8", psz_encoding );
1866                     if( s->conv == (vlc_iconv_t)-1 )
1867                     {
1868                         msg_Err( s, "iconv_open failed" );
1869                     }
1870                 }
1871                 if( p_input != NULL)
1872                 {
1873                     var_Create( p_input, "subsdec-encoding", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
1874                     var_SetString( p_input, "subsdec-encoding", "UTF-8" );
1875                     vlc_object_release( p_input );
1876                 }
1877             }
1878         }
1879
1880         if( i_data % s->i_char_width )
1881         {
1882             /* keep i_char_width boundary */
1883             i_data = i_data - ( i_data % s->i_char_width );
1884             msg_Warn( s, "the read is not i_char_width compatible");
1885         }
1886
1887         if( i_data == 0 )
1888             break;
1889
1890         /* Check if there is an EOL */
1891         if( s->i_char_width == 1 )
1892         {
1893             /* UTF-8: 0A <LF> */
1894             psz_eol = memchr( p_data, '\n', i_data );
1895         }
1896         else
1897         {
1898             const uint8_t *p = p_data;
1899             const uint8_t *p_last = p + i_data - s->i_char_width;
1900
1901             if( s->i_char_width == 2 )
1902             {
1903                 if( s->b_little_endian == true)
1904                 {
1905                     /* UTF-16LE: 0A 00 <LF> */
1906                     while( p <= p_last && ( p[0] != 0x0A || p[1] != 0x00 ) )
1907                         p += 2;
1908                 }
1909                 else
1910                 {
1911                     /* UTF-16BE: 00 0A <LF> */
1912                     while( p <= p_last && ( p[1] != 0x0A || p[0] != 0x00 ) )
1913                         p += 2;
1914                 }
1915             }
1916
1917             if( p > p_last )
1918             {
1919                 psz_eol = NULL;
1920             }
1921             else
1922             {
1923                 psz_eol = (char *)p + ( s->i_char_width - 1 );
1924             }
1925         }
1926
1927         if(psz_eol)
1928         {
1929             i_data = (psz_eol - (char *)p_data) + 1;
1930             p_line = realloc( p_line, i_line + i_data + s->i_char_width ); /* add \0 */
1931             if( !p_line )
1932                 goto error;
1933             i_data = stream_Read( s, &p_line[i_line], i_data );
1934             if( i_data <= 0 ) break; /* Hmmm */
1935             i_line += i_data - s->i_char_width; /* skip \n */;
1936             i_read += i_data;
1937
1938             /* We have our line */
1939             break;
1940         }
1941
1942         /* Read data (+1 for easy \0 append) */
1943         p_line = realloc( p_line, i_line + STREAM_PROBE_LINE + s->i_char_width );
1944         if( !p_line )
1945             goto error;
1946         i_data = stream_Read( s, &p_line[i_line], STREAM_PROBE_LINE );
1947         if( i_data <= 0 ) break; /* Hmmm */
1948         i_line += i_data;
1949         i_read += i_data;
1950     }
1951
1952     if( i_read > 0 )
1953     {
1954         int j;
1955         for( j = 0; j < s->i_char_width; j++ )
1956         {
1957             p_line[i_line + j] = '\0';
1958         }
1959         i_line += s->i_char_width; /* the added \0 */
1960         if( s->i_char_width > 1 )
1961         {
1962             size_t i_in = 0, i_out = 0;
1963             const char * p_in = NULL;
1964             char * p_out = NULL;
1965             char * psz_new_line = NULL;
1966
1967             /* iconv */
1968             psz_new_line = malloc( i_line );
1969             if( psz_new_line == NULL )
1970                 goto error;
1971             i_in = i_out = (size_t)i_line;
1972             p_in = p_line;
1973             p_out = psz_new_line;
1974
1975             if( vlc_iconv( s->conv, &p_in, &i_in, &p_out, &i_out ) == (size_t)-1 )
1976             {
1977                 msg_Err( s, "iconv failed" );
1978                 msg_Dbg( s, "original: %d, in %d, out %d", i_line, (int)i_in, (int)i_out );
1979             }
1980             free( p_line );
1981             p_line = psz_new_line;
1982             i_line = (size_t)i_line - i_out; /* does not include \0 */
1983         }
1984
1985         /* Remove trailing LF/CR */
1986         while( i_line >= 2 && ( p_line[i_line-2] == '\r' ||
1987             p_line[i_line-2] == '\n') ) i_line--;
1988
1989         /* Make sure the \0 is there */
1990         p_line[i_line-1] = '\0';
1991
1992         return p_line;
1993     }
1994
1995 error:
1996
1997     /* We failed to read any data, probably EOF */
1998     free( p_line );
1999     if( s->conv != (vlc_iconv_t)(-1) ) vlc_iconv_close( s->conv );
2000     return NULL;
2001 }
2002
2003 /****************************************************************************
2004  * Access reading/seeking wrappers to handle concatenated streams.
2005  ****************************************************************************/
2006 static int AReadStream( stream_t *s, void *p_read, unsigned int i_read )
2007 {
2008     stream_sys_t *p_sys = s->p_sys;
2009     access_t *p_access = p_sys->p_access;
2010     input_thread_t *p_input = NULL;
2011     int i_read_orig = i_read;
2012     int i_total = 0;
2013
2014     if( s->p_parent && s->p_parent->p_parent &&
2015         s->p_parent->p_parent->i_object_type == VLC_OBJECT_INPUT )
2016         p_input = (input_thread_t *)s->p_parent->p_parent;
2017
2018     if( !p_sys->i_list )
2019     {
2020         i_read = p_access->pf_read( p_access, p_read, i_read );
2021         if( p_access->b_die )
2022             vlc_object_kill( s );
2023         if( p_input )
2024         {
2025             vlc_mutex_lock( &p_input->p->counters.counters_lock );
2026             stats_UpdateInteger( s, p_input->p->counters.p_read_bytes, i_read,
2027                              &i_total );
2028             stats_UpdateFloat( s, p_input->p->counters.p_input_bitrate,
2029                            (float)i_total, NULL );
2030             stats_UpdateInteger( s, p_input->p->counters.p_read_packets, 1, NULL );
2031             vlc_mutex_unlock( &p_input->p->counters.counters_lock );
2032         }
2033         return i_read;
2034     }
2035
2036     i_read = p_sys->p_list_access->pf_read( p_sys->p_list_access, p_read,
2037                                             i_read );
2038     if( p_access->b_die )
2039         vlc_object_kill( s );
2040
2041     /* If we reached an EOF then switch to the next stream in the list */
2042     if( i_read == 0 && p_sys->i_list_index + 1 < p_sys->i_list )
2043     {
2044         char *psz_name = p_sys->list[++p_sys->i_list_index]->psz_path;
2045         access_t *p_list_access;
2046
2047         msg_Dbg( s, "opening input `%s'", psz_name );
2048
2049         p_list_access = access_New( s, p_access->psz_access, "", psz_name );
2050
2051         if( !p_list_access ) return 0;
2052
2053         if( p_sys->p_list_access != p_access )
2054             access_Delete( p_sys->p_list_access );
2055
2056         p_sys->p_list_access = p_list_access;
2057
2058         /* We have to read some data */
2059         return AReadStream( s, p_read, i_read_orig );
2060     }
2061
2062     /* Update read bytes in input */
2063     if( p_input )
2064     {
2065         vlc_mutex_lock( &p_input->p->counters.counters_lock );
2066         stats_UpdateInteger( s, p_input->p->counters.p_read_bytes, i_read, &i_total );
2067         stats_UpdateFloat( s, p_input->p->counters.p_input_bitrate,
2068                        (float)i_total, NULL );
2069         stats_UpdateInteger( s, p_input->p->counters.p_read_packets, 1, NULL );
2070         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
2071     }
2072     return i_read;
2073 }
2074
2075 static block_t *AReadBlock( stream_t *s, bool *pb_eof )
2076 {
2077     stream_sys_t *p_sys = s->p_sys;
2078     access_t *p_access = p_sys->p_access;
2079     input_thread_t *p_input = NULL;
2080     block_t *p_block;
2081     bool b_eof;
2082     int i_total = 0;
2083
2084     if( s->p_parent && s->p_parent->p_parent &&
2085         s->p_parent->p_parent->i_object_type == VLC_OBJECT_INPUT )
2086         p_input = (input_thread_t *)s->p_parent->p_parent;
2087
2088     if( !p_sys->i_list )
2089     {
2090         p_block = p_access->pf_block( p_access );
2091         if( p_access->b_die )
2092             vlc_object_kill( s );
2093         if( pb_eof ) *pb_eof = p_access->info.b_eof;
2094         if( p_input && p_block && libvlc_stats (p_access) )
2095         {
2096             vlc_mutex_lock( &p_input->p->counters.counters_lock );
2097             stats_UpdateInteger( s, p_input->p->counters.p_read_bytes,
2098                                  p_block->i_buffer, &i_total );
2099             stats_UpdateFloat( s, p_input->p->counters.p_input_bitrate,
2100                               (float)i_total, NULL );
2101             stats_UpdateInteger( s, p_input->p->counters.p_read_packets, 1, NULL );
2102             vlc_mutex_unlock( &p_input->p->counters.counters_lock );
2103         }
2104         return p_block;
2105     }
2106
2107     p_block = p_sys->p_list_access->pf_block( p_access );
2108     if( p_access->b_die )
2109         vlc_object_kill( s );
2110     b_eof = p_sys->p_list_access->info.b_eof;
2111     if( pb_eof ) *pb_eof = b_eof;
2112
2113     /* If we reached an EOF then switch to the next stream in the list */
2114     if( !p_block && b_eof && p_sys->i_list_index + 1 < p_sys->i_list )
2115     {
2116         char *psz_name = p_sys->list[++p_sys->i_list_index]->psz_path;
2117         access_t *p_list_access;
2118
2119         msg_Dbg( s, "opening input `%s'", psz_name );
2120
2121         p_list_access = access_New( s, p_access->psz_access, "", psz_name );
2122
2123         if( !p_list_access ) return 0;
2124
2125         if( p_sys->p_list_access != p_access )
2126             access_Delete( p_sys->p_list_access );
2127
2128         p_sys->p_list_access = p_list_access;
2129
2130         /* We have to read some data */
2131         return AReadBlock( s, pb_eof );
2132     }
2133     if( p_block )
2134     {
2135         if( p_input )
2136         {
2137             vlc_mutex_lock( &p_input->p->counters.counters_lock );
2138             stats_UpdateInteger( s, p_input->p->counters.p_read_bytes,
2139                                  p_block->i_buffer, &i_total );
2140             stats_UpdateFloat( s, p_input->p->counters.p_input_bitrate,
2141                               (float)i_total, NULL );
2142             stats_UpdateInteger( s, p_input->p->counters.p_read_packets,
2143                                  1 , NULL);
2144             vlc_mutex_unlock( &p_input->p->counters.counters_lock );
2145         }
2146     }
2147     return p_block;
2148 }
2149
2150 static int ASeek( stream_t *s, int64_t i_pos )
2151 {
2152     stream_sys_t *p_sys = s->p_sys;
2153     access_t *p_access = p_sys->p_access;
2154
2155     /* Check which stream we need to access */
2156     if( p_sys->i_list )
2157     {
2158         int i;
2159         char *psz_name;
2160         int64_t i_size = 0;
2161         access_t *p_list_access = 0;
2162
2163         for( i = 0; i < p_sys->i_list - 1; i++ )
2164         {
2165             if( i_pos < p_sys->list[i]->i_size + i_size ) break;
2166             i_size += p_sys->list[i]->i_size;
2167         }
2168         psz_name = p_sys->list[i]->psz_path;
2169
2170         if( i != p_sys->i_list_index )
2171             msg_Dbg( s, "opening input `%s'", psz_name );
2172
2173         if( i != p_sys->i_list_index && i != 0 )
2174         {
2175             p_list_access =
2176                 access_New( s, p_access->psz_access, "", psz_name );
2177         }
2178         else if( i != p_sys->i_list_index )
2179         {
2180             p_list_access = p_access;
2181         }
2182
2183         if( p_list_access )
2184         {
2185             if( p_sys->p_list_access != p_access )
2186                 access_Delete( p_sys->p_list_access );
2187
2188             p_sys->p_list_access = p_list_access;
2189         }
2190
2191         p_sys->i_list_index = i;
2192         return p_sys->p_list_access->pf_seek( p_sys->p_list_access,
2193                                               i_pos - i_size );
2194     }
2195
2196     return p_access->pf_seek( p_access, i_pos );
2197 }
2198
2199
2200 /**
2201  * Try to read "i_read" bytes into a buffer pointed by "p_read".  If
2202  * "p_read" is NULL then data are skipped instead of read.  The return
2203  * value is the real numbers of bytes read/skip. If this value is less
2204  * than i_read that means that it's the end of the stream.
2205  */
2206 int stream_Read( stream_t *s, void *p_read, int i_read )
2207 {
2208     return s->pf_read( s, p_read, i_read );
2209 }
2210
2211 /**
2212  * Store in pp_peek a pointer to the next "i_peek" bytes in the stream
2213  * \return The real numbers of valid bytes, if it's less
2214  * or equal to 0, *pp_peek is invalid.
2215  * \note pp_peek is a pointer to internal buffer and it will be invalid as
2216  * soons as other stream_* functions are called.
2217  * \note Due to input limitation, it could be less than i_peek without meaning
2218  * the end of the stream (but only when you have i_peek >=
2219  * p_input->i_bufsize)
2220  */
2221 int stream_Peek( stream_t *s, const uint8_t **pp_peek, int i_peek )
2222 {
2223     return s->pf_peek( s, pp_peek, i_peek );
2224 }
2225
2226 /**
2227  * Use to control the "stream_t *". Look at #stream_query_e for
2228  * possible "i_query" value and format arguments.  Return VLC_SUCCESS
2229  * if ... succeed ;) and VLC_EGENERIC if failed or unimplemented
2230  */
2231 int stream_vaControl( stream_t *s, int i_query, va_list args )
2232 {
2233     return s->pf_control( s, i_query, args );
2234 }
2235
2236 /**
2237  * Destroy a stream
2238  */
2239 void stream_Delete( stream_t *s )
2240 {
2241     s->pf_destroy( s );
2242 }
2243
2244 int stream_Control( stream_t *s, int i_query, ... )
2245 {
2246     va_list args;
2247     int     i_result;
2248
2249     if( s == NULL )
2250         return VLC_EGENERIC;
2251
2252     va_start( args, i_query );
2253     i_result = s->pf_control( s, i_query, args );
2254     va_end( args );
2255     return i_result;
2256 }
2257
2258 /**
2259  * Read "i_size" bytes and store them in a block_t.
2260  * It always read i_size bytes unless you are at the end of the stream
2261  * where it return what is available.
2262  */
2263 block_t *stream_Block( stream_t *s, int i_size )
2264 {
2265     if( i_size <= 0 ) return NULL;
2266
2267     /* emulate block read */
2268     block_t *p_bk = block_New( s, i_size );
2269     if( p_bk )
2270     {
2271         int i_read = stream_Read( s, p_bk->p_buffer, i_size );
2272         if( i_read > 0 )
2273         {
2274             p_bk->i_buffer = i_read;
2275             return p_bk;
2276         }
2277         block_Release( p_bk );
2278     }
2279     return NULL;
2280 }