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