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