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