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