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