OS/2 fixes (SF#1771378: https://sourceforge.net/tracker/index.php?func=detail&aid...
[platform/upstream/flac.git] / src / libFLAC / stream_decoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * - Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
11  * - Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * - Neither the name of the Xiph.org Foundation nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #if HAVE_CONFIG_H
33 #  include <config.h>
34 #endif
35
36 #if defined _MSC_VER || defined __MINGW32__
37 #include <io.h> /* for _setmode() */
38 #include <fcntl.h> /* for _O_BINARY */
39 #endif
40 #if defined __CYGWIN__ || defined __EMX__
41 #include <io.h> /* for setmode(), O_BINARY */
42 #include <fcntl.h> /* for _O_BINARY */
43 #endif
44 #include <stdio.h>
45 #include <stdlib.h> /* for malloc() */
46 #include <string.h> /* for memset/memcpy() */
47 #include <sys/stat.h> /* for stat() */
48 #include <sys/types.h> /* for off_t */
49 #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
50 #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
51 #define fseeko fseek
52 #define ftello ftell
53 #endif
54 #endif
55 #include "FLAC/assert.h"
56 #include "protected/stream_decoder.h"
57 #include "private/bitreader.h"
58 #include "private/bitmath.h"
59 #include "private/cpu.h"
60 #include "private/crc.h"
61 #include "private/fixed.h"
62 #include "private/format.h"
63 #include "private/lpc.h"
64 #include "private/md5.h"
65 #include "private/memory.h"
66
67 #ifdef max
68 #undef max
69 #endif
70 #define max(a,b) ((a)>(b)?(a):(b))
71
72 /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
73 #ifdef _MSC_VER
74 #define FLAC__U64L(x) x
75 #else
76 #define FLAC__U64L(x) x##LLU
77 #endif
78
79
80 /* technically this should be in an "export.c" but this is convenient enough */
81 FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
82 #if FLAC__HAS_OGG
83         1
84 #else
85         0
86 #endif
87 ;
88
89
90 /***********************************************************************
91  *
92  * Private static data
93  *
94  ***********************************************************************/
95
96 static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
97
98 /***********************************************************************
99  *
100  * Private class method prototypes
101  *
102  ***********************************************************************/
103
104 static void set_defaults_(FLAC__StreamDecoder *decoder);
105 static FILE *get_binary_stdin_(void);
106 static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
107 static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
108 static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
109 static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
110 static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
111 static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
112 static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
113 static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
114 static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
115 static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
116 static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
117 static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
118 static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
119 static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
120 static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
121 static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
122 static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
123 static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
124 static FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended);
125 static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
126 static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
127 #if FLAC__HAS_OGG
128 static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
129 static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
130 #endif
131 static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
132 static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
133 static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
134 #if FLAC__HAS_OGG
135 static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
136 #endif
137 static FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
138 static FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
139 static FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
140 static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
141 static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
142
143 /***********************************************************************
144  *
145  * Private class data
146  *
147  ***********************************************************************/
148
149 typedef struct FLAC__StreamDecoderPrivate {
150 #if FLAC__HAS_OGG
151         FLAC__bool is_ogg;
152 #endif
153         FLAC__StreamDecoderReadCallback read_callback;
154         FLAC__StreamDecoderSeekCallback seek_callback;
155         FLAC__StreamDecoderTellCallback tell_callback;
156         FLAC__StreamDecoderLengthCallback length_callback;
157         FLAC__StreamDecoderEofCallback eof_callback;
158         FLAC__StreamDecoderWriteCallback write_callback;
159         FLAC__StreamDecoderMetadataCallback metadata_callback;
160         FLAC__StreamDecoderErrorCallback error_callback;
161         /* generic 32-bit datapath: */
162         void (*local_lpc_restore_signal)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
163         /* generic 64-bit datapath: */
164         void (*local_lpc_restore_signal_64bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
165         /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
166         void (*local_lpc_restore_signal_16bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
167         /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit), AND order <= 8: */
168         void (*local_lpc_restore_signal_16bit_order8)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
169         FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
170         void *client_data;
171         FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
172         FLAC__BitReader *input;
173         FLAC__int32 *output[FLAC__MAX_CHANNELS];
174         FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
175         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
176         unsigned output_capacity, output_channels;
177         FLAC__uint32 fixed_block_size, next_fixed_block_size;
178         FLAC__uint64 samples_decoded;
179         FLAC__bool has_stream_info, has_seek_table;
180         FLAC__StreamMetadata stream_info;
181         FLAC__StreamMetadata seek_table;
182         FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
183         FLAC__byte *metadata_filter_ids;
184         unsigned metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
185         FLAC__Frame frame;
186         FLAC__bool cached; /* true if there is a byte in lookahead */
187         FLAC__CPUInfo cpuinfo;
188         FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
189         FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
190         /* unaligned (original) pointers to allocated data */
191         FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
192         FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */
193         FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
194         FLAC__bool is_seeking;
195         FLAC__MD5Context md5context;
196         FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
197         /* (the rest of these are only used for seeking) */
198         FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
199         FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
200         FLAC__uint64 target_sample;
201         unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
202 #if FLAC__HAS_OGG
203         FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
204 #endif
205 } FLAC__StreamDecoderPrivate;
206
207 /***********************************************************************
208  *
209  * Public static class data
210  *
211  ***********************************************************************/
212
213 FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
214         "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
215         "FLAC__STREAM_DECODER_READ_METADATA",
216         "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
217         "FLAC__STREAM_DECODER_READ_FRAME",
218         "FLAC__STREAM_DECODER_END_OF_STREAM",
219         "FLAC__STREAM_DECODER_OGG_ERROR",
220         "FLAC__STREAM_DECODER_SEEK_ERROR",
221         "FLAC__STREAM_DECODER_ABORTED",
222         "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
223         "FLAC__STREAM_DECODER_UNINITIALIZED"
224 };
225
226 FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
227         "FLAC__STREAM_DECODER_INIT_STATUS_OK",
228         "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
229         "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
230         "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
231         "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
232         "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
233 };
234
235 FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
236         "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
237         "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
238         "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
239 };
240
241 FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
242         "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
243         "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
244         "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
245 };
246
247 FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
248         "FLAC__STREAM_DECODER_TELL_STATUS_OK",
249         "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
250         "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
251 };
252
253 FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
254         "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
255         "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
256         "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
257 };
258
259 FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
260         "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
261         "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
262 };
263
264 FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
265         "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
266         "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
267         "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
268         "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
269 };
270
271 /***********************************************************************
272  *
273  * Class constructor/destructor
274  *
275  ***********************************************************************/
276 FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
277 {
278         FLAC__StreamDecoder *decoder;
279         unsigned i;
280
281         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
282
283         decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
284         if(decoder == 0) {
285                 return 0;
286         }
287
288         decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
289         if(decoder->protected_ == 0) {
290                 free(decoder);
291                 return 0;
292         }
293
294         decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
295         if(decoder->private_ == 0) {
296                 free(decoder->protected_);
297                 free(decoder);
298                 return 0;
299         }
300
301         decoder->private_->input = FLAC__bitreader_new();
302         if(decoder->private_->input == 0) {
303                 free(decoder->private_);
304                 free(decoder->protected_);
305                 free(decoder);
306                 return 0;
307         }
308
309         decoder->private_->metadata_filter_ids_capacity = 16;
310         if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
311                 FLAC__bitreader_delete(decoder->private_->input);
312                 free(decoder->private_);
313                 free(decoder->protected_);
314                 free(decoder);
315                 return 0;
316         }
317
318         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
319                 decoder->private_->output[i] = 0;
320                 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
321         }
322
323         decoder->private_->output_capacity = 0;
324         decoder->private_->output_channels = 0;
325         decoder->private_->has_seek_table = false;
326
327         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
328                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
329
330         decoder->private_->file = 0;
331
332         set_defaults_(decoder);
333
334         decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
335
336         return decoder;
337 }
338
339 FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
340 {
341         unsigned i;
342
343         FLAC__ASSERT(0 != decoder);
344         FLAC__ASSERT(0 != decoder->protected_);
345         FLAC__ASSERT(0 != decoder->private_);
346         FLAC__ASSERT(0 != decoder->private_->input);
347
348         (void)FLAC__stream_decoder_finish(decoder);
349
350         if(0 != decoder->private_->metadata_filter_ids)
351                 free(decoder->private_->metadata_filter_ids);
352
353         FLAC__bitreader_delete(decoder->private_->input);
354
355         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
356                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
357
358         free(decoder->private_);
359         free(decoder->protected_);
360         free(decoder);
361 }
362
363 /***********************************************************************
364  *
365  * Public class methods
366  *
367  ***********************************************************************/
368
369 static FLAC__StreamDecoderInitStatus init_stream_internal_(
370         FLAC__StreamDecoder *decoder,
371         FLAC__StreamDecoderReadCallback read_callback,
372         FLAC__StreamDecoderSeekCallback seek_callback,
373         FLAC__StreamDecoderTellCallback tell_callback,
374         FLAC__StreamDecoderLengthCallback length_callback,
375         FLAC__StreamDecoderEofCallback eof_callback,
376         FLAC__StreamDecoderWriteCallback write_callback,
377         FLAC__StreamDecoderMetadataCallback metadata_callback,
378         FLAC__StreamDecoderErrorCallback error_callback,
379         void *client_data,
380         FLAC__bool is_ogg
381 )
382 {
383         FLAC__ASSERT(0 != decoder);
384
385         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
386                 return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
387
388 #if !FLAC__HAS_OGG
389         if(is_ogg)
390                 return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
391 #endif
392
393         if(
394                 0 == read_callback ||
395                 0 == write_callback ||
396                 0 == error_callback ||
397                 (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
398         )
399                 return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
400
401 #if FLAC__HAS_OGG
402         decoder->private_->is_ogg = is_ogg;
403         if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
404                 return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
405 #endif
406
407         /*
408          * get the CPU info and set the function pointers
409          */
410         FLAC__cpu_info(&decoder->private_->cpuinfo);
411         /* first default to the non-asm routines */
412         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
413         decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
414         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
415         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
416         decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
417         /* now override with asm where appropriate */
418 #ifndef FLAC__NO_ASM
419         if(decoder->private_->cpuinfo.use_asm) {
420 #ifdef FLAC__CPU_IA32
421                 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
422 #ifdef FLAC__HAS_NASM
423 #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
424                 if(decoder->private_->cpuinfo.data.ia32.bswap)
425                         decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
426 #endif
427                 if(decoder->private_->cpuinfo.data.ia32.mmx) {
428                         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
429                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
430                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
431                 }
432                 else {
433                         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
434                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
435                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
436                 }
437 #endif
438 #elif defined FLAC__CPU_PPC
439                 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
440                 if(decoder->private_->cpuinfo.data.ppc.altivec) {
441                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
442                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
443                 }
444 #endif
445         }
446 #endif
447
448         /* from here on, errors are fatal */
449
450         if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
451                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
452                 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
453         }
454
455         decoder->private_->read_callback = read_callback;
456         decoder->private_->seek_callback = seek_callback;
457         decoder->private_->tell_callback = tell_callback;
458         decoder->private_->length_callback = length_callback;
459         decoder->private_->eof_callback = eof_callback;
460         decoder->private_->write_callback = write_callback;
461         decoder->private_->metadata_callback = metadata_callback;
462         decoder->private_->error_callback = error_callback;
463         decoder->private_->client_data = client_data;
464         decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
465         decoder->private_->samples_decoded = 0;
466         decoder->private_->has_stream_info = false;
467         decoder->private_->cached = false;
468
469         decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
470         decoder->private_->is_seeking = false;
471
472         decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
473         if(!FLAC__stream_decoder_reset(decoder)) {
474                 /* above call sets the state for us */
475                 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
476         }
477
478         return FLAC__STREAM_DECODER_INIT_STATUS_OK;
479 }
480
481 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
482         FLAC__StreamDecoder *decoder,
483         FLAC__StreamDecoderReadCallback read_callback,
484         FLAC__StreamDecoderSeekCallback seek_callback,
485         FLAC__StreamDecoderTellCallback tell_callback,
486         FLAC__StreamDecoderLengthCallback length_callback,
487         FLAC__StreamDecoderEofCallback eof_callback,
488         FLAC__StreamDecoderWriteCallback write_callback,
489         FLAC__StreamDecoderMetadataCallback metadata_callback,
490         FLAC__StreamDecoderErrorCallback error_callback,
491         void *client_data
492 )
493 {
494         return init_stream_internal_(
495                 decoder,
496                 read_callback,
497                 seek_callback,
498                 tell_callback,
499                 length_callback,
500                 eof_callback,
501                 write_callback,
502                 metadata_callback,
503                 error_callback,
504                 client_data,
505                 /*is_ogg=*/false
506         );
507 }
508
509 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
510         FLAC__StreamDecoder *decoder,
511         FLAC__StreamDecoderReadCallback read_callback,
512         FLAC__StreamDecoderSeekCallback seek_callback,
513         FLAC__StreamDecoderTellCallback tell_callback,
514         FLAC__StreamDecoderLengthCallback length_callback,
515         FLAC__StreamDecoderEofCallback eof_callback,
516         FLAC__StreamDecoderWriteCallback write_callback,
517         FLAC__StreamDecoderMetadataCallback metadata_callback,
518         FLAC__StreamDecoderErrorCallback error_callback,
519         void *client_data
520 )
521 {
522         return init_stream_internal_(
523                 decoder,
524                 read_callback,
525                 seek_callback,
526                 tell_callback,
527                 length_callback,
528                 eof_callback,
529                 write_callback,
530                 metadata_callback,
531                 error_callback,
532                 client_data,
533                 /*is_ogg=*/true
534         );
535 }
536
537 static FLAC__StreamDecoderInitStatus init_FILE_internal_(
538         FLAC__StreamDecoder *decoder,
539         FILE *file,
540         FLAC__StreamDecoderWriteCallback write_callback,
541         FLAC__StreamDecoderMetadataCallback metadata_callback,
542         FLAC__StreamDecoderErrorCallback error_callback,
543         void *client_data,
544         FLAC__bool is_ogg
545 )
546 {
547         FLAC__ASSERT(0 != decoder);
548         FLAC__ASSERT(0 != file);
549
550         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
551                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
552
553         if(0 == write_callback || 0 == error_callback)
554                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
555
556         /*
557          * To make sure that our file does not go unclosed after an error, we
558          * must assign the FILE pointer before any further error can occur in
559          * this routine.
560          */
561         if(file == stdin)
562                 file = get_binary_stdin_(); /* just to be safe */
563
564         decoder->private_->file = file;
565
566         return init_stream_internal_(
567                 decoder,
568                 file_read_callback_,
569                 decoder->private_->file == stdin? 0: file_seek_callback_,
570                 decoder->private_->file == stdin? 0: file_tell_callback_,
571                 decoder->private_->file == stdin? 0: file_length_callback_,
572                 file_eof_callback_,
573                 write_callback,
574                 metadata_callback,
575                 error_callback,
576                 client_data,
577                 is_ogg
578         );
579 }
580
581 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
582         FLAC__StreamDecoder *decoder,
583         FILE *file,
584         FLAC__StreamDecoderWriteCallback write_callback,
585         FLAC__StreamDecoderMetadataCallback metadata_callback,
586         FLAC__StreamDecoderErrorCallback error_callback,
587         void *client_data
588 )
589 {
590         return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
591 }
592
593 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
594         FLAC__StreamDecoder *decoder,
595         FILE *file,
596         FLAC__StreamDecoderWriteCallback write_callback,
597         FLAC__StreamDecoderMetadataCallback metadata_callback,
598         FLAC__StreamDecoderErrorCallback error_callback,
599         void *client_data
600 )
601 {
602         return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
603 }
604
605 static FLAC__StreamDecoderInitStatus init_file_internal_(
606         FLAC__StreamDecoder *decoder,
607         const char *filename,
608         FLAC__StreamDecoderWriteCallback write_callback,
609         FLAC__StreamDecoderMetadataCallback metadata_callback,
610         FLAC__StreamDecoderErrorCallback error_callback,
611         void *client_data,
612         FLAC__bool is_ogg
613 )
614 {
615         FILE *file;
616
617         FLAC__ASSERT(0 != decoder);
618
619         /*
620          * To make sure that our file does not go unclosed after an error, we
621          * have to do the same entrance checks here that are later performed
622          * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
623          */
624         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
625                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
626
627         if(0 == write_callback || 0 == error_callback)
628                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
629
630         file = filename? fopen(filename, "rb") : stdin;
631
632         if(0 == file)
633                 return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
634
635         return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
636 }
637
638 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
639         FLAC__StreamDecoder *decoder,
640         const char *filename,
641         FLAC__StreamDecoderWriteCallback write_callback,
642         FLAC__StreamDecoderMetadataCallback metadata_callback,
643         FLAC__StreamDecoderErrorCallback error_callback,
644         void *client_data
645 )
646 {
647         return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
648 }
649
650 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
651         FLAC__StreamDecoder *decoder,
652         const char *filename,
653         FLAC__StreamDecoderWriteCallback write_callback,
654         FLAC__StreamDecoderMetadataCallback metadata_callback,
655         FLAC__StreamDecoderErrorCallback error_callback,
656         void *client_data
657 )
658 {
659         return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
660 }
661
662 FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
663 {
664         FLAC__bool md5_failed = false;
665         unsigned i;
666
667         FLAC__ASSERT(0 != decoder);
668         FLAC__ASSERT(0 != decoder->private_);
669         FLAC__ASSERT(0 != decoder->protected_);
670
671         if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
672                 return true;
673
674         /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
675          * always call FLAC__MD5Final()
676          */
677         FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
678
679         if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
680                 free(decoder->private_->seek_table.data.seek_table.points);
681                 decoder->private_->seek_table.data.seek_table.points = 0;
682                 decoder->private_->has_seek_table = false;
683         }
684         FLAC__bitreader_free(decoder->private_->input);
685         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
686                 /* WATCHOUT:
687                  * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
688                  * output arrays have a buffer of up to 3 zeroes in front
689                  * (at negative indices) for alignment purposes; we use 4
690                  * to keep the data well-aligned.
691                  */
692                 if(0 != decoder->private_->output[i]) {
693                         free(decoder->private_->output[i]-4);
694                         decoder->private_->output[i] = 0;
695                 }
696                 if(0 != decoder->private_->residual_unaligned[i]) {
697                         free(decoder->private_->residual_unaligned[i]);
698                         decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
699                 }
700         }
701         decoder->private_->output_capacity = 0;
702         decoder->private_->output_channels = 0;
703
704 #if FLAC__HAS_OGG
705         if(decoder->private_->is_ogg)
706                 FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
707 #endif
708
709         if(0 != decoder->private_->file) {
710                 if(decoder->private_->file != stdin)
711                         fclose(decoder->private_->file);
712                 decoder->private_->file = 0;
713         }
714
715         if(decoder->private_->do_md5_checking) {
716                 if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
717                         md5_failed = true;
718         }
719         decoder->private_->is_seeking = false;
720
721         set_defaults_(decoder);
722
723         decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
724
725         return !md5_failed;
726 }
727
728 FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
729 {
730         FLAC__ASSERT(0 != decoder);
731         FLAC__ASSERT(0 != decoder->private_);
732         FLAC__ASSERT(0 != decoder->protected_);
733         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
734                 return false;
735 #if FLAC__HAS_OGG
736         /* can't check decoder->private_->is_ogg since that's not set until init time */
737         FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
738         return true;
739 #else
740         (void)value;
741         return false;
742 #endif
743 }
744
745 FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
746 {
747         FLAC__ASSERT(0 != decoder);
748         FLAC__ASSERT(0 != decoder->protected_);
749         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
750                 return false;
751         decoder->protected_->md5_checking = value;
752         return true;
753 }
754
755 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
756 {
757         FLAC__ASSERT(0 != decoder);
758         FLAC__ASSERT(0 != decoder->private_);
759         FLAC__ASSERT(0 != decoder->protected_);
760         FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
761         /* double protection */
762         if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
763                 return false;
764         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
765                 return false;
766         decoder->private_->metadata_filter[type] = true;
767         if(type == FLAC__METADATA_TYPE_APPLICATION)
768                 decoder->private_->metadata_filter_ids_count = 0;
769         return true;
770 }
771
772 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
773 {
774         FLAC__ASSERT(0 != decoder);
775         FLAC__ASSERT(0 != decoder->private_);
776         FLAC__ASSERT(0 != decoder->protected_);
777         FLAC__ASSERT(0 != id);
778         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
779                 return false;
780
781         if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
782                 return true;
783
784         FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
785
786         if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
787                 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2))) {
788                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
789                         return false;
790                 }
791                 decoder->private_->metadata_filter_ids_capacity *= 2;
792         }
793
794         memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
795         decoder->private_->metadata_filter_ids_count++;
796
797         return true;
798 }
799
800 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
801 {
802         unsigned i;
803         FLAC__ASSERT(0 != decoder);
804         FLAC__ASSERT(0 != decoder->private_);
805         FLAC__ASSERT(0 != decoder->protected_);
806         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
807                 return false;
808         for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
809                 decoder->private_->metadata_filter[i] = true;
810         decoder->private_->metadata_filter_ids_count = 0;
811         return true;
812 }
813
814 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
815 {
816         FLAC__ASSERT(0 != decoder);
817         FLAC__ASSERT(0 != decoder->private_);
818         FLAC__ASSERT(0 != decoder->protected_);
819         FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
820         /* double protection */
821         if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
822                 return false;
823         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
824                 return false;
825         decoder->private_->metadata_filter[type] = false;
826         if(type == FLAC__METADATA_TYPE_APPLICATION)
827                 decoder->private_->metadata_filter_ids_count = 0;
828         return true;
829 }
830
831 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
832 {
833         FLAC__ASSERT(0 != decoder);
834         FLAC__ASSERT(0 != decoder->private_);
835         FLAC__ASSERT(0 != decoder->protected_);
836         FLAC__ASSERT(0 != id);
837         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
838                 return false;
839
840         if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
841                 return true;
842
843         FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
844
845         if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
846                 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2))) {
847                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
848                         return false;
849                 }
850                 decoder->private_->metadata_filter_ids_capacity *= 2;
851         }
852
853         memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
854         decoder->private_->metadata_filter_ids_count++;
855
856         return true;
857 }
858
859 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
860 {
861         FLAC__ASSERT(0 != decoder);
862         FLAC__ASSERT(0 != decoder->private_);
863         FLAC__ASSERT(0 != decoder->protected_);
864         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
865                 return false;
866         memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
867         decoder->private_->metadata_filter_ids_count = 0;
868         return true;
869 }
870
871 FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
872 {
873         FLAC__ASSERT(0 != decoder);
874         FLAC__ASSERT(0 != decoder->protected_);
875         return decoder->protected_->state;
876 }
877
878 FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
879 {
880         return FLAC__StreamDecoderStateString[decoder->protected_->state];
881 }
882
883 FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
884 {
885         FLAC__ASSERT(0 != decoder);
886         FLAC__ASSERT(0 != decoder->protected_);
887         return decoder->protected_->md5_checking;
888 }
889
890 FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
891 {
892         FLAC__ASSERT(0 != decoder);
893         FLAC__ASSERT(0 != decoder->protected_);
894         return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
895 }
896
897 FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
898 {
899         FLAC__ASSERT(0 != decoder);
900         FLAC__ASSERT(0 != decoder->protected_);
901         return decoder->protected_->channels;
902 }
903
904 FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
905 {
906         FLAC__ASSERT(0 != decoder);
907         FLAC__ASSERT(0 != decoder->protected_);
908         return decoder->protected_->channel_assignment;
909 }
910
911 FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
912 {
913         FLAC__ASSERT(0 != decoder);
914         FLAC__ASSERT(0 != decoder->protected_);
915         return decoder->protected_->bits_per_sample;
916 }
917
918 FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
919 {
920         FLAC__ASSERT(0 != decoder);
921         FLAC__ASSERT(0 != decoder->protected_);
922         return decoder->protected_->sample_rate;
923 }
924
925 FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
926 {
927         FLAC__ASSERT(0 != decoder);
928         FLAC__ASSERT(0 != decoder->protected_);
929         return decoder->protected_->blocksize;
930 }
931
932 FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
933 {
934         FLAC__ASSERT(0 != decoder);
935         FLAC__ASSERT(0 != decoder->private_);
936         FLAC__ASSERT(0 != position);
937
938 #if FLAC__HAS_OGG
939         if(decoder->private_->is_ogg)
940                 return false;
941 #endif
942         if(0 == decoder->private_->tell_callback)
943                 return false;
944         if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
945                 return false;
946         /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
947         if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
948                 return false;
949         FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
950         *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
951         return true;
952 }
953
954 FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
955 {
956         FLAC__ASSERT(0 != decoder);
957         FLAC__ASSERT(0 != decoder->private_);
958         FLAC__ASSERT(0 != decoder->protected_);
959
960         decoder->private_->samples_decoded = 0;
961         decoder->private_->do_md5_checking = false;
962
963 #if FLAC__HAS_OGG
964         if(decoder->private_->is_ogg)
965                 FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
966 #endif
967
968         if(!FLAC__bitreader_clear(decoder->private_->input)) {
969                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
970                 return false;
971         }
972         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
973
974         return true;
975 }
976
977 FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
978 {
979         FLAC__ASSERT(0 != decoder);
980         FLAC__ASSERT(0 != decoder->private_);
981         FLAC__ASSERT(0 != decoder->protected_);
982
983         if(!FLAC__stream_decoder_flush(decoder)) {
984                 /* above call sets the state for us */
985                 return false;
986         }
987
988 #if FLAC__HAS_OGG
989         /*@@@ could go in !internal_reset_hack block below */
990         if(decoder->private_->is_ogg)
991                 FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
992 #endif
993
994         /* Rewind if necessary.  If FLAC__stream_decoder_init() is calling us,
995          * (internal_reset_hack) don't try to rewind since we are already at
996          * the beginning of the stream and don't want to fail if the input is
997          * not seekable.
998          */
999         if(!decoder->private_->internal_reset_hack) {
1000                 if(decoder->private_->file == stdin)
1001                         return false; /* can't rewind stdin, reset fails */
1002                 if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
1003                         return false; /* seekable and seek fails, reset fails */
1004         }
1005         else
1006                 decoder->private_->internal_reset_hack = false;
1007
1008         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
1009
1010         decoder->private_->has_stream_info = false;
1011         if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
1012                 free(decoder->private_->seek_table.data.seek_table.points);
1013                 decoder->private_->seek_table.data.seek_table.points = 0;
1014                 decoder->private_->has_seek_table = false;
1015         }
1016         decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
1017         /*
1018          * This goes in reset() and not flush() because according to the spec, a
1019          * fixed-blocksize stream must stay that way through the whole stream.
1020          */
1021         decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
1022
1023         /* We initialize the FLAC__MD5Context even though we may never use it.  This
1024          * is because md5 checking may be turned on to start and then turned off if
1025          * a seek occurs.  So we init the context here and finalize it in
1026          * FLAC__stream_decoder_finish() to make sure things are always cleaned up
1027          * properly.
1028          */
1029         FLAC__MD5Init(&decoder->private_->md5context);
1030
1031         decoder->private_->first_frame_offset = 0;
1032         decoder->private_->unparseable_frame_count = 0;
1033
1034         return true;
1035 }
1036
1037 FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
1038 {
1039         FLAC__bool got_a_frame;
1040         FLAC__ASSERT(0 != decoder);
1041         FLAC__ASSERT(0 != decoder->protected_);
1042
1043         while(1) {
1044                 switch(decoder->protected_->state) {
1045                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1046                                 if(!find_metadata_(decoder))
1047                                         return false; /* above function sets the status for us */
1048                                 break;
1049                         case FLAC__STREAM_DECODER_READ_METADATA:
1050                                 if(!read_metadata_(decoder))
1051                                         return false; /* above function sets the status for us */
1052                                 else
1053                                         return true;
1054                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1055                                 if(!frame_sync_(decoder))
1056                                         return true; /* above function sets the status for us */
1057                                 break;
1058                         case FLAC__STREAM_DECODER_READ_FRAME:
1059                                 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
1060                                         return false; /* above function sets the status for us */
1061                                 if(got_a_frame)
1062                                         return true; /* above function sets the status for us */
1063                                 break;
1064                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1065                         case FLAC__STREAM_DECODER_ABORTED:
1066                                 return true;
1067                         default:
1068                                 FLAC__ASSERT(0);
1069                                 return false;
1070                 }
1071         }
1072 }
1073
1074 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
1075 {
1076         FLAC__ASSERT(0 != decoder);
1077         FLAC__ASSERT(0 != decoder->protected_);
1078
1079         while(1) {
1080                 switch(decoder->protected_->state) {
1081                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1082                                 if(!find_metadata_(decoder))
1083                                         return false; /* above function sets the status for us */
1084                                 break;
1085                         case FLAC__STREAM_DECODER_READ_METADATA:
1086                                 if(!read_metadata_(decoder))
1087                                         return false; /* above function sets the status for us */
1088                                 break;
1089                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1090                         case FLAC__STREAM_DECODER_READ_FRAME:
1091                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1092                         case FLAC__STREAM_DECODER_ABORTED:
1093                                 return true;
1094                         default:
1095                                 FLAC__ASSERT(0);
1096                                 return false;
1097                 }
1098         }
1099 }
1100
1101 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
1102 {
1103         FLAC__bool dummy;
1104         FLAC__ASSERT(0 != decoder);
1105         FLAC__ASSERT(0 != decoder->protected_);
1106
1107         while(1) {
1108                 switch(decoder->protected_->state) {
1109                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1110                                 if(!find_metadata_(decoder))
1111                                         return false; /* above function sets the status for us */
1112                                 break;
1113                         case FLAC__STREAM_DECODER_READ_METADATA:
1114                                 if(!read_metadata_(decoder))
1115                                         return false; /* above function sets the status for us */
1116                                 break;
1117                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1118                                 if(!frame_sync_(decoder))
1119                                         return true; /* above function sets the status for us */
1120                                 break;
1121                         case FLAC__STREAM_DECODER_READ_FRAME:
1122                                 if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
1123                                         return false; /* above function sets the status for us */
1124                                 break;
1125                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1126                         case FLAC__STREAM_DECODER_ABORTED:
1127                                 return true;
1128                         default:
1129                                 FLAC__ASSERT(0);
1130                                 return false;
1131                 }
1132         }
1133 }
1134
1135 FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
1136 {
1137         FLAC__bool got_a_frame;
1138         FLAC__ASSERT(0 != decoder);
1139         FLAC__ASSERT(0 != decoder->protected_);
1140
1141         while(1) {
1142                 switch(decoder->protected_->state) {
1143                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1144                         case FLAC__STREAM_DECODER_READ_METADATA:
1145                                 return false; /* above function sets the status for us */
1146                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1147                                 if(!frame_sync_(decoder))
1148                                         return true; /* above function sets the status for us */
1149                                 break;
1150                         case FLAC__STREAM_DECODER_READ_FRAME:
1151                                 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
1152                                         return false; /* above function sets the status for us */
1153                                 if(got_a_frame)
1154                                         return true; /* above function sets the status for us */
1155                                 break;
1156                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1157                         case FLAC__STREAM_DECODER_ABORTED:
1158                                 return true;
1159                         default:
1160                                 FLAC__ASSERT(0);
1161                                 return false;
1162                 }
1163         }
1164 }
1165
1166 FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
1167 {
1168         FLAC__uint64 length;
1169
1170         FLAC__ASSERT(0 != decoder);
1171
1172         if(
1173                 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
1174                 decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
1175                 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
1176                 decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
1177                 decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
1178         )
1179                 return false;
1180
1181         if(0 == decoder->private_->seek_callback)
1182                 return false;
1183
1184         FLAC__ASSERT(decoder->private_->seek_callback);
1185         FLAC__ASSERT(decoder->private_->tell_callback);
1186         FLAC__ASSERT(decoder->private_->length_callback);
1187         FLAC__ASSERT(decoder->private_->eof_callback);
1188
1189         if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
1190                 return false;
1191
1192         decoder->private_->is_seeking = true;
1193
1194         /* turn off md5 checking if a seek is attempted */
1195         decoder->private_->do_md5_checking = false;
1196
1197         /* get the file length (currently our algorithm needs to know the length so it's also an error to get FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED) */
1198         if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
1199                 decoder->private_->is_seeking = false;
1200                 return false;
1201         }
1202
1203         /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
1204         if(
1205                 decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
1206                 decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
1207         ) {
1208                 if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
1209                         /* above call sets the state for us */
1210                         decoder->private_->is_seeking = false;
1211                         return false;
1212                 }
1213                 /* check this again in case we didn't know total_samples the first time */
1214                 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
1215                         decoder->private_->is_seeking = false;
1216                         return false;
1217                 }
1218         }
1219
1220         {
1221                 const FLAC__bool ok =
1222 #if FLAC__HAS_OGG
1223                         decoder->private_->is_ogg?
1224                         seek_to_absolute_sample_ogg_(decoder, length, sample) :
1225 #endif
1226                         seek_to_absolute_sample_(decoder, length, sample)
1227                 ;
1228                 decoder->private_->is_seeking = false;
1229                 return ok;
1230         }
1231 }
1232
1233 /***********************************************************************
1234  *
1235  * Protected class methods
1236  *
1237  ***********************************************************************/
1238
1239 unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
1240 {
1241         FLAC__ASSERT(0 != decoder);
1242         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1243         FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
1244         return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
1245 }
1246
1247 /***********************************************************************
1248  *
1249  * Private class methods
1250  *
1251  ***********************************************************************/
1252
1253 void set_defaults_(FLAC__StreamDecoder *decoder)
1254 {
1255 #if FLAC__HAS_OGG
1256         decoder->private_->is_ogg = false;
1257 #endif
1258         decoder->private_->read_callback = 0;
1259         decoder->private_->seek_callback = 0;
1260         decoder->private_->tell_callback = 0;
1261         decoder->private_->length_callback = 0;
1262         decoder->private_->eof_callback = 0;
1263         decoder->private_->write_callback = 0;
1264         decoder->private_->metadata_callback = 0;
1265         decoder->private_->error_callback = 0;
1266         decoder->private_->client_data = 0;
1267
1268         memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
1269         decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
1270         decoder->private_->metadata_filter_ids_count = 0;
1271
1272         decoder->protected_->md5_checking = false;
1273
1274 #if FLAC__HAS_OGG
1275         FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
1276 #endif
1277 }
1278
1279 /*
1280  * This will forcibly set stdin to binary mode (for OSes that require it)
1281  */
1282 FILE *get_binary_stdin_(void)
1283 {
1284         /* if something breaks here it is probably due to the presence or
1285          * absence of an underscore before the identifiers 'setmode',
1286          * 'fileno', and/or 'O_BINARY'; check your system header files.
1287          */
1288 #if defined _MSC_VER || defined __MINGW32__
1289         _setmode(_fileno(stdin), _O_BINARY);
1290 #elif defined __CYGWIN__ 
1291         /* almost certainly not needed for any modern Cygwin, but let's be safe... */
1292         setmode(_fileno(stdin), _O_BINARY);
1293 #elif defined __EMX__
1294         setmode(fileno(stdin), O_BINARY);
1295 #endif
1296
1297         return stdin;
1298 }
1299
1300 FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
1301 {
1302         unsigned i;
1303         FLAC__int32 *tmp;
1304
1305         if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
1306                 return true;
1307
1308         /* simply using realloc() is not practical because the number of channels may change mid-stream */
1309
1310         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
1311                 if(0 != decoder->private_->output[i]) {
1312                         free(decoder->private_->output[i]-4);
1313                         decoder->private_->output[i] = 0;
1314                 }
1315                 if(0 != decoder->private_->residual_unaligned[i]) {
1316                         free(decoder->private_->residual_unaligned[i]);
1317                         decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
1318                 }
1319         }
1320
1321         for(i = 0; i < channels; i++) {
1322                 /* WATCHOUT:
1323                  * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
1324                  * output arrays have a buffer of up to 3 zeroes in front
1325                  * (at negative indices) for alignment purposes; we use 4
1326                  * to keep the data well-aligned.
1327                  */
1328                 tmp = (FLAC__int32*)malloc(sizeof(FLAC__int32)*(size+4));
1329                 if(tmp == 0) {
1330                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1331                         return false;
1332                 }
1333                 memset(tmp, 0, sizeof(FLAC__int32)*4);
1334                 decoder->private_->output[i] = tmp + 4;
1335
1336                 /* WATCHOUT:
1337                  * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
1338                  */
1339                 if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
1340                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1341                         return false;
1342                 }
1343         }
1344
1345         decoder->private_->output_capacity = size;
1346         decoder->private_->output_channels = channels;
1347
1348         return true;
1349 }
1350
1351 FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
1352 {
1353         unsigned i;
1354
1355         FLAC__ASSERT(0 != decoder);
1356         FLAC__ASSERT(0 != decoder->private_);
1357
1358         for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
1359                 if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
1360                         return true;
1361
1362         return false;
1363 }
1364
1365 FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
1366 {
1367         FLAC__uint32 x;
1368         unsigned i, id;
1369         FLAC__bool first = true;
1370
1371         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1372
1373         for(i = id = 0; i < 4; ) {
1374                 if(decoder->private_->cached) {
1375                         x = (FLAC__uint32)decoder->private_->lookahead;
1376                         decoder->private_->cached = false;
1377                 }
1378                 else {
1379                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1380                                 return false; /* read_callback_ sets the state for us */
1381                 }
1382                 if(x == FLAC__STREAM_SYNC_STRING[i]) {
1383                         first = true;
1384                         i++;
1385                         id = 0;
1386                         continue;
1387                 }
1388                 if(x == ID3V2_TAG_[id]) {
1389                         id++;
1390                         i = 0;
1391                         if(id == 3) {
1392                                 if(!skip_id3v2_tag_(decoder))
1393                                         return false; /* skip_id3v2_tag_ sets the state for us */
1394                         }
1395                         continue;
1396                 }
1397                 id = 0;
1398                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1399                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1400                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1401                                 return false; /* read_callback_ sets the state for us */
1402
1403                         /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
1404                         /* else we have to check if the second byte is the end of a sync code */
1405                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1406                                 decoder->private_->lookahead = (FLAC__byte)x;
1407                                 decoder->private_->cached = true;
1408                         }
1409                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1410                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1411                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1412                                 return true;
1413                         }
1414                 }
1415                 i = 0;
1416                 if(first) {
1417                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1418                         first = false;
1419                 }
1420         }
1421
1422         decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
1423         return true;
1424 }
1425
1426 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
1427 {
1428         FLAC__bool is_last;
1429         FLAC__uint32 i, x, type, length;
1430
1431         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1432
1433         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
1434                 return false; /* read_callback_ sets the state for us */
1435         is_last = x? true : false;
1436
1437         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
1438                 return false; /* read_callback_ sets the state for us */
1439
1440         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
1441                 return false; /* read_callback_ sets the state for us */
1442
1443         if(type == FLAC__METADATA_TYPE_STREAMINFO) {
1444                 if(!read_metadata_streaminfo_(decoder, is_last, length))
1445                         return false;
1446
1447                 decoder->private_->has_stream_info = true;
1448                 if(0 == memcmp(decoder->private_->stream_info.data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
1449                         decoder->private_->do_md5_checking = false;
1450                 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
1451                         decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
1452         }
1453         else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
1454                 if(!read_metadata_seektable_(decoder, is_last, length))
1455                         return false;
1456
1457                 decoder->private_->has_seek_table = true;
1458                 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
1459                         decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
1460         }
1461         else {
1462                 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
1463                 unsigned real_length = length;
1464                 FLAC__StreamMetadata block;
1465
1466                 block.is_last = is_last;
1467                 block.type = (FLAC__MetadataType)type;
1468                 block.length = length;
1469
1470                 if(type == FLAC__METADATA_TYPE_APPLICATION) {
1471                         if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
1472                                 return false; /* read_callback_ sets the state for us */
1473
1474                         real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
1475
1476                         if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
1477                                 skip_it = !skip_it;
1478                 }
1479
1480                 if(skip_it) {
1481                         if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
1482                                 return false; /* read_callback_ sets the state for us */
1483                 }
1484                 else {
1485                         switch(type) {
1486                                 case FLAC__METADATA_TYPE_PADDING:
1487                                         /* skip the padding bytes */
1488                                         if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
1489                                                 return false; /* read_callback_ sets the state for us */
1490                                         break;
1491                                 case FLAC__METADATA_TYPE_APPLICATION:
1492                                         /* remember, we read the ID already */
1493                                         if(real_length > 0) {
1494                                                 if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
1495                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1496                                                         return false;
1497                                                 }
1498                                                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
1499                                                         return false; /* read_callback_ sets the state for us */
1500                                         }
1501                                         else
1502                                                 block.data.application.data = 0;
1503                                         break;
1504                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1505                                         if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
1506                                                 return false;
1507                                         break;
1508                                 case FLAC__METADATA_TYPE_CUESHEET:
1509                                         if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
1510                                                 return false;
1511                                         break;
1512                                 case FLAC__METADATA_TYPE_PICTURE:
1513                                         if(!read_metadata_picture_(decoder, &block.data.picture))
1514                                                 return false;
1515                                         break;
1516                                 case FLAC__METADATA_TYPE_STREAMINFO:
1517                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1518                                         FLAC__ASSERT(0);
1519                                         break;
1520                                 default:
1521                                         if(real_length > 0) {
1522                                                 if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
1523                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1524                                                         return false;
1525                                                 }
1526                                                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
1527                                                         return false; /* read_callback_ sets the state for us */
1528                                         }
1529                                         else
1530                                                 block.data.unknown.data = 0;
1531                                         break;
1532                         }
1533                         if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
1534                                 decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1535
1536                         /* now we have to free any malloc'ed data in the block */
1537                         switch(type) {
1538                                 case FLAC__METADATA_TYPE_PADDING:
1539                                         break;
1540                                 case FLAC__METADATA_TYPE_APPLICATION:
1541                                         if(0 != block.data.application.data)
1542                                                 free(block.data.application.data);
1543                                         break;
1544                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1545                                         if(0 != block.data.vorbis_comment.vendor_string.entry)
1546                                                 free(block.data.vorbis_comment.vendor_string.entry);
1547                                         if(block.data.vorbis_comment.num_comments > 0)
1548                                                 for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
1549                                                         if(0 != block.data.vorbis_comment.comments[i].entry)
1550                                                                 free(block.data.vorbis_comment.comments[i].entry);
1551                                         if(0 != block.data.vorbis_comment.comments)
1552                                                 free(block.data.vorbis_comment.comments);
1553                                         break;
1554                                 case FLAC__METADATA_TYPE_CUESHEET:
1555                                         if(block.data.cue_sheet.num_tracks > 0)
1556                                                 for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
1557                                                         if(0 != block.data.cue_sheet.tracks[i].indices)
1558                                                                 free(block.data.cue_sheet.tracks[i].indices);
1559                                         if(0 != block.data.cue_sheet.tracks)
1560                                                 free(block.data.cue_sheet.tracks);
1561                                         break;
1562                                 case FLAC__METADATA_TYPE_PICTURE:
1563                                         if(0 != block.data.picture.mime_type)
1564                                                 free(block.data.picture.mime_type);
1565                                         if(0 != block.data.picture.description)
1566                                                 free(block.data.picture.description);
1567                                         if(0 != block.data.picture.data)
1568                                                 free(block.data.picture.data);
1569                                         break;
1570                                 case FLAC__METADATA_TYPE_STREAMINFO:
1571                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1572                                         FLAC__ASSERT(0);
1573                                 default:
1574                                         if(0 != block.data.unknown.data)
1575                                                 free(block.data.unknown.data);
1576                                         break;
1577                         }
1578                 }
1579         }
1580
1581         if(is_last) {
1582                 /* if this fails, it's OK, it's just a hint for the seek routine */
1583                 if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
1584                         decoder->private_->first_frame_offset = 0;
1585                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1586         }
1587
1588         return true;
1589 }
1590
1591 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1592 {
1593         FLAC__uint32 x;
1594         unsigned bits, used_bits = 0;
1595
1596         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1597
1598         decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
1599         decoder->private_->stream_info.is_last = is_last;
1600         decoder->private_->stream_info.length = length;
1601
1602         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1603         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
1604                 return false; /* read_callback_ sets the state for us */
1605         decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1606         used_bits += bits;
1607
1608         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1609         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
1610                 return false; /* read_callback_ sets the state for us */
1611         decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1612         used_bits += bits;
1613
1614         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1615         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
1616                 return false; /* read_callback_ sets the state for us */
1617         decoder->private_->stream_info.data.stream_info.min_framesize = x;
1618         used_bits += bits;
1619
1620         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1621         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
1622                 return false; /* read_callback_ sets the state for us */
1623         decoder->private_->stream_info.data.stream_info.max_framesize = x;
1624         used_bits += bits;
1625
1626         bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1627         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
1628                 return false; /* read_callback_ sets the state for us */
1629         decoder->private_->stream_info.data.stream_info.sample_rate = x;
1630         used_bits += bits;
1631
1632         bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1633         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
1634                 return false; /* read_callback_ sets the state for us */
1635         decoder->private_->stream_info.data.stream_info.channels = x+1;
1636         used_bits += bits;
1637
1638         bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1639         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
1640                 return false; /* read_callback_ sets the state for us */
1641         decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1642         used_bits += bits;
1643
1644         bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1645         if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
1646                 return false; /* read_callback_ sets the state for us */
1647         used_bits += bits;
1648
1649         if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
1650                 return false; /* read_callback_ sets the state for us */
1651         used_bits += 16*8;
1652
1653         /* skip the rest of the block */
1654         FLAC__ASSERT(used_bits % 8 == 0);
1655         length -= (used_bits / 8);
1656         if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
1657                 return false; /* read_callback_ sets the state for us */
1658
1659         return true;
1660 }
1661
1662 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1663 {
1664         FLAC__uint32 i, x;
1665         FLAC__uint64 xx;
1666
1667         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1668
1669         decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1670         decoder->private_->seek_table.is_last = is_last;
1671         decoder->private_->seek_table.length = length;
1672
1673         decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1674
1675         /* use realloc since we may pass through here several times (e.g. after seeking) */
1676         if(0 == (decoder->private_->seek_table.data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)realloc(decoder->private_->seek_table.data.seek_table.points, decoder->private_->seek_table.data.seek_table.num_points * sizeof(FLAC__StreamMetadata_SeekPoint)))) {
1677                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1678                 return false;
1679         }
1680         for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1681                 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
1682                         return false; /* read_callback_ sets the state for us */
1683                 decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1684
1685                 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
1686                         return false; /* read_callback_ sets the state for us */
1687                 decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1688
1689                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
1690                         return false; /* read_callback_ sets the state for us */
1691                 decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1692         }
1693         length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1694         /* if there is a partial point left, skip over it */
1695         if(length > 0) {
1696                 /*@@@ do a send_error_to_client_() here?  there's an argument for either way */
1697                 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
1698                         return false; /* read_callback_ sets the state for us */
1699         }
1700
1701         return true;
1702 }
1703
1704 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1705 {
1706         FLAC__uint32 i;
1707
1708         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1709
1710         /* read vendor string */
1711         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1712         if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
1713                 return false; /* read_callback_ sets the state for us */
1714         if(obj->vendor_string.length > 0) {
1715                 if(0 == (obj->vendor_string.entry = (FLAC__byte*)malloc(obj->vendor_string.length+1))) {
1716                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1717                         return false;
1718                 }
1719                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
1720                         return false; /* read_callback_ sets the state for us */
1721                 obj->vendor_string.entry[obj->vendor_string.length] = '\0';
1722         }
1723         else
1724                 obj->vendor_string.entry = 0;
1725
1726         /* read num comments */
1727         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1728         if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
1729                 return false; /* read_callback_ sets the state for us */
1730
1731         /* read comments */
1732         if(obj->num_comments > 0) {
1733                 if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)malloc(obj->num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1734                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1735                         return false;
1736                 }
1737                 for(i = 0; i < obj->num_comments; i++) {
1738                         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1739                         if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
1740                                 return false; /* read_callback_ sets the state for us */
1741                         if(obj->comments[i].length > 0) {
1742                                 if(0 == (obj->comments[i].entry = (FLAC__byte*)malloc(obj->comments[i].length+1))) {
1743                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1744                                         return false;
1745                                 }
1746                                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
1747                                         return false; /* read_callback_ sets the state for us */
1748                                 obj->comments[i].entry[obj->comments[i].length] = '\0';
1749                         }
1750                         else
1751                                 obj->comments[i].entry = 0;
1752                 }
1753         }
1754         else {
1755                 obj->comments = 0;
1756         }
1757
1758         return true;
1759 }
1760
1761 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1762 {
1763         FLAC__uint32 i, j, x;
1764
1765         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1766
1767         memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1768
1769         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1770         if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
1771                 return false; /* read_callback_ sets the state for us */
1772
1773         if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
1774                 return false; /* read_callback_ sets the state for us */
1775
1776         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
1777                 return false; /* read_callback_ sets the state for us */
1778         obj->is_cd = x? true : false;
1779
1780         if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
1781                 return false; /* read_callback_ sets the state for us */
1782
1783         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
1784                 return false; /* read_callback_ sets the state for us */
1785         obj->num_tracks = x;
1786
1787         if(obj->num_tracks > 0) {
1788                 if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1789                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1790                         return false;
1791                 }
1792                 for(i = 0; i < obj->num_tracks; i++) {
1793                         FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1794                         if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
1795                                 return false; /* read_callback_ sets the state for us */
1796
1797                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
1798                                 return false; /* read_callback_ sets the state for us */
1799                         track->number = (FLAC__byte)x;
1800
1801                         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1802                         if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
1803                                 return false; /* read_callback_ sets the state for us */
1804
1805                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
1806                                 return false; /* read_callback_ sets the state for us */
1807                         track->type = x;
1808
1809                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
1810                                 return false; /* read_callback_ sets the state for us */
1811                         track->pre_emphasis = x;
1812
1813                         if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
1814                                 return false; /* read_callback_ sets the state for us */
1815
1816                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
1817                                 return false; /* read_callback_ sets the state for us */
1818                         track->num_indices = (FLAC__byte)x;
1819
1820                         if(track->num_indices > 0) {
1821                                 if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1822                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1823                                         return false;
1824                                 }
1825                                 for(j = 0; j < track->num_indices; j++) {
1826                                         FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1827                                         if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
1828                                                 return false; /* read_callback_ sets the state for us */
1829
1830                                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
1831                                                 return false; /* read_callback_ sets the state for us */
1832                                         index->number = (FLAC__byte)x;
1833
1834                                         if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
1835                                                 return false; /* read_callback_ sets the state for us */
1836                                 }
1837                         }
1838                 }
1839         }
1840
1841         return true;
1842 }
1843
1844 FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
1845 {
1846         FLAC__uint32 x;
1847
1848         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1849
1850         /* read type */
1851         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
1852                 return false; /* read_callback_ sets the state for us */
1853         obj->type = x;
1854
1855         /* read MIME type */
1856         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
1857                 return false; /* read_callback_ sets the state for us */
1858         if(0 == (obj->mime_type = (char*)malloc(x+1))) {
1859                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1860                 return false;
1861         }
1862         if(x > 0) {
1863                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
1864                         return false; /* read_callback_ sets the state for us */
1865         }
1866         obj->mime_type[x] = '\0';
1867
1868         /* read description */
1869         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
1870                 return false; /* read_callback_ sets the state for us */
1871         if(0 == (obj->description = (FLAC__byte*)malloc(x+1))) {
1872                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1873                 return false;
1874         }
1875         if(x > 0) {
1876                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
1877                         return false; /* read_callback_ sets the state for us */
1878         }
1879         obj->description[x] = '\0';
1880
1881         /* read width */
1882         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
1883                 return false; /* read_callback_ sets the state for us */
1884
1885         /* read height */
1886         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
1887                 return false; /* read_callback_ sets the state for us */
1888
1889         /* read depth */
1890         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
1891                 return false; /* read_callback_ sets the state for us */
1892
1893         /* read colors */
1894         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
1895                 return false; /* read_callback_ sets the state for us */
1896
1897         /* read data */
1898         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
1899                 return false; /* read_callback_ sets the state for us */
1900         if(0 == (obj->data = (FLAC__byte*)malloc(obj->data_length))) {
1901                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1902                 return false;
1903         }
1904         if(obj->data_length > 0) {
1905                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
1906                         return false; /* read_callback_ sets the state for us */
1907         }
1908
1909         return true;
1910 }
1911
1912 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1913 {
1914         FLAC__uint32 x;
1915         unsigned i, skip;
1916
1917         /* skip the version and flags bytes */
1918         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
1919                 return false; /* read_callback_ sets the state for us */
1920         /* get the size (in bytes) to skip */
1921         skip = 0;
1922         for(i = 0; i < 4; i++) {
1923                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1924                         return false; /* read_callback_ sets the state for us */
1925                 skip <<= 7;
1926                 skip |= (x & 0x7f);
1927         }
1928         /* skip the rest of the tag */
1929         if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
1930                 return false; /* read_callback_ sets the state for us */
1931         return true;
1932 }
1933
1934 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1935 {
1936         FLAC__uint32 x;
1937         FLAC__bool first = true;
1938
1939         /* If we know the total number of samples in the stream, stop if we've read that many. */
1940         /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1941         if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
1942                 if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
1943                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1944                         return true;
1945                 }
1946         }
1947
1948         /* make sure we're byte aligned */
1949         if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
1950                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
1951                         return false; /* read_callback_ sets the state for us */
1952         }
1953
1954         while(1) {
1955                 if(decoder->private_->cached) {
1956                         x = (FLAC__uint32)decoder->private_->lookahead;
1957                         decoder->private_->cached = false;
1958                 }
1959                 else {
1960                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1961                                 return false; /* read_callback_ sets the state for us */
1962                 }
1963                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1964                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1965                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1966                                 return false; /* read_callback_ sets the state for us */
1967
1968                         /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
1969                         /* else we have to check if the second byte is the end of a sync code */
1970                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1971                                 decoder->private_->lookahead = (FLAC__byte)x;
1972                                 decoder->private_->cached = true;
1973                         }
1974                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1975                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1976                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1977                                 return true;
1978                         }
1979                 }
1980                 if(first) {
1981                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1982                         first = false;
1983                 }
1984         }
1985
1986         return true;
1987 }
1988
1989 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
1990 {
1991         unsigned channel;
1992         unsigned i;
1993         FLAC__int32 mid, side;
1994         unsigned frame_crc; /* the one we calculate from the input stream */
1995         FLAC__uint32 x;
1996
1997         *got_a_frame = false;
1998
1999         /* init the CRC */
2000         frame_crc = 0;
2001         frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
2002         frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
2003         FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
2004
2005         if(!read_frame_header_(decoder))
2006                 return false;
2007         if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
2008                 return true;
2009         if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
2010                 return false;
2011         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2012                 /*
2013                  * first figure the correct bits-per-sample of the subframe
2014                  */
2015                 unsigned bps = decoder->private_->frame.header.bits_per_sample;
2016                 switch(decoder->private_->frame.header.channel_assignment) {
2017                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2018                                 /* no adjustment needed */
2019                                 break;
2020                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2021                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2022                                 if(channel == 1)
2023                                         bps++;
2024                                 break;
2025                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2026                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2027                                 if(channel == 0)
2028                                         bps++;
2029                                 break;
2030                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2031                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2032                                 if(channel == 1)
2033                                         bps++;
2034                                 break;
2035                         default:
2036                                 FLAC__ASSERT(0);
2037                 }
2038                 /*
2039                  * now read it
2040                  */
2041                 if(!read_subframe_(decoder, channel, bps, do_full_decode))
2042                         return false;
2043                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2044                         return true;
2045         }
2046         if(!read_zero_padding_(decoder))
2047                 return false;
2048         if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption (i.e. "zero bits" were not all zeroes) */
2049                 return true;
2050
2051         /*
2052          * Read the frame CRC-16 from the footer and check
2053          */
2054         frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
2055         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
2056                 return false; /* read_callback_ sets the state for us */
2057         if(frame_crc == x) {
2058                 if(do_full_decode) {
2059                         /* Undo any special channel coding */
2060                         switch(decoder->private_->frame.header.channel_assignment) {
2061                                 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2062                                         /* do nothing */
2063                                         break;
2064                                 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2065                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2066                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2067                                                 decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
2068                                         break;
2069                                 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2070                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2071                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2072                                                 decoder->private_->output[0][i] += decoder->private_->output[1][i];
2073                                         break;
2074                                 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2075                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2076                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2077 #if 1
2078                                                 mid = decoder->private_->output[0][i];
2079                                                 side = decoder->private_->output[1][i];
2080                                                 mid <<= 1;
2081                                                 mid |= (side & 1); /* i.e. if 'side' is odd... */
2082                                                 decoder->private_->output[0][i] = (mid + side) >> 1;
2083                                                 decoder->private_->output[1][i] = (mid - side) >> 1;
2084 #else
2085                                                 /* OPT: without 'side' temp variable */
2086                                                 mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
2087                                                 decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
2088                                                 decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
2089 #endif
2090                                         }
2091                                         break;
2092                                 default:
2093                                         FLAC__ASSERT(0);
2094                                         break;
2095                         }
2096                 }
2097         }
2098         else {
2099                 /* Bad frame, emit error and zero the output signal */
2100                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
2101                 if(do_full_decode) {
2102                         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2103                                 memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2104                         }
2105                 }
2106         }
2107
2108         *got_a_frame = true;
2109
2110         /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
2111         if(decoder->private_->next_fixed_block_size)
2112                 decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
2113
2114         /* put the latest values into the public section of the decoder instance */
2115         decoder->protected_->channels = decoder->private_->frame.header.channels;
2116         decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
2117         decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
2118         decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
2119         decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
2120
2121         FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2122         decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
2123
2124         /* write it */
2125         if(do_full_decode) {
2126                 if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
2127                         return false;
2128         }
2129
2130         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2131         return true;
2132 }
2133
2134 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
2135 {
2136         FLAC__uint32 x;
2137         FLAC__uint64 xx;
2138         unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
2139         FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
2140         unsigned raw_header_len;
2141         FLAC__bool is_unparseable = false;
2142
2143         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
2144
2145         /* init the raw header with the saved bits from synchronization */
2146         raw_header[0] = decoder->private_->header_warmup[0];
2147         raw_header[1] = decoder->private_->header_warmup[1];
2148         raw_header_len = 2;
2149
2150         /* check to make sure that reserved bit is 0 */
2151         if(raw_header[1] & 0x02) /* MAGIC NUMBER */
2152                 is_unparseable = true;
2153
2154         /*
2155          * Note that along the way as we read the header, we look for a sync
2156          * code inside.  If we find one it would indicate that our original
2157          * sync was bad since there cannot be a sync code in a valid header.
2158          *
2159          * Three kinds of things can go wrong when reading the frame header:
2160          *  1) We may have sync'ed incorrectly and not landed on a frame header.
2161          *     If we don't find a sync code, it can end up looking like we read
2162          *     a valid but unparseable header, until getting to the frame header
2163          *     CRC.  Even then we could get a false positive on the CRC.
2164          *  2) We may have sync'ed correctly but on an unparseable frame (from a
2165          *     future encoder).
2166          *  3) We may be on a damaged frame which appears valid but unparseable.
2167          *
2168          * For all these reasons, we try and read a complete frame header as
2169          * long as it seems valid, even if unparseable, up until the frame
2170          * header CRC.
2171          */
2172
2173         /*
2174          * read in the raw header as bytes so we can CRC it, and parse it on the way
2175          */
2176         for(i = 0; i < 2; i++) {
2177                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2178                         return false; /* read_callback_ sets the state for us */
2179                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
2180                         /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
2181                         decoder->private_->lookahead = (FLAC__byte)x;
2182                         decoder->private_->cached = true;
2183                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2184                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2185                         return true;
2186                 }
2187                 raw_header[raw_header_len++] = (FLAC__byte)x;
2188         }
2189
2190         switch(x = raw_header[2] >> 4) {
2191                 case 0:
2192                         is_unparseable = true;
2193                         break;
2194                 case 1:
2195                         decoder->private_->frame.header.blocksize = 192;
2196                         break;
2197                 case 2:
2198                 case 3:
2199                 case 4:
2200                 case 5:
2201                         decoder->private_->frame.header.blocksize = 576 << (x-2);
2202                         break;
2203                 case 6:
2204                 case 7:
2205                         blocksize_hint = x;
2206                         break;
2207                 case 8:
2208                 case 9:
2209                 case 10:
2210                 case 11:
2211                 case 12:
2212                 case 13:
2213                 case 14:
2214                 case 15:
2215                         decoder->private_->frame.header.blocksize = 256 << (x-8);
2216                         break;
2217                 default:
2218                         FLAC__ASSERT(0);
2219                         break;
2220         }
2221
2222         switch(x = raw_header[2] & 0x0f) {
2223                 case 0:
2224                         if(decoder->private_->has_stream_info)
2225                                 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
2226                         else
2227                                 is_unparseable = true;
2228                         break;
2229                 case 1:
2230                         decoder->private_->frame.header.sample_rate = 88200;
2231                         break;
2232                 case 2:
2233                         decoder->private_->frame.header.sample_rate = 176400;
2234                         break;
2235                 case 3:
2236                         decoder->private_->frame.header.sample_rate = 192000;
2237                         break;
2238                 case 4:
2239                         decoder->private_->frame.header.sample_rate = 8000;
2240                         break;
2241                 case 5:
2242                         decoder->private_->frame.header.sample_rate = 16000;
2243                         break;
2244                 case 6:
2245                         decoder->private_->frame.header.sample_rate = 22050;
2246                         break;
2247                 case 7:
2248                         decoder->private_->frame.header.sample_rate = 24000;
2249                         break;
2250                 case 8:
2251                         decoder->private_->frame.header.sample_rate = 32000;
2252                         break;
2253                 case 9:
2254                         decoder->private_->frame.header.sample_rate = 44100;
2255                         break;
2256                 case 10:
2257                         decoder->private_->frame.header.sample_rate = 48000;
2258                         break;
2259                 case 11:
2260                         decoder->private_->frame.header.sample_rate = 96000;
2261                         break;
2262                 case 12:
2263                 case 13:
2264                 case 14:
2265                         sample_rate_hint = x;
2266                         break;
2267                 case 15:
2268                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2269                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2270                         return true;
2271                 default:
2272                         FLAC__ASSERT(0);
2273         }
2274
2275         x = (unsigned)(raw_header[3] >> 4);
2276         if(x & 8) {
2277                 decoder->private_->frame.header.channels = 2;
2278                 switch(x & 7) {
2279                         case 0:
2280                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2281                                 break;
2282                         case 1:
2283                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2284                                 break;
2285                         case 2:
2286                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2287                                 break;
2288                         default:
2289                                 is_unparseable = true;
2290                                 break;
2291                 }
2292         }
2293         else {
2294                 decoder->private_->frame.header.channels = (unsigned)x + 1;
2295                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2296         }
2297
2298         switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2299                 case 0:
2300                         if(decoder->private_->has_stream_info)
2301                                 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2302                         else
2303                                 is_unparseable = true;
2304                         break;
2305                 case 1:
2306                         decoder->private_->frame.header.bits_per_sample = 8;
2307                         break;
2308                 case 2:
2309                         decoder->private_->frame.header.bits_per_sample = 12;
2310                         break;
2311                 case 4:
2312                         decoder->private_->frame.header.bits_per_sample = 16;
2313                         break;
2314                 case 5:
2315                         decoder->private_->frame.header.bits_per_sample = 20;
2316                         break;
2317                 case 6:
2318                         decoder->private_->frame.header.bits_per_sample = 24;
2319                         break;
2320                 case 3:
2321                 case 7:
2322                         is_unparseable = true;
2323                         break;
2324                 default:
2325                         FLAC__ASSERT(0);
2326                         break;
2327         }
2328
2329         /* check to make sure that reserved bit is 0 */
2330         if(raw_header[3] & 0x01) /* MAGIC NUMBER */
2331                 is_unparseable = true;
2332
2333         /* read the frame's starting sample number (or frame number as the case may be) */
2334         if(
2335                 raw_header[1] & 0x01 ||
2336                 /*@@@ this clause is a concession to the old way of doing variable blocksize; the only known implementation is flake and can probably be removed without inconveniencing anyone */
2337                 (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
2338         ) { /* variable blocksize */
2339                 if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
2340                         return false; /* read_callback_ sets the state for us */
2341                 if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
2342                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2343                         decoder->private_->cached = true;
2344                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2345                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2346                         return true;
2347                 }
2348                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2349                 decoder->private_->frame.header.number.sample_number = xx;
2350         }
2351         else { /* fixed blocksize */
2352                 if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
2353                         return false; /* read_callback_ sets the state for us */
2354                 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
2355                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2356                         decoder->private_->cached = true;
2357                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2358                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2359                         return true;
2360                 }
2361                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2362                 decoder->private_->frame.header.number.frame_number = x;
2363         }
2364
2365         if(blocksize_hint) {
2366                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2367                         return false; /* read_callback_ sets the state for us */
2368                 raw_header[raw_header_len++] = (FLAC__byte)x;
2369                 if(blocksize_hint == 7) {
2370                         FLAC__uint32 _x;
2371                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2372                                 return false; /* read_callback_ sets the state for us */
2373                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2374                         x = (x << 8) | _x;
2375                 }
2376                 decoder->private_->frame.header.blocksize = x+1;
2377         }
2378
2379         if(sample_rate_hint) {
2380                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2381                         return false; /* read_callback_ sets the state for us */
2382                 raw_header[raw_header_len++] = (FLAC__byte)x;
2383                 if(sample_rate_hint != 12) {
2384                         FLAC__uint32 _x;
2385                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2386                                 return false; /* read_callback_ sets the state for us */
2387                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2388                         x = (x << 8) | _x;
2389                 }
2390                 if(sample_rate_hint == 12)
2391                         decoder->private_->frame.header.sample_rate = x*1000;
2392                 else if(sample_rate_hint == 13)
2393                         decoder->private_->frame.header.sample_rate = x;
2394                 else
2395                         decoder->private_->frame.header.sample_rate = x*10;
2396         }
2397
2398         /* read the CRC-8 byte */
2399         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2400                 return false; /* read_callback_ sets the state for us */
2401         crc8 = (FLAC__byte)x;
2402
2403         if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
2404                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2405                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2406                 return true;
2407         }
2408
2409         /* calculate the sample number from the frame number if needed */
2410         decoder->private_->next_fixed_block_size = 0;
2411         if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
2412                 x = decoder->private_->frame.header.number.frame_number;
2413                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2414                 if(decoder->private_->fixed_block_size)
2415                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
2416                 else if(decoder->private_->has_stream_info) {
2417                         if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
2418                                 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
2419                                 decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
2420                         }
2421                         else
2422                                 is_unparseable = true;
2423                 }
2424                 else if(x == 0) {
2425                         decoder->private_->frame.header.number.sample_number = 0;
2426                         decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
2427                 }
2428                 else {
2429                         /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
2430                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
2431                 }
2432         }
2433
2434         if(is_unparseable) {
2435                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2436                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2437                 return true;
2438         }
2439
2440         return true;
2441 }
2442
2443 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2444 {
2445         FLAC__uint32 x;
2446         FLAC__bool wasted_bits;
2447         unsigned i;
2448
2449         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
2450                 return false; /* read_callback_ sets the state for us */
2451
2452         wasted_bits = (x & 1);
2453         x &= 0xfe;
2454
2455         if(wasted_bits) {
2456                 unsigned u;
2457                 if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
2458                         return false; /* read_callback_ sets the state for us */
2459                 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
2460                 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
2461         }
2462         else
2463                 decoder->private_->frame.subframes[channel].wasted_bits = 0;
2464
2465         /*
2466          * Lots of magic numbers here
2467          */
2468         if(x & 0x80) {
2469                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2470                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2471                 return true;
2472         }
2473         else if(x == 0) {
2474                 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2475                         return false;
2476         }
2477         else if(x == 2) {
2478                 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2479                         return false;
2480         }
2481         else if(x < 16) {
2482                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2483                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2484                 return true;
2485         }
2486         else if(x <= 24) {
2487                 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2488                         return false;
2489                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2490                         return true;
2491         }
2492         else if(x < 64) {
2493                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2494                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2495                 return true;
2496         }
2497         else {
2498                 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2499                         return false;
2500                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2501                         return true;
2502         }
2503
2504         if(wasted_bits && do_full_decode) {
2505                 x = decoder->private_->frame.subframes[channel].wasted_bits;
2506                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2507                         decoder->private_->output[channel][i] <<= x;
2508         }
2509
2510         return true;
2511 }
2512
2513 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2514 {
2515         FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2516         FLAC__int32 x;
2517         unsigned i;
2518         FLAC__int32 *output = decoder->private_->output[channel];
2519
2520         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2521
2522         if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2523                 return false; /* read_callback_ sets the state for us */
2524
2525         subframe->value = x;
2526
2527         /* decode the subframe */
2528         if(do_full_decode) {
2529                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2530                         output[i] = x;
2531         }
2532
2533         return true;
2534 }
2535
2536 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2537 {
2538         FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2539         FLAC__int32 i32;
2540         FLAC__uint32 u32;
2541         unsigned u;
2542
2543         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2544
2545         subframe->residual = decoder->private_->residual[channel];
2546         subframe->order = order;
2547
2548         /* read warm-up samples */
2549         for(u = 0; u < order; u++) {
2550                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2551                         return false; /* read_callback_ sets the state for us */
2552                 subframe->warmup[u] = i32;
2553         }
2554
2555         /* read entropy coding method info */
2556         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2557                 return false; /* read_callback_ sets the state for us */
2558         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2559         switch(subframe->entropy_coding_method.type) {
2560                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2561                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2562                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2563                                 return false; /* read_callback_ sets the state for us */
2564                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2565                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2566                         break;
2567                 default:
2568                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2569                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2570                         return true;
2571         }
2572
2573         /* read residual */
2574         switch(subframe->entropy_coding_method.type) {
2575                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2576                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2577                         if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
2578                                 return false;
2579                         break;
2580                 default:
2581                         FLAC__ASSERT(0);
2582         }
2583
2584         /* decode the subframe */
2585         if(do_full_decode) {
2586                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2587                 FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
2588         }
2589
2590         return true;
2591 }
2592
2593 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2594 {
2595         FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2596         FLAC__int32 i32;
2597         FLAC__uint32 u32;
2598         unsigned u;
2599
2600         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2601
2602         subframe->residual = decoder->private_->residual[channel];
2603         subframe->order = order;
2604
2605         /* read warm-up samples */
2606         for(u = 0; u < order; u++) {
2607                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2608                         return false; /* read_callback_ sets the state for us */
2609                 subframe->warmup[u] = i32;
2610         }
2611
2612         /* read qlp coeff precision */
2613         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
2614                 return false; /* read_callback_ sets the state for us */
2615         if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
2616                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2617                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2618                 return true;
2619         }
2620         subframe->qlp_coeff_precision = u32+1;
2621
2622         /* read qlp shift */
2623         if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
2624                 return false; /* read_callback_ sets the state for us */
2625         subframe->quantization_level = i32;
2626
2627         /* read quantized lp coefficiencts */
2628         for(u = 0; u < order; u++) {
2629                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
2630                         return false; /* read_callback_ sets the state for us */
2631                 subframe->qlp_coeff[u] = i32;
2632         }
2633
2634         /* read entropy coding method info */
2635         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2636                 return false; /* read_callback_ sets the state for us */
2637         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2638         switch(subframe->entropy_coding_method.type) {
2639                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2640                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2641                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2642                                 return false; /* read_callback_ sets the state for us */
2643                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2644                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2645                         break;
2646                 default:
2647                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2648                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2649                         return true;
2650         }
2651
2652         /* read residual */
2653         switch(subframe->entropy_coding_method.type) {
2654                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2655                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2656                         if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
2657                                 return false;
2658                         break;
2659                 default:
2660                         FLAC__ASSERT(0);
2661         }
2662
2663         /* decode the subframe */
2664         if(do_full_decode) {
2665                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2666                 /*@@@@@@ technically not pessimistic enough, should be more like
2667                 if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
2668                 */
2669                 if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2670                         if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2671                                 if(order <= 8)
2672                                         decoder->private_->local_lpc_restore_signal_16bit_order8(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
2673                                 else
2674                                         decoder->private_->local_lpc_restore_signal_16bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
2675                         }
2676                         else
2677                                 decoder->private_->local_lpc_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
2678                 else
2679                         decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
2680         }
2681
2682         return true;
2683 }
2684
2685 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2686 {
2687         FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2688         FLAC__int32 x, *residual = decoder->private_->residual[channel];
2689         unsigned i;
2690
2691         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2692
2693         subframe->data = residual;
2694
2695         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2696                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2697                         return false; /* read_callback_ sets the state for us */
2698                 residual[i] = x;
2699         }
2700
2701         /* decode the subframe */
2702         if(do_full_decode)
2703                 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2704
2705         return true;
2706 }
2707
2708 FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended)
2709 {
2710         FLAC__uint32 rice_parameter;
2711         int i;
2712         unsigned partition, sample, u;
2713         const unsigned partitions = 1u << partition_order;
2714         const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2715         const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
2716         const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
2717
2718         /* sanity checks */
2719         if(partition_order == 0) {
2720                 if(decoder->private_->frame.header.blocksize < predictor_order) {
2721                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2722                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2723                         return true;
2724                 }
2725         }
2726         else {
2727                 if(partition_samples < predictor_order) {
2728                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2729                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2730                         return true;
2731                 }
2732         }
2733
2734         if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2735                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2736                 return false;
2737         }
2738
2739         sample = 0;
2740         for(partition = 0; partition < partitions; partition++) {
2741                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
2742                         return false; /* read_callback_ sets the state for us */
2743                 partitioned_rice_contents->parameters[partition] = rice_parameter;
2744                 if(rice_parameter < pesc) {
2745                         partitioned_rice_contents->raw_bits[partition] = 0;
2746                         u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2747                         if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter))
2748                                 return false; /* read_callback_ sets the state for us */
2749                         sample += u;
2750                 }
2751                 else {
2752                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
2753                                 return false; /* read_callback_ sets the state for us */
2754                         partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2755                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2756                                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i, rice_parameter))
2757                                         return false; /* read_callback_ sets the state for us */
2758                                 residual[sample] = i;
2759                         }
2760                 }
2761         }
2762
2763         return true;
2764 }
2765
2766 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2767 {
2768         if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
2769                 FLAC__uint32 zero = 0;
2770                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
2771                         return false; /* read_callback_ sets the state for us */
2772                 if(zero != 0) {
2773                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2774                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2775                 }
2776         }
2777         return true;
2778 }
2779
2780 FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
2781 {
2782         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2783
2784         if(
2785 #if FLAC__HAS_OGG
2786                 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2787                 !decoder->private_->is_ogg &&
2788 #endif
2789                 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2790         ) {
2791                 *bytes = 0;
2792                 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2793                 return false;
2794         }
2795         else if(*bytes > 0) {
2796                 /* While seeking, it is possible for our seek to land in the
2797                  * middle of audio data that looks exactly like a frame header
2798                  * from a future version of an encoder.  When that happens, our
2799                  * error callback will get an
2800                  * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
2801                  * unparseable_frame_count.  But there is a remote possibility
2802                  * that it is properly synced at such a "future-codec frame",
2803                  * so to make sure, we wait to see many "unparseable" errors in
2804                  * a row before bailing out.
2805                  */
2806                 if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2807                         decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2808                         return false;
2809                 }
2810                 else {
2811                         const FLAC__StreamDecoderReadStatus status =
2812 #if FLAC__HAS_OGG
2813                                 decoder->private_->is_ogg?
2814                                 read_callback_ogg_aspect_(decoder, buffer, bytes) :
2815 #endif
2816                                 decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
2817                         ;
2818                         if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
2819                                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2820                                 return false;
2821                         }
2822                         else if(*bytes == 0) {
2823                                 if(
2824                                         status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
2825                                         (
2826 #if FLAC__HAS_OGG
2827                                                 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2828                                                 !decoder->private_->is_ogg &&
2829 #endif
2830                                                 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2831                                         )
2832                                 ) {
2833                                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2834                                         return false;
2835                                 }
2836                                 else
2837                                         return true;
2838                         }
2839                         else
2840                                 return true;
2841                 }
2842         }
2843         else {
2844                 /* abort to avoid a deadlock */
2845                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2846                 return false;
2847         }
2848         /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
2849          * for Ogg FLAC.  This is because the ogg decoder aspect can lose sync
2850          * and at the same time hit the end of the stream (for example, seeking
2851          * to a point that is after the beginning of the last Ogg page).  There
2852          * is no way to report an Ogg sync loss through the callbacks (see note
2853          * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
2854          * So to keep the decoder from stopping at this point we gate the call
2855          * to the eof_callback and let the Ogg decoder aspect set the
2856          * end-of-stream state when it is needed.
2857          */
2858 }
2859
2860 #if FLAC__HAS_OGG
2861 FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
2862 {
2863         switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
2864                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
2865                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2866                 /* we don't really have a way to handle lost sync via read
2867                  * callback so we'll let it pass and let the underlying
2868                  * FLAC decoder catch the error
2869                  */
2870                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
2871                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2872                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
2873                         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2874                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
2875                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
2876                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
2877                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
2878                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
2879                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2880                 default:
2881                         FLAC__ASSERT(0);
2882                         /* double protection */
2883                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2884         }
2885 }
2886
2887 FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
2888 {
2889         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
2890
2891         switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
2892                 case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
2893                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
2894                 case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
2895                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
2896                 case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
2897                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2898                 default:
2899                         /* double protection: */
2900                         FLAC__ASSERT(0);
2901                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2902         }
2903 }
2904 #endif
2905
2906 FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2907 {
2908         if(decoder->private_->is_seeking) {
2909                 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
2910                 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
2911                 FLAC__uint64 target_sample = decoder->private_->target_sample;
2912
2913                 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2914
2915 #if FLAC__HAS_OGG
2916                 decoder->private_->got_a_frame = true;
2917 #endif
2918                 decoder->private_->last_frame = *frame; /* save the frame */
2919                 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
2920                         unsigned delta = (unsigned)(target_sample - this_frame_sample);
2921                         /* kick out of seek mode */
2922                         decoder->private_->is_seeking = false;
2923                         /* shift out the samples before target_sample */
2924                         if(delta > 0) {
2925                                 unsigned channel;
2926                                 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
2927                                 for(channel = 0; channel < frame->header.channels; channel++)
2928                                         newbuffer[channel] = buffer[channel] + delta;
2929                                 decoder->private_->last_frame.header.blocksize -= delta;
2930                                 decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
2931                                 /* write the relevant samples */
2932                                 return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
2933                         }
2934                         else {
2935                                 /* write the relevant samples */
2936                                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2937                         }
2938                 }
2939                 else {
2940                         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2941                 }
2942         }
2943         else {
2944                 /*
2945                  * If we never got STREAMINFO, turn off MD5 checking to save
2946                  * cycles since we don't have a sum to compare to anyway
2947                  */
2948                 if(!decoder->private_->has_stream_info)
2949                         decoder->private_->do_md5_checking = false;
2950                 if(decoder->private_->do_md5_checking) {
2951                         if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
2952                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2953                 }
2954                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2955         }
2956 }
2957
2958 void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2959 {
2960         if(!decoder->private_->is_seeking)
2961                 decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
2962         else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
2963                 decoder->private_->unparseable_frame_count++;
2964 }
2965
2966 FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2967 {
2968         FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
2969         FLAC__int64 pos = -1;
2970         int i;
2971         unsigned approx_bytes_per_frame;
2972         FLAC__bool first_seek = true;
2973         const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
2974         const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2975         const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
2976         const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
2977         const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
2978         /* take these from the current frame in case they've changed mid-stream */
2979         unsigned channels = FLAC__stream_decoder_get_channels(decoder);
2980         unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
2981         const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
2982
2983         /* use values from stream info if we didn't decode a frame */
2984         if(channels == 0)
2985                 channels = decoder->private_->stream_info.data.stream_info.channels;
2986         if(bps == 0)
2987                 bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2988
2989         /* we are just guessing here */
2990         if(max_framesize > 0)
2991                 approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
2992         /*
2993          * Check if it's a known fixed-blocksize stream.  Note that though
2994          * the spec doesn't allow zeroes in the STREAMINFO block, we may
2995          * never get a STREAMINFO block when decoding so the value of
2996          * min_blocksize might be zero.
2997          */
2998         else if(min_blocksize == max_blocksize && min_blocksize > 0) {
2999                 /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
3000                 approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
3001         }
3002         else
3003                 approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
3004
3005         /*
3006          * First, we set an upper and lower bound on where in the
3007          * stream we will search.  For now we assume the worst case
3008          * scenario, which is our best guess at the beginning of
3009          * the first frame and end of the stream.
3010          */
3011         lower_bound = first_frame_offset;
3012         lower_bound_sample = 0;
3013         upper_bound = stream_length;
3014         upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
3015
3016         /*
3017          * Now we refine the bounds if we have a seektable with
3018          * suitable points.  Note that according to the spec they
3019          * must be ordered by ascending sample number.
3020          *
3021          * Note: to protect against invalid seek tables we will ignore points
3022          * that have frame_samples==0 or sample_number>=total_samples
3023          */
3024         if(seek_table) {
3025                 FLAC__uint64 new_lower_bound = lower_bound;
3026                 FLAC__uint64 new_upper_bound = upper_bound;
3027                 FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
3028                 FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
3029
3030                 /* find the closest seek point <= target_sample, if it exists */
3031                 for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
3032                         if(
3033                                 seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
3034                                 seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
3035                                 (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
3036                                 seek_table->points[i].sample_number <= target_sample
3037                         )
3038                                 break;
3039                 }
3040                 if(i >= 0) { /* i.e. we found a suitable seek point... */
3041                         new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
3042                         new_lower_bound_sample = seek_table->points[i].sample_number;
3043                 }
3044
3045                 /* find the closest seek point > target_sample, if it exists */
3046                 for(i = 0; i < (int)seek_table->num_points; i++) {
3047                         if(
3048                                 seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
3049                                 seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
3050                                 (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
3051                                 seek_table->points[i].sample_number > target_sample
3052                         )
3053                                 break;
3054                 }
3055                 if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
3056                         new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
3057                         new_upper_bound_sample = seek_table->points[i].sample_number;
3058                 }
3059                 /* final protection against unsorted seek tables; keep original values if bogus */
3060                 if(new_upper_bound >= new_lower_bound) {
3061                         lower_bound = new_lower_bound;
3062                         upper_bound = new_upper_bound;
3063                         lower_bound_sample = new_lower_bound_sample;
3064                         upper_bound_sample = new_upper_bound_sample;
3065                 }
3066         }
3067
3068         FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
3069         /* there are 2 insidious ways that the following equality occurs, which
3070          * we need to fix:
3071          *  1) total_samples is 0 (unknown) and target_sample is 0
3072          *  2) total_samples is 0 (unknown) and target_sample happens to be
3073          *     exactly equal to the last seek point in the seek table; this
3074          *     means there is no seek point above it, and upper_bound_samples
3075          *     remains equal to the estimate (of target_samples) we made above
3076          * in either case it does not hurt to move upper_bound_sample up by 1
3077          */
3078         if(upper_bound_sample == lower_bound_sample)
3079                 upper_bound_sample++;
3080
3081         decoder->private_->target_sample = target_sample;
3082         while(1) {
3083                 /* check if the bounds are still ok */
3084                 if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
3085                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3086                         return false;
3087                 }
3088 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3089 #if defined _MSC_VER || defined __MINGW32__
3090                 /* with VC++ you have to spoon feed it the casting */
3091                 pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(FLAC__int64)(target_sample - lower_bound_sample) / (FLAC__double)(FLAC__int64)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(FLAC__int64)(upper_bound - lower_bound)) - approx_bytes_per_frame;
3092 #else
3093                 pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(target_sample - lower_bound_sample) / (FLAC__double)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(upper_bound - lower_bound)) - approx_bytes_per_frame;
3094 #endif
3095 #else
3096                 /* a little less accurate: */
3097                 if(upper_bound - lower_bound < 0xffffffff)
3098                         pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_sample - lower_bound_sample) * (upper_bound - lower_bound)) / (upper_bound_sample - lower_bound_sample)) - approx_bytes_per_frame;
3099                 else /* @@@ WATCHOUT, ~2TB limit */
3100                         pos = (FLAC__int64)lower_bound + (FLAC__int64)((((target_sample - lower_bound_sample)>>8) * ((upper_bound - lower_bound)>>8)) / ((upper_bound_sample - lower_bound_sample)>>16)) - approx_bytes_per_frame;
3101 #endif
3102                 if(pos >= (FLAC__int64)upper_bound)
3103                         pos = (FLAC__int64)upper_bound - 1;
3104                 if(pos < (FLAC__int64)lower_bound)
3105                         pos = (FLAC__int64)lower_bound;
3106                 if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3107                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3108                         return false;
3109                 }
3110                 if(!FLAC__stream_decoder_flush(decoder)) {
3111                         /* above call sets the state for us */
3112                         return false;
3113                 }
3114                 /* Now we need to get a frame.  First we need to reset our
3115                  * unparseable_frame_count; if we get too many unparseable
3116                  * frames in a row, the read callback will return
3117                  * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
3118                  * FLAC__stream_decoder_process_single() to return false.
3119                  */
3120                 decoder->private_->unparseable_frame_count = 0;
3121                 if(!FLAC__stream_decoder_process_single(decoder)) {
3122                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3123                         return false;
3124                 }
3125                 /* our write callback will change the state when it gets to the target frame */
3126                 /* actually, we could have got_a_frame if our decoder is at FLAC__STREAM_DECODER_END_OF_STREAM so we need to check for that also */
3127 #if 0
3128                 /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
3129                 if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
3130                         break;
3131 #endif
3132                 if(!decoder->private_->is_seeking)
3133                         break;
3134
3135                 FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3136                 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3137
3138                 if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
3139                         if (pos == (FLAC__int64)lower_bound) {
3140                                 /* can't move back any more than the first frame, something is fatally wrong */
3141                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3142                                 return false;
3143                         }
3144                         /* our last move backwards wasn't big enough, try again */
3145                         approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
3146                         continue;       
3147                 }
3148                 /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
3149                 first_seek = false;
3150                 
3151                 /* make sure we are not seeking in corrupted stream */
3152                 if (this_frame_sample < lower_bound_sample) {
3153                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3154                         return false;
3155                 }
3156
3157                 /* we need to narrow the search */
3158                 if(target_sample < this_frame_sample) {
3159                         upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
3160 /*@@@@@@ what will decode position be if at end of stream? */
3161                         if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
3162                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3163                                 return false;
3164                         }
3165                         approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
3166                 }
3167                 else { /* target_sample >= this_frame_sample + this frame's blocksize */
3168                         lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
3169                         if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
3170                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3171                                 return false;
3172                         }
3173                         approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
3174                 }
3175         }
3176
3177         return true;
3178 }
3179
3180 #if FLAC__HAS_OGG
3181 FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
3182 {
3183         FLAC__uint64 left_pos = 0, right_pos = stream_length;
3184         FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
3185         FLAC__uint64 this_frame_sample = 0; /* only initialized to avoid compiler warning */
3186         FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
3187         FLAC__bool did_a_seek;
3188         unsigned iteration = 0;
3189
3190         /* In the first iterations, we will calculate the target byte position 
3191          * by the distance from the target sample to left_sample and
3192          * right_sample (let's call it "proportional search").  After that, we
3193          * will switch to binary search.
3194          */
3195         unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
3196
3197         /* We will switch to a linear search once our current sample is less
3198          * than this number of samples ahead of the target sample
3199          */
3200         static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
3201
3202         /* If the total number of samples is unknown, use a large value, and
3203          * force binary search immediately.
3204          */
3205         if(right_sample == 0) {
3206                 right_sample = (FLAC__uint64)(-1);
3207                 BINARY_SEARCH_AFTER_ITERATION = 0;
3208         }
3209
3210         decoder->private_->target_sample = target_sample;
3211         for( ; ; iteration++) {
3212                 if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
3213                         if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
3214                                 pos = (right_pos + left_pos) / 2;
3215                         }
3216                         else {
3217 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3218 #if defined _MSC_VER || defined __MINGW32__
3219                                 /* with MSVC you have to spoon feed it the casting */
3220                                 pos = (FLAC__uint64)((FLAC__double)(FLAC__int64)(target_sample - left_sample) / (FLAC__double)(FLAC__int64)(right_sample - left_sample) * (FLAC__double)(FLAC__int64)(right_pos - left_pos));
3221 #else
3222                                 pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
3223 #endif
3224 #else
3225                                 /* a little less accurate: */
3226                                 if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
3227                                         pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
3228                                 else /* @@@ WATCHOUT, ~2TB limit */
3229                                         pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
3230 #endif
3231                                 /* @@@ TODO: might want to limit pos to some distance
3232                                  * before EOF, to make sure we land before the last frame,
3233                                  * thereby getting a this_frame_sample and so having a better
3234                                  * estimate.  @@@@@@DELETE:this would also mostly (or totally if we could
3235                                  * be sure to land before the last frame) avoid the
3236                                  * end-of-stream case we have to check later.
3237                                  */
3238                         }
3239
3240                         /* physical seek */
3241                         if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3242                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3243                                 return false;
3244                         }
3245                         if(!FLAC__stream_decoder_flush(decoder)) {
3246                                 /* above call sets the state for us */
3247                                 return false;
3248                         }
3249                         did_a_seek = true;
3250                 }
3251                 else
3252                         did_a_seek = false;
3253
3254                 decoder->private_->got_a_frame = false;
3255                 if(!FLAC__stream_decoder_process_single(decoder)) {
3256                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3257                         return false;
3258                 }
3259                 if(!decoder->private_->got_a_frame) {
3260                         if(did_a_seek) {
3261                                 /* this can happen if we seek to a point after the last frame; we drop
3262                                  * to binary search right away in this case to avoid any wasted
3263                                  * iterations of proportional search.
3264                                  */
3265                                 right_pos = pos;
3266                                 BINARY_SEARCH_AFTER_ITERATION = 0;
3267                         }
3268                         else {
3269                                 /* this can probably only happen if total_samples is unknown and the
3270                                  * target_sample is past the end of the stream
3271                                  */
3272                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3273                                 return false;
3274                         }
3275                 }
3276                 /* our write callback will change the state when it gets to the target frame */
3277                 else if(!decoder->private_->is_seeking/*@@@@@@ && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM*/) {
3278                         break;
3279                 }
3280                 else {
3281                         this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3282                         FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3283
3284                         if (did_a_seek) {
3285                                 if (this_frame_sample <= target_sample) {
3286                                         /* The 'equal' case should not happen, since
3287                                          * FLAC__stream_decoder_process_single()
3288                                          * should recognize that it has hit the
3289                                          * target sample and we would exit through
3290                                          * the 'break' above.
3291                                          */
3292                                         FLAC__ASSERT(this_frame_sample != target_sample);
3293
3294                                         left_sample = this_frame_sample;
3295                                         /* sanity check to avoid infinite loop */
3296                                         if (left_pos == pos) {
3297                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3298                                                 return false;
3299                                         }
3300                                         left_pos = pos;
3301                                 }
3302                                 else if(this_frame_sample > target_sample) {
3303                                         right_sample = this_frame_sample;
3304                                         /* sanity check to avoid infinite loop */
3305                                         if (right_pos == pos) {
3306                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3307                                                 return false;
3308                                         }
3309                                         right_pos = pos;
3310                                 }
3311                         }
3312                 }
3313         }
3314
3315         return true;
3316 }
3317 #endif
3318
3319 FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
3320 {
3321         (void)client_data;
3322
3323         if(*bytes > 0) {
3324                 *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
3325                 if(ferror(decoder->private_->file))
3326                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
3327                 else if(*bytes == 0)
3328                         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
3329                 else
3330                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
3331         }
3332         else
3333                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
3334 }
3335
3336 FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
3337 {
3338         (void)client_data;
3339
3340         if(decoder->private_->file == stdin)
3341                 return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
3342         else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
3343                 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
3344         else
3345                 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
3346 }
3347
3348 FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
3349 {
3350         off_t pos;
3351         (void)client_data;
3352
3353         if(decoder->private_->file == stdin)
3354                 return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
3355         else if((pos = ftello(decoder->private_->file)) < 0)
3356                 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
3357         else {
3358                 *absolute_byte_offset = (FLAC__uint64)pos;
3359                 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
3360         }
3361 }
3362
3363 FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
3364 {
3365         struct stat filestats;
3366         (void)client_data;
3367
3368         if(decoder->private_->file == stdin)
3369                 return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
3370         else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
3371                 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
3372         else {
3373                 *stream_length = (FLAC__uint64)filestats.st_size;
3374                 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
3375         }
3376 }
3377
3378 FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
3379 {
3380         (void)client_data;
3381
3382         return feof(decoder->private_->file)? true : false;
3383 }