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