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