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