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