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