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