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