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