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