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