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