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