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