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