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