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