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