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