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