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