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