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