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