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