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