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