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