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