]> git.sesse.net Git - vlc/blob - src/input/stream.c
*experimental* input pre-parsing support.
[vlc] / src / input / stream.c
1 /*****************************************************************************
2  * stream.c
3  *****************************************************************************
4  * Copyright (C) 1999-2004 VideoLAN
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., 59 Temple Place - Suite 330, Boston, MA  02111, 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 /* 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 track we have, currently only used for stream mode */
45 #define STREAM_CACHE_TRACK 3
46 /* Max size of our cache 4Mo per track */
47 #define STREAM_CACHE_SIZE  (4*STREAM_CACHE_TRACK*1024*1024)
48   /* How many data we try to prebuffer */
49 #define STREAM_CACHE_PREBUFFER_SIZE (32767)
50 /* Maximum time we take to pre-buffer */
51 #define STREAM_CACHE_PREBUFFER_LENGTH (100*1000)
52
53
54 /* Method1: Simple, for pf_block.
55  *  We get blocks and put them in the linked list.
56  *  We release blocks once the total size is bigger than CACHE_BLOCK_SIZE
57  */
58 #define STREAM_DATA_WAIT 40000       /* Time between before a pf_block retry */
59
60 /* Method2: A bit more complex, for pf_read
61  *  - We use ring buffers, only one if unseekable, all if seekable
62  *  - Upon seek date current ring, then search if one ring match the pos,
63  *      yes: switch to it, seek the access to match the end of the ring
64  *      no: search the ring with i_end the closer to i_pos,
65  *          if close enough, read data and use this ring
66  *          else use the oldest ring, seek and use it.
67  *
68  *  TODO: - with access non seekable: use all space available for only one ring, but
69  *          we have to support seekable/non-seekable switch on the fly.
70  *        - compute a good value for i_read_size
71  *        - ?
72  */
73 #define STREAM_READ_ATONCE 32767
74 #define STREAM_CACHE_TRACK_SIZE (STREAM_CACHE_SIZE/STREAM_CACHE_TRACK)
75
76 typedef struct
77 {
78     int64_t i_date;
79
80     int64_t i_start;
81     int64_t i_end;
82
83     uint8_t *p_buffer;
84 } stream_track_t;
85
86 struct stream_sys_t
87 {
88     access_t    *p_access;
89
90     vlc_bool_t  b_block;    /* Block method (1) or stream */
91
92     int64_t     i_pos;      /* Current reading offset */
93
94     /* Method 1: pf_block */
95     struct
96     {
97         int64_t i_start;        /* Offset of block for p_first */
98         int     i_offset;       /* Offset for data in p_current */
99         block_t *p_current;     /* Current block */
100
101         int     i_size;         /* Total amount of data in the list */
102         block_t *p_first;
103         block_t **pp_last;
104     } block;
105
106     /* Method 2: for pf_read */
107     struct
108     {
109         int i_offset;   /* Buffer offset in the current track */
110         int i_tk;       /* Current track */
111         stream_track_t tk[STREAM_CACHE_TRACK];
112
113         /* Global buffer */
114         uint8_t *p_buffer;
115
116         /* */
117         int i_used; /* Used since last read */
118         int i_read_size;
119     } stream;
120
121     /* Peek temporary buffer */
122     int     i_peek;
123     uint8_t *p_peek;
124
125     /* Stat for both method */
126     struct
127     {
128         vlc_bool_t b_fastseek;  /* From access */
129
130         /* Stat about reading data */
131         int64_t i_read_count;
132         int64_t i_bytes;
133         int64_t i_read_time;
134
135         /* Stat about seek */
136         int     i_seek_count;
137         int64_t i_seek_time;
138     } stat;
139
140     /* Preparse mode ? */
141     vlc_bool_t b_quick;
142 };
143
144 /* Method 1: */
145 static int  AStreamReadBlock( stream_t *, void *p_read, int i_read );
146 static int  AStreamPeekBlock( stream_t *, uint8_t **p_peek, int i_read );
147 static int  AStreamSeekBlock( stream_t *s, int64_t i_pos );
148 static void AStreamPrebufferBlock( stream_t * );
149
150 /* Method 2 */
151 static int  AStreamReadStream( stream_t *, void *p_read, int i_read );
152 static int  AStreamPeekStream( stream_t *, uint8_t **pp_peek, int i_read );
153 static int  AStreamSeekStream( stream_t *s, int64_t i_pos );
154 static void AStreamPrebufferStream( stream_t * );
155
156 /* Common */
157 static int AStreamControl( stream_t *, int i_query, va_list );
158
159
160 /****************************************************************************
161  * stream_AccessNew: create a stream from a access
162  ****************************************************************************/
163 stream_t *stream_AccessNew( access_t *p_access, vlc_bool_t b_quick )
164 {
165     stream_t *s = vlc_object_create( p_access, VLC_OBJECT_STREAM );
166     stream_sys_t *p_sys;
167
168     if( !s )
169         return NULL;
170
171     /* Attach it now, needed for b_die */
172     vlc_object_attach( s, p_access );
173
174     s->pf_block  = NULL;
175     s->pf_read   = NULL;    /* Set up later */
176     s->pf_peek   = NULL;
177     s->pf_control= AStreamControl;
178
179     s->p_sys = p_sys = malloc( sizeof( stream_sys_t ) );
180
181     /* Common field */
182     p_sys->p_access = p_access;
183     p_sys->b_block = p_access->pf_block ? VLC_TRUE : VLC_FALSE;
184     p_sys->i_pos = p_access->info.i_pos;
185
186     /* Stats */
187     access2_Control( p_access, ACCESS_CAN_FASTSEEK, &p_sys->stat.b_fastseek );
188     p_sys->stat.i_bytes = 0;
189     p_sys->stat.i_read_time = 0;
190     p_sys->stat.i_read_count = 0;
191     p_sys->stat.i_seek_count = 0;
192     p_sys->stat.i_seek_time = 0;
193
194     p_sys->b_quick = b_quick;
195
196     /* Peek */
197     p_sys->i_peek = 0;
198     p_sys->p_peek = NULL;
199
200     if( p_sys->b_block )
201     {
202         s->pf_read = AStreamReadBlock;
203         s->pf_peek = AStreamPeekBlock;
204
205         /* Init all fields of p_sys->block */
206         p_sys->block.i_start = p_sys->i_pos;
207         p_sys->block.i_offset = 0;
208         p_sys->block.p_current = NULL;
209         p_sys->block.i_size = 0;
210         p_sys->block.p_first = NULL;
211         p_sys->block.pp_last = &p_sys->block.p_first;
212
213         /* Do the prebuffering */
214         AStreamPrebufferBlock( s );
215
216         if( p_sys->block.i_size <= 0 )
217         {
218             msg_Err( s, "cannot pre fill buffer" );
219             goto error;
220         }
221     }
222     else
223     {
224         int i;
225
226         s->pf_read = AStreamReadStream;
227         s->pf_peek = AStreamPeekStream;
228
229         /* Allocate/Setup our tracks */
230         p_sys->stream.i_offset = 0;
231         p_sys->stream.i_tk     = 0;
232         p_sys->stream.p_buffer = malloc( STREAM_CACHE_SIZE );
233         p_sys->stream.i_used   = 0;
234         access2_Control( p_access, ACCESS_GET_MTU,
235                          &p_sys->stream.i_read_size );
236         if( p_sys->stream.i_read_size <= 0 )
237             p_sys->stream.i_read_size = STREAM_READ_ATONCE;
238         else if( p_sys->stream.i_read_size <= 256 )
239             p_sys->stream.i_read_size = 256;
240
241         for( i = 0; i < STREAM_CACHE_TRACK; i++ )
242         {
243             p_sys->stream.tk[i].i_date  = 0;
244             p_sys->stream.tk[i].i_start = p_sys->i_pos;
245             p_sys->stream.tk[i].i_end   = p_sys->i_pos;
246             p_sys->stream.tk[i].p_buffer=
247                 &p_sys->stream.p_buffer[i * STREAM_CACHE_TRACK_SIZE];
248         }
249
250         /* Do the prebuffering */
251         AStreamPrebufferStream( s );
252
253         if( p_sys->stream.tk[p_sys->stream.i_tk].i_end <= 0 )
254         {
255             msg_Err( s, "cannot pre fill buffer" );
256             goto error;
257         }
258     }
259
260     return s;
261
262 error:
263     if( p_sys->b_block )
264     {
265         /* Nothing yet */
266     }
267     else
268     {
269         free( p_sys->stream.p_buffer );
270     }
271     free( s->p_sys );
272     vlc_object_detach( s );
273     vlc_object_destroy( s );
274     return NULL;
275 }
276
277 /****************************************************************************
278  * stream_AccessDelete:
279  ****************************************************************************/
280 void stream_AccessDelete( stream_t *s )
281 {
282     stream_sys_t *p_sys = s->p_sys;
283
284     vlc_object_detach( s );
285
286     if( p_sys->b_block )
287     {
288         block_ChainRelease( p_sys->block.p_first );
289     }
290     else
291     {
292         free( p_sys->stream.p_buffer );
293     }
294
295     if( p_sys->p_peek )
296         free( p_sys->p_peek );
297
298     free( s->p_sys );
299     vlc_object_destroy( s );
300 }
301
302 /****************************************************************************
303  * stream_AccessReset:
304  ****************************************************************************/
305 void stream_AccessReset( stream_t *s )
306 {
307     stream_sys_t *p_sys = s->p_sys;
308
309     p_sys->i_pos = p_sys->p_access->info.i_pos;
310
311     if( p_sys->b_block )
312     {
313         block_ChainRelease( p_sys->block.p_first );
314
315         /* Init all fields of p_sys->block */
316         p_sys->block.i_start = p_sys->i_pos;
317         p_sys->block.i_offset = 0;
318         p_sys->block.p_current = NULL;
319         p_sys->block.i_size = 0;
320         p_sys->block.p_first = NULL;
321         p_sys->block.pp_last = &p_sys->block.p_first;
322
323         /* Do the prebuffering */
324         AStreamPrebufferBlock( s );
325     }
326     else
327     {
328         int i;
329
330         /* Setup our tracks */
331         p_sys->stream.i_offset = 0;
332         p_sys->stream.i_tk     = 0;
333         p_sys->stream.i_used   = 0;
334
335         for( i = 0; i < STREAM_CACHE_TRACK; i++ )
336         {
337             p_sys->stream.tk[i].i_date  = 0;
338             p_sys->stream.tk[i].i_start = p_sys->i_pos;
339             p_sys->stream.tk[i].i_end   = p_sys->i_pos;
340         }
341
342         /* Do the prebuffering */
343         AStreamPrebufferStream( s );
344     }
345 }
346
347 /****************************************************************************
348  * stream_AccessUpdate:
349  ****************************************************************************/
350 void stream_AccessUpdate( stream_t *s )
351 {
352     stream_sys_t *p_sys = s->p_sys;
353     p_sys->i_pos = p_sys->p_access->info.i_pos;
354 }
355
356 /****************************************************************************
357  * AStreamControl:
358  ****************************************************************************/
359 static int AStreamControl( stream_t *s, int i_query, va_list args )
360 {
361     stream_sys_t *p_sys = s->p_sys;
362     access_t     *p_access = p_sys->p_access;
363
364     vlc_bool_t *p_bool;
365     int64_t    *pi_64, i_64;
366     int        i_int;
367
368     switch( i_query )
369     {
370         case STREAM_GET_SIZE:
371             pi_64 = (int64_t*)va_arg( args, int64_t * );
372             *pi_64 = p_access->info.i_size;
373             break;
374
375         case STREAM_CAN_SEEK:
376             p_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
377             access2_Control( p_access, ACCESS_CAN_SEEK, p_bool );
378             break;
379
380         case STREAM_CAN_FASTSEEK:
381             p_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
382             access2_Control( p_access, ACCESS_CAN_FASTSEEK, p_bool );
383             break;
384
385         case STREAM_GET_POSITION:
386             pi_64 = (int64_t*)va_arg( args, int64_t * );
387             *pi_64 = p_sys->i_pos;
388             break;
389
390         case STREAM_SET_POSITION:
391             i_64 = (int64_t)va_arg( args, int64_t );
392             if( p_sys->b_block )
393                 return AStreamSeekBlock( s, i_64 );
394             else
395                 return AStreamSeekStream( s, i_64 );
396
397         case STREAM_GET_MTU:
398             return VLC_EGENERIC;
399
400         case STREAM_CONTROL_ACCESS:
401             i_int = (int) va_arg( args, int );
402             if( i_int != ACCESS_SET_PRIVATE_ID_STATE
403                  && i_int != ACCESS_SET_PRIVATE_ID_CA )
404             {
405                 msg_Err( s, "Hey, what are you thinking ?"
406                             "DON'T USE STREAM_CONTROL_ACCESS !!!" );
407                 return VLC_EGENERIC;
408             }
409             return access2_vaControl( p_access, i_int, args );
410
411         default:
412             msg_Err( s, "invalid stream_vaControl query=0x%x", i_query );
413             return VLC_EGENERIC;
414     }
415     return VLC_SUCCESS;
416 }
417
418
419
420 /****************************************************************************
421  * Method 1:
422  ****************************************************************************/
423 static void AStreamPrebufferBlock( stream_t *s )
424 {
425     stream_sys_t *p_sys = s->p_sys;
426     access_t     *p_access = p_sys->p_access;
427
428     int64_t i_first = 0;
429     int64_t i_start;
430
431     msg_Dbg( s, "pre buffering" );
432     i_start = mdate();
433     for( ;; )
434     {
435         int64_t i_date = mdate();
436         block_t *b;
437
438         if( s->b_die || p_sys->block.i_size > STREAM_CACHE_PREBUFFER_SIZE ||
439             ( i_first > 0 && i_first + STREAM_CACHE_PREBUFFER_LENGTH < i_date ) )
440         {
441             int64_t i_byterate;
442
443             /* Update stat */
444             p_sys->stat.i_bytes = p_sys->block.i_size;
445             p_sys->stat.i_read_time = i_date - i_start;
446             i_byterate = ( I64C(1000000) * p_sys->stat.i_bytes ) /
447                          (p_sys->stat.i_read_time + 1);
448
449             msg_Dbg( s, "prebuffering done "I64Fd" bytes in "I64Fd"s - "
450                      I64Fd" kbytes/s",
451                      p_sys->stat.i_bytes,
452                      p_sys->stat.i_read_time / I64C(1000000),
453                      i_byterate / 1024 );
454             break;
455         }
456
457         /* Fetch a block */
458         if( ( b = p_access->pf_block( p_access ) ) == NULL )
459         {
460             if( p_access->info.b_eof )
461                 break;
462
463             msleep( STREAM_DATA_WAIT );
464             continue;
465         }
466
467         if( i_first == 0 )
468         {
469             i_first = mdate();
470             msg_Dbg( s, "received first data for our buffer");
471         }
472
473         /* Append the block */
474         p_sys->block.i_size += b->i_buffer;
475         *p_sys->block.pp_last = b;
476         p_sys->block.pp_last = &b->p_next;
477
478         p_sys->stat.i_read_count++;
479     }
480
481     p_sys->block.p_current = p_sys->block.p_first;
482 }
483
484 static int AStreamRefillBlock( stream_t *s );
485
486 static int AStreamReadBlock( stream_t *s, void *p_read, int i_read )
487 {
488     stream_sys_t *p_sys = s->p_sys;
489
490     uint8_t *p_data= (uint8_t*)p_read;
491     int     i_data = 0;
492
493     /* It means EOF */
494     if( p_sys->block.p_current == NULL )
495         return 0;
496
497     if( p_read == NULL )
498     {
499         /* seek within this stream if possible, else use plain old read and discard */
500         stream_sys_t *p_sys = s->p_sys;
501         access_t     *p_access = p_sys->p_access;
502         vlc_bool_t   b_aseek;
503         access2_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
504         if( b_aseek )
505             return AStreamSeekBlock( s, p_sys->i_pos + i_read ) ? 0 : i_read;
506     }
507
508     while( i_data < i_read )
509     {
510         int i_current =
511             p_sys->block.p_current->i_buffer - p_sys->block.i_offset;
512         int i_copy = __MIN( i_current, i_read - i_data);
513
514         /* Copy data */
515         if( p_data )
516         {
517             memcpy( p_data,
518                     &p_sys->block.p_current->p_buffer[p_sys->block.i_offset],
519                     i_copy );
520             p_data += i_copy;
521         }
522         i_data += i_copy;
523
524         p_sys->block.i_offset += i_copy;
525         if( p_sys->block.i_offset >= p_sys->block.p_current->i_buffer )
526         {
527             /* Current block is now empty, switch to next */
528             if( p_sys->block.p_current )
529             {
530                 p_sys->block.i_offset = 0;
531                 p_sys->block.p_current = p_sys->block.p_current->p_next;
532             }
533             /*Get a new block */
534             if( AStreamRefillBlock( s ) )
535             {
536                 break;
537             }
538         }
539     }
540
541     p_sys->i_pos += i_data;
542     return i_data;
543 }
544
545 static int AStreamPeekBlock( stream_t *s, uint8_t **pp_peek, int i_read )
546 {
547     stream_sys_t *p_sys = s->p_sys;
548     uint8_t *p_data;
549     int      i_data = 0;
550     block_t *b;
551     int      i_offset;
552
553     if( p_sys->block.p_current == NULL ) return 0; /* EOF */
554
555     /* We can directly give a pointer over our buffer */
556     if( i_read <= p_sys->block.p_current->i_buffer - p_sys->block.i_offset )
557     {
558         *pp_peek = &p_sys->block.p_current->p_buffer[p_sys->block.i_offset];
559         return i_read;
560     }
561
562     /* We need to create a local copy */
563     if( p_sys->i_peek < i_read )
564     {
565         if( p_sys->p_peek )
566             free( p_sys->p_peek );
567         p_sys->i_peek = i_read;
568         p_sys->p_peek = malloc( p_sys->i_peek );
569     }
570
571     /* Fill enough data */
572     while( p_sys->block.i_size - (p_sys->i_pos - p_sys->block.i_start)
573            < i_read )
574     {
575         block_t **pp_last = p_sys->block.pp_last;
576
577         if( AStreamRefillBlock( s ) )
578             break;
579
580         /* Our buffer are probably filled enough, don't try anymore */
581         if( pp_last == p_sys->block.pp_last )
582             break;
583     }
584
585     /* Copy what we have */
586     b = p_sys->block.p_current;
587     i_offset = p_sys->block.i_offset;
588     p_data = p_sys->p_peek;
589
590     while( b && i_data < i_read )
591     {
592         int i_current = b->i_buffer - i_offset;
593         int i_copy = __MIN( i_current, i_read - i_data );
594
595         memcpy( p_data, &b->p_buffer[i_offset], i_copy );
596         i_data += i_copy;
597         p_data += i_copy;
598         i_offset += i_copy;
599
600         if( i_offset >= b->i_buffer )
601         {
602             i_offset = 0;
603             b = b->p_next;
604         }
605     }
606
607     *pp_peek = p_sys->p_peek;
608     return i_data;
609 }
610
611 static int AStreamSeekBlock( stream_t *s, int64_t i_pos )
612 {
613     stream_sys_t *p_sys = s->p_sys;
614     access_t   *p_access = p_sys->p_access;
615     int64_t    i_offset = i_pos - p_sys->block.i_start;
616     vlc_bool_t b_seek;
617
618     /* We already have thoses data, just update p_current/i_offset */
619     if( i_offset >= 0 && i_offset < p_sys->block.i_size )
620     {
621         block_t *b = p_sys->block.p_first;
622         int i_current = 0;
623
624         while( i_current + b->i_buffer < i_offset )
625         {
626             i_current += b->i_buffer;
627             b = b->p_next;
628         }
629
630         p_sys->block.p_current = b;
631         p_sys->block.i_offset = i_offset - i_current;
632
633         p_sys->i_pos = i_pos;
634
635         return VLC_SUCCESS;
636     }
637
638     /* We may need to seek or to read data */
639     if( i_offset < 0 )
640     {
641         vlc_bool_t b_aseek;
642         access2_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
643
644         if( !b_aseek )
645         {
646             msg_Err( s, "backward seek impossible (access non seekable)" );
647             return VLC_EGENERIC;
648         }
649
650         b_seek = VLC_TRUE;
651     }
652     else
653     {
654         vlc_bool_t b_aseek, b_aseekfast;
655
656         access2_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
657         access2_Control( p_access, ACCESS_CAN_FASTSEEK, &b_aseekfast );
658
659         if( !b_aseek )
660         {
661             b_seek = VLC_FALSE;
662             msg_Warn( s, I64Fd" bytes need to be skipped "
663                       "(access non seekable)",
664                       i_offset - p_sys->block.i_size );
665         }
666         else
667         {
668             int64_t i_skip = i_offset - p_sys->block.i_size;
669
670             /* Avg bytes per packets */
671             int i_avg = p_sys->stat.i_bytes / p_sys->stat.i_read_count;
672             /* TODO compute a seek cost instead of fixed threshold */
673             int i_th = b_aseekfast ? 1 : 5;
674
675             if( i_skip <= i_th * i_avg &&
676                 i_skip < STREAM_CACHE_SIZE )
677                 b_seek = VLC_FALSE;
678             else
679                 b_seek = VLC_TRUE;
680
681             msg_Dbg( s, "b_seek=%d th*avg=%d skip="I64Fd,
682                      b_seek, i_th*i_avg, i_skip );
683         }
684     }
685
686     if( b_seek )
687     {
688         int64_t i_start, i_end;
689         /* Do the access seek */
690         i_start = mdate();
691         if( p_access->pf_seek( p_access, i_pos ) )
692             return VLC_EGENERIC;
693         i_end = mdate();
694
695         /* Release data */
696         block_ChainRelease( p_sys->block.p_first );
697
698         /* Reinit */
699         p_sys->block.i_start = p_sys->i_pos = i_pos;
700         p_sys->block.i_offset = 0;
701         p_sys->block.p_current = NULL;
702         p_sys->block.i_size = 0;
703         p_sys->block.p_first = NULL;
704         p_sys->block.pp_last = &p_sys->block.p_first;
705
706         /* Refill a block */
707         if( AStreamRefillBlock( s ) )
708         {
709             msg_Err( s, "cannot re fill buffer" );
710             return VLC_EGENERIC;
711         }
712         /* Update stat */
713         p_sys->stat.i_seek_time += i_end - i_start;
714         p_sys->stat.i_seek_count++;
715         return VLC_SUCCESS;
716     }
717     else
718     {
719         /* Read enought data */
720         while( p_sys->block.i_start + p_sys->block.i_size < i_pos )
721         {
722             if( AStreamRefillBlock( s ) )
723             {
724                 msg_Err( s, "can't read enough data in seek" );
725                 return VLC_EGENERIC;
726             }
727             while( p_sys->block.p_current &&
728                    p_sys->i_pos + p_sys->block.p_current->i_buffer < i_pos )
729             {
730                 p_sys->i_pos += p_sys->block.p_current->i_buffer;
731                 p_sys->block.p_current = p_sys->block.p_current->p_next;
732             }
733         }
734
735         p_sys->block.i_offset = i_pos - p_sys->i_pos;
736         p_sys->i_pos = i_pos;
737
738         /* TODO read data */
739         return VLC_SUCCESS;
740     }
741
742     return VLC_EGENERIC;
743 }
744
745 static int AStreamRefillBlock( stream_t *s )
746 {
747     stream_sys_t *p_sys = s->p_sys;
748     access_t     *p_access = p_sys->p_access;
749     int64_t      i_start, i_stop;
750     block_t      *b;
751
752     /* Release data */
753     while( p_sys->block.i_size >= STREAM_CACHE_SIZE &&
754            p_sys->block.p_first != p_sys->block.p_current )
755     {
756         block_t *b = p_sys->block.p_first;
757
758         p_sys->block.i_start += b->i_buffer;
759         p_sys->block.i_size  -= b->i_buffer;
760         p_sys->block.p_first  = b->p_next;
761
762         block_Release( b );
763     }
764     if( p_sys->block.i_size >= STREAM_CACHE_SIZE &&
765         p_sys->block.p_current == p_sys->block.p_first &&
766         p_sys->block.p_current->p_next )    /* At least 2 packets */
767     {
768         /* Enough data, don't read more */
769         return VLC_SUCCESS;
770     }
771
772     /* Now read a new block */
773     i_start = mdate();
774     for( ;; )
775     {
776         if( s->b_die )
777             return VLC_EGENERIC;
778
779
780         /* Fetch a block */
781         if( ( b = p_access->pf_block( p_access ) ) )
782             break;
783
784         if( p_access->info.b_eof )
785             return VLC_EGENERIC;
786
787         msleep( STREAM_DATA_WAIT );
788     }
789     i_stop = mdate();
790
791     /* Append the block */
792     p_sys->block.i_size += b->i_buffer;
793     *p_sys->block.pp_last = b;
794     p_sys->block.pp_last = &b->p_next;
795
796     /* Fix p_current */
797     if( p_sys->block.p_current == NULL )
798         p_sys->block.p_current = b;
799
800     /* Update stat */
801     p_sys->stat.i_bytes += b->i_buffer;
802     p_sys->stat.i_read_time += i_stop - i_start;
803     p_sys->stat.i_read_count++;
804
805     return VLC_SUCCESS;
806 }
807
808
809 /****************************************************************************
810  * Method 2:
811  ****************************************************************************/
812 static int AStreamRefillStream( stream_t *s );
813
814 static int AStreamReadStream( stream_t *s, void *p_read, int i_read )
815 {
816     stream_sys_t *p_sys = s->p_sys;
817     stream_track_t *tk = &p_sys->stream.tk[p_sys->stream.i_tk];
818
819     uint8_t *p_data = (uint8_t *)p_read;
820     int      i_data = 0;
821
822     if( tk->i_start >= tk->i_end ) return 0; /* EOF */
823
824     if( p_read == NULL )
825     {
826         /* seek within this stream if possible, else use plain old read and discard */
827         stream_sys_t *p_sys = s->p_sys;
828         access_t     *p_access = p_sys->p_access;
829         vlc_bool_t   b_aseek;
830         access2_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
831         if( b_aseek )
832             return AStreamSeekStream( s, p_sys->i_pos + i_read ) ? 0 : i_read;
833     }
834
835 #if 0
836     msg_Dbg( s, "AStreamReadStream: %d pos="I64Fd" tk=%d start="I64Fd
837              " offset=%d end="I64Fd,
838              i_read, p_sys->i_pos, p_sys->stream.i_tk,
839              tk->i_start, p_sys->stream.i_offset, tk->i_end );
840 #endif
841
842     while( i_data < i_read )
843     {
844         int i_off = (tk->i_start + p_sys->stream.i_offset) %
845                     STREAM_CACHE_TRACK_SIZE;
846         int i_current =
847             __MIN( tk->i_end - tk->i_start - p_sys->stream.i_offset,
848                    STREAM_CACHE_TRACK_SIZE - i_off );
849         int i_copy = __MIN( i_current, i_read - i_data );
850
851         if( i_copy <= 0 ) break; /* EOF */
852
853         /* Copy data */
854         /* msg_Dbg( s, "AStreamReadStream: copy %d", i_copy ); */
855         if( p_data )
856         {
857             memcpy( p_data, &tk->p_buffer[i_off], i_copy );
858             p_data += i_copy;
859         }
860         i_data += i_copy;
861         p_sys->stream.i_offset += i_copy;
862
863         /* Update pos now */
864         p_sys->i_pos += i_copy;
865
866         /* */
867         p_sys->stream.i_used += i_copy;
868         if( tk->i_start + p_sys->stream.i_offset >= tk->i_end ||
869             p_sys->stream.i_used >= p_sys->stream.i_read_size )
870         {
871             if( AStreamRefillStream( s ) )
872             {
873                 /* EOF */
874                 if( tk->i_start >= tk->i_end ) break;
875             }
876         }
877     }
878
879     return i_data;
880 }
881
882 static int AStreamPeekStream( stream_t *s, uint8_t **pp_peek, int i_read )
883 {
884     stream_sys_t *p_sys = s->p_sys;
885     stream_track_t *tk = &p_sys->stream.tk[p_sys->stream.i_tk];
886     int64_t i_off;
887
888     if( tk->i_start >= tk->i_end ) return 0; /* EOF */
889
890 #if 0
891     msg_Dbg( s, "AStreamPeekStream: %d pos="I64Fd" tk=%d "
892              "start="I64Fd" offset=%d end="I64Fd,
893              i_read, p_sys->i_pos, p_sys->stream.i_tk,
894              tk->i_start, p_sys->stream.i_offset, tk->i_end );
895 #endif
896
897     /* Avoid problem, but that should *never* happen */
898     if( i_read > STREAM_CACHE_TRACK_SIZE / 2 )
899         i_read = STREAM_CACHE_TRACK_SIZE / 2;
900
901     while( tk->i_end - tk->i_start - p_sys->stream.i_offset < i_read )
902     {
903         if( p_sys->stream.i_used <= 1 )
904         {
905             /* Be sure we will read something */
906             p_sys->stream.i_used += i_read - (tk->i_end - tk->i_start - p_sys->stream.i_offset);
907         }
908         if( AStreamRefillStream( s ) )
909             break;
910     }
911
912     if( tk->i_end - tk->i_start - p_sys->stream.i_offset < i_read )
913         i_read = tk->i_end - tk->i_start - p_sys->stream.i_offset;
914
915     /* Now, direct pointer or a copy ? */
916     i_off = (tk->i_start + p_sys->stream.i_offset) % STREAM_CACHE_TRACK_SIZE;
917     if( i_off + i_read <= STREAM_CACHE_TRACK_SIZE )
918     {
919         *pp_peek = &tk->p_buffer[i_off];
920         return i_read;
921     }
922
923     if( p_sys->i_peek < i_read )
924     {
925         if( p_sys->p_peek ) free( p_sys->p_peek );
926         p_sys->i_peek = i_read;
927         p_sys->p_peek = malloc( i_read );
928     }
929
930     memcpy( p_sys->p_peek, &tk->p_buffer[i_off],
931             STREAM_CACHE_TRACK_SIZE - i_off );
932     memcpy( &p_sys->p_peek[STREAM_CACHE_TRACK_SIZE - i_off],
933             &tk->p_buffer[0], i_read - (STREAM_CACHE_TRACK_SIZE - i_off) );
934
935     *pp_peek = p_sys->p_peek;
936     return i_read;
937 }
938
939 static int AStreamSeekStream( stream_t *s, int64_t i_pos )
940 {
941     stream_sys_t *p_sys = s->p_sys;
942     access_t     *p_access = p_sys->p_access;
943     vlc_bool_t   b_aseek;
944     vlc_bool_t   b_afastseek;
945     int i_maxth;
946     int i_new;
947     int i;
948
949 #if 0
950     msg_Dbg( s, "AStreamSeekStream: to "I64Fd" pos="I64Fd
951              "tk=%d start="I64Fd" offset=%d end="I64Fd,
952              i_pos, p_sys->i_pos, p_sys->stream.i_tk,
953              p_sys->stream.tk[p_sys->stream.i_tk].i_start,
954              p_sys->stream.i_offset,
955              p_sys->stream.tk[p_sys->stream.i_tk].i_end );
956 #endif
957
958
959     /* Seek in our current track ? */
960     if( i_pos >= p_sys->stream.tk[p_sys->stream.i_tk].i_start &&
961         i_pos < p_sys->stream.tk[p_sys->stream.i_tk].i_end )
962     {
963         //msg_Dbg( s, "AStreamSeekStream: current track" );
964         p_sys->i_pos = i_pos;
965         p_sys->stream.i_offset = i_pos - p_sys->stream.tk[p_sys->stream.i_tk].i_start;
966         return VLC_SUCCESS;
967     }
968
969     access2_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
970     if( !b_aseek )
971     {
972         /* We can't do nothing */
973         msg_Dbg( s, "AStreamSeekStream: can't seek" );
974         return VLC_EGENERIC;
975     }
976
977     /* Date the current track */
978     p_sys->stream.tk[p_sys->stream.i_tk].i_date = mdate();
979
980     /* Try to reuse already read data */
981     for( i = 0; i < STREAM_CACHE_TRACK; i++ )
982     {
983         stream_track_t *tk = &p_sys->stream.tk[i];
984
985         if( i_pos >= tk->i_start && i_pos <= tk->i_end )
986         {
987 #if 0
988             msg_Dbg( s, "AStreamSeekStream: reusing %d start="I64Fd
989                      " end="I64Fd, i, tk->i_start, tk->i_end );
990 #endif
991             /* Seek at the end of the buffer */
992             if( p_access->pf_seek( p_access, tk->i_end ) )
993                 return VLC_EGENERIC;
994
995             /* That's it */
996             p_sys->i_pos = i_pos;
997             p_sys->stream.i_tk = i;
998             p_sys->stream.i_offset = i_pos - tk->i_start;
999
1000             if( p_sys->stream.i_used < 1024 )
1001                 p_sys->stream.i_used = 1024;
1002
1003             if( AStreamRefillStream( s ) && i_pos == tk->i_end )
1004                 return VLC_EGENERIC;
1005
1006             return VLC_SUCCESS;
1007         }
1008     }
1009
1010     access2_Control( p_access, ACCESS_CAN_SEEK, &b_afastseek );
1011     /* FIXME compute seek cost (instead of static 'stupid' value) */
1012     i_maxth = __MIN( p_sys->stream.i_read_size, STREAM_READ_ATONCE / 2 );
1013     if( !b_afastseek )
1014         i_maxth *= 3;
1015
1016     /* FIXME TODO */
1017 #if 0
1018     /* Search closest segment TODO */
1019     for( i = 0; i < STREAM_CACHE_TRACK; i++ )
1020     {
1021         stream_track_t *tk = &p_sys->stream.tk[i];
1022
1023         if( i_pos + i_maxth >= tk->i_start )
1024         {
1025             msg_Dbg( s, "good segment before current pos, TODO" );
1026         }
1027         if( i_pos - i_maxth <= tk->i_end )
1028         {
1029             msg_Dbg( s, "good segment after current pos, TODO" );
1030         }
1031     }
1032 #endif
1033
1034     /* Nothing good, seek and choose oldest segment */
1035     if( p_access->pf_seek( p_access, i_pos ) )
1036         return VLC_EGENERIC;
1037     p_sys->i_pos = i_pos;
1038
1039     i_new = 0;
1040     for( i = 1; i < STREAM_CACHE_TRACK; i++ )
1041     {
1042         if( p_sys->stream.tk[i].i_date < p_sys->stream.tk[i_new].i_date )
1043             i_new = i;
1044     }
1045
1046     /* Reset the segment */
1047     p_sys->stream.i_tk     = i_new;
1048     p_sys->stream.i_offset =  0;
1049     p_sys->stream.tk[i_new].i_start = i_pos;
1050     p_sys->stream.tk[i_new].i_end   = i_pos;
1051
1052     /* Read data */
1053     if( p_sys->stream.i_used < STREAM_READ_ATONCE / 2 )
1054         p_sys->stream.i_used = STREAM_READ_ATONCE / 2;
1055
1056     if( AStreamRefillStream( s ) )
1057         return VLC_EGENERIC;
1058
1059     return VLC_SUCCESS;
1060 }
1061
1062 static int AStreamRefillStream( stream_t *s )
1063 {
1064     stream_sys_t *p_sys = s->p_sys;
1065     access_t     *p_access = p_sys->p_access;
1066     stream_track_t *tk = &p_sys->stream.tk[p_sys->stream.i_tk];
1067
1068     /* We read but won't increase i_start after initial start + offset */
1069     int i_toread =
1070         __MIN( p_sys->stream.i_used, STREAM_CACHE_TRACK_SIZE -
1071                (tk->i_end - tk->i_start - p_sys->stream.i_offset) );
1072     vlc_bool_t b_read = VLC_FALSE;
1073     int64_t i_start, i_stop;
1074
1075     if( i_toread <= 0 ) return VLC_EGENERIC; /* EOF */
1076
1077     /* msg_Dbg( s, "AStreamRefillStream: toread=%d", i_toread ); */
1078
1079     i_start = mdate();
1080     while( i_toread > 0 )
1081     {
1082         int i_off = tk->i_end % STREAM_CACHE_TRACK_SIZE;
1083         int i_read;
1084
1085         if( s->b_die )
1086             return VLC_EGENERIC;
1087
1088         i_read = __MIN( i_toread, STREAM_CACHE_TRACK_SIZE - i_off );
1089         i_read = p_access->pf_read( p_access, &tk->p_buffer[i_off], i_read );
1090
1091         /* msg_Dbg( s, "AStreamRefillStream: read=%d", i_read ); */
1092         if( i_read <  0 )
1093         {
1094             msleep( STREAM_DATA_WAIT );
1095             continue;
1096         }
1097         else if( i_read == 0 )
1098         {
1099             if( !b_read )
1100                 return VLC_EGENERIC;
1101             return VLC_SUCCESS;
1102         }
1103         b_read = VLC_TRUE;
1104
1105         /* Update end */
1106         tk->i_end += i_read;
1107
1108         /* Windows of STREAM_CACHE_TRACK_SIZE */
1109         if( tk->i_end - tk->i_start > STREAM_CACHE_TRACK_SIZE )
1110         {
1111             int i_invalid = tk->i_end - tk->i_start - STREAM_CACHE_TRACK_SIZE;
1112
1113             tk->i_start += i_invalid;
1114             p_sys->stream.i_offset -= i_invalid;
1115         }
1116
1117         i_toread -= i_read;
1118         p_sys->stream.i_used -= i_read;
1119
1120         p_sys->stat.i_bytes += i_read;
1121         p_sys->stat.i_read_count++;
1122     }
1123     i_stop = mdate();
1124
1125     p_sys->stat.i_read_time += i_stop - i_start;
1126
1127     return VLC_SUCCESS;
1128 }
1129
1130 static void AStreamPrebufferStream( stream_t *s )
1131 {
1132     stream_sys_t *p_sys = s->p_sys;
1133     access_t     *p_access = p_sys->p_access;
1134
1135     int64_t i_first = 0;
1136     int64_t i_start;
1137     int64_t i_prebuffer = p_sys->b_quick ? STREAM_CACHE_TRACK_SIZE /100 :
1138                               ((s->p_sys->p_access->info.i_title > 1 ||
1139                            s->p_sys->p_access->info.i_seekpoint > 1) ? STREAM_CACHE_PREBUFFER_SIZE : STREAM_CACHE_TRACK_SIZE / 3);
1140
1141     msg_Dbg( s, "pre buffering" );
1142     i_start = mdate();
1143     for( ;; )
1144     {
1145         stream_track_t *tk = &p_sys->stream.tk[p_sys->stream.i_tk];
1146
1147         int64_t i_date = mdate();
1148         int i_read;
1149
1150         if( s->b_die || tk->i_end >= i_prebuffer ||
1151             (i_first > 0 && i_first + STREAM_CACHE_PREBUFFER_LENGTH < i_date) )
1152         {
1153             int64_t i_byterate;
1154
1155             /* Update stat */
1156             p_sys->stat.i_bytes = tk->i_end - tk->i_start;
1157             p_sys->stat.i_read_time = i_date - i_start;
1158             i_byterate = ( I64C(1000000) * p_sys->stat.i_bytes ) /
1159                          (p_sys->stat.i_read_time+1);
1160
1161             msg_Dbg( s, "prebuffering done "I64Fd" bytes in "I64Fd"s - "
1162                      I64Fd" kbytes/s",
1163                      p_sys->stat.i_bytes,
1164                      p_sys->stat.i_read_time / I64C(1000000),
1165                      i_byterate / 1024 );
1166             break;
1167         }
1168
1169         /* */
1170         i_read = STREAM_CACHE_TRACK_SIZE - tk->i_end;
1171         i_read = __MIN( p_sys->stream.i_read_size, i_read );
1172         i_read = p_access->pf_read( p_access, &tk->p_buffer[tk->i_end],
1173                                     i_read );
1174         if( i_read <  0 )
1175         {
1176             msleep( STREAM_DATA_WAIT );
1177             continue;
1178         }
1179         else if( i_read == 0 )
1180         {
1181             /* EOF */
1182             break;
1183         }
1184
1185         if( i_first == 0 )
1186         {
1187             i_first = mdate();
1188             msg_Dbg( s, "received first data for our buffer");
1189         }
1190
1191         tk->i_end += i_read;
1192
1193         p_sys->stat.i_read_count++;
1194     }
1195 }
1196
1197
1198 /****************************************************************************
1199  * stream_ReadLine:
1200  ****************************************************************************/
1201 /**
1202  * Read from the stream untill first newline.
1203  * \param s Stream handle to read from
1204  * \return A null-terminated string. This must be freed,
1205  */
1206 #define STREAM_PROBE_LINE 2048
1207 #define STREAM_LINE_MAX (2048*100)
1208 char *stream_ReadLine( stream_t *s )
1209 {
1210     char *p_line = NULL;
1211     int i_line = 0, i_read = 0;
1212
1213     while( i_read < STREAM_LINE_MAX )
1214     {
1215         char *psz_eol;
1216         uint8_t *p_data;
1217         int i_data;
1218
1219         /* Probe new data */
1220         i_data = stream_Peek( s, &p_data, STREAM_PROBE_LINE );
1221         if( i_data <= 0 ) break; /* No more data */
1222
1223         /* Check if there is an EOL */
1224         if( ( psz_eol = memchr( p_data, '\n', i_data ) ) )
1225         {
1226             i_data = (psz_eol - (char *)p_data) + 1;
1227             p_line = realloc( p_line, i_line + i_data + 1 );
1228             i_data = stream_Read( s, &p_line[i_line], i_data );
1229             if( i_data <= 0 ) break; /* Hmmm */
1230             i_line += (i_data - 1);
1231             i_read += i_data;
1232
1233             /* We have our line */
1234             break;
1235         }
1236
1237         /* Read data (+1 for easy \0 append) */
1238         p_line = realloc( p_line, i_line + STREAM_PROBE_LINE + 1 );
1239         i_data = stream_Read( s, &p_line[i_line], STREAM_PROBE_LINE );
1240         if( i_data <= 0 ) break; /* Hmmm */
1241         i_line += i_data;
1242         i_read += i_data;
1243     }
1244
1245     /* Remove trailing LF/CR */
1246     while( i_line > 0 && ( p_line[i_line-1] == '\r' ||
1247            p_line[i_line-1] == '\n') ) i_line--;
1248
1249     if( i_read > 0 )
1250     {
1251         p_line[i_line] = '\0';
1252         return p_line;
1253     }
1254
1255     /* We failed to read any data, probably EOF */
1256     if( p_line ) free( p_line );
1257     return NULL;
1258 }