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