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