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