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