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