convert C prototypes for functions with no args from () to (void)
[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  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 <= 1200 || 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         struct 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, 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 len;
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, &obj->type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
1843                 return false; /* read_callback_ sets the state for us */
1844
1845         /* read MIME type */
1846         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
1847                 return false; /* read_callback_ sets the state for us */
1848         if(0 == (obj->mime_type = (char*)malloc(len+1))) {
1849                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1850                 return false;
1851         }
1852         if(len > 0) {
1853                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, len))
1854                         return false; /* read_callback_ sets the state for us */
1855         }
1856         obj->mime_type[len] = '\0';
1857
1858         /* read description */
1859         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
1860                 return false; /* read_callback_ sets the state for us */
1861         if(0 == (obj->description = (FLAC__byte*)malloc(len+1))) {
1862                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1863                 return false;
1864         }
1865         if(len > 0) {
1866                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, len))
1867                         return false; /* read_callback_ sets the state for us */
1868         }
1869         obj->description[len] = '\0';
1870
1871         /* read width */
1872         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
1873                 return false; /* read_callback_ sets the state for us */
1874
1875         /* read height */
1876         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
1877                 return false; /* read_callback_ sets the state for us */
1878
1879         /* read depth */
1880         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
1881                 return false; /* read_callback_ sets the state for us */
1882
1883         /* read colors */
1884         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
1885                 return false; /* read_callback_ sets the state for us */
1886
1887         /* read data */
1888         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
1889                 return false; /* read_callback_ sets the state for us */
1890         if(0 == (obj->data = (FLAC__byte*)malloc(obj->data_length))) {
1891                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1892                 return false;
1893         }
1894         if(obj->data_length > 0) {
1895                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
1896                         return false; /* read_callback_ sets the state for us */
1897         }
1898
1899         return true;
1900 }
1901
1902 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1903 {
1904         FLAC__uint32 x;
1905         unsigned i, skip;
1906
1907         /* skip the version and flags bytes */
1908         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
1909                 return false; /* read_callback_ sets the state for us */
1910         /* get the size (in bytes) to skip */
1911         skip = 0;
1912         for(i = 0; i < 4; i++) {
1913                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1914                         return false; /* read_callback_ sets the state for us */
1915                 skip <<= 7;
1916                 skip |= (x & 0x7f);
1917         }
1918         /* skip the rest of the tag */
1919         if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
1920                 return false; /* read_callback_ sets the state for us */
1921         return true;
1922 }
1923
1924 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1925 {
1926         FLAC__uint32 x;
1927         FLAC__bool first = true;
1928
1929         /* If we know the total number of samples in the stream, stop if we've read that many. */
1930         /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1931         if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
1932                 if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
1933                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1934                         return true;
1935                 }
1936         }
1937
1938         /* make sure we're byte aligned */
1939         if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
1940                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
1941                         return false; /* read_callback_ sets the state for us */
1942         }
1943
1944         while(1) {
1945                 if(decoder->private_->cached) {
1946                         x = (FLAC__uint32)decoder->private_->lookahead;
1947                         decoder->private_->cached = false;
1948                 }
1949                 else {
1950                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1951                                 return false; /* read_callback_ sets the state for us */
1952                 }
1953                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1954                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1955                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1956                                 return false; /* read_callback_ sets the state for us */
1957
1958                         /* 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 */
1959                         /* else we have to check if the second byte is the end of a sync code */
1960                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1961                                 decoder->private_->lookahead = (FLAC__byte)x;
1962                                 decoder->private_->cached = true;
1963                         }
1964                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1965                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1966                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1967                                 return true;
1968                         }
1969                 }
1970                 if(first) {
1971                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1972                         first = false;
1973                 }
1974         }
1975
1976         return true;
1977 }
1978
1979 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
1980 {
1981         unsigned channel;
1982         unsigned i;
1983         FLAC__int32 mid, side, left, right;
1984         unsigned frame_crc; /* the one we calculate from the input stream */
1985         FLAC__uint32 x;
1986
1987         *got_a_frame = false;
1988
1989         /* init the CRC */
1990         frame_crc = 0;
1991         frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
1992         frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
1993         FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
1994
1995         if(!read_frame_header_(decoder))
1996                 return false;
1997         if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
1998                 return true;
1999         if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
2000                 return false;
2001         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2002                 /*
2003                  * first figure the correct bits-per-sample of the subframe
2004                  */
2005                 unsigned bps = decoder->private_->frame.header.bits_per_sample;
2006                 switch(decoder->private_->frame.header.channel_assignment) {
2007                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2008                                 /* no adjustment needed */
2009                                 break;
2010                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2011                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2012                                 if(channel == 1)
2013                                         bps++;
2014                                 break;
2015                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2016                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2017                                 if(channel == 0)
2018                                         bps++;
2019                                 break;
2020                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2021                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2022                                 if(channel == 1)
2023                                         bps++;
2024                                 break;
2025                         default:
2026                                 FLAC__ASSERT(0);
2027                 }
2028                 /*
2029                  * now read it
2030                  */
2031                 if(!read_subframe_(decoder, channel, bps, do_full_decode))
2032                         return false;
2033                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2034                         return true;
2035         }
2036         if(!read_zero_padding_(decoder))
2037                 return false;
2038
2039         /*
2040          * Read the frame CRC-16 from the footer and check
2041          */
2042         frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
2043         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
2044                 return false; /* read_callback_ sets the state for us */
2045         if(frame_crc == x) {
2046                 if(do_full_decode) {
2047                         /* Undo any special channel coding */
2048                         switch(decoder->private_->frame.header.channel_assignment) {
2049                                 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2050                                         /* do nothing */
2051                                         break;
2052                                 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2053                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2054                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2055                                                 decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
2056                                         break;
2057                                 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2058                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2059                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2060                                                 decoder->private_->output[0][i] += decoder->private_->output[1][i];
2061                                         break;
2062                                 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2063                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2064                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2065                                                 mid = decoder->private_->output[0][i];
2066                                                 side = decoder->private_->output[1][i];
2067                                                 mid <<= 1;
2068                                                 if(side & 1) /* i.e. if 'side' is odd... */
2069                                                         mid++;
2070                                                 left = mid + side;
2071                                                 right = mid - side;
2072                                                 decoder->private_->output[0][i] = left >> 1;
2073                                                 decoder->private_->output[1][i] = right >> 1;
2074                                         }
2075                                         break;
2076                                 default:
2077                                         FLAC__ASSERT(0);
2078                                         break;
2079                         }
2080                 }
2081         }
2082         else {
2083                 /* Bad frame, emit error and zero the output signal */
2084                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
2085                 if(do_full_decode) {
2086                         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2087                                 memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2088                         }
2089                 }
2090         }
2091
2092         *got_a_frame = true;
2093
2094         /* put the latest values into the public section of the decoder instance */
2095         decoder->protected_->channels = decoder->private_->frame.header.channels;
2096         decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
2097         decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
2098         decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
2099         decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
2100
2101         FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2102         decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
2103
2104         /* write it */
2105         if(do_full_decode) {
2106                 if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
2107                         return false;
2108         }
2109
2110         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2111         return true;
2112 }
2113
2114 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
2115 {
2116         FLAC__uint32 x;
2117         FLAC__uint64 xx;
2118         unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
2119         FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
2120         unsigned raw_header_len;
2121         FLAC__bool is_unparseable = false;
2122         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);
2123         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);
2124
2125         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
2126
2127         /* init the raw header with the saved bits from synchronization */
2128         raw_header[0] = decoder->private_->header_warmup[0];
2129         raw_header[1] = decoder->private_->header_warmup[1];
2130         raw_header_len = 2;
2131
2132         /*
2133          * check to make sure that the reserved bits are 0
2134          */
2135         if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
2136                 is_unparseable = true;
2137         }
2138
2139         /*
2140          * Note that along the way as we read the header, we look for a sync
2141          * code inside.  If we find one it would indicate that our original
2142          * sync was bad since there cannot be a sync code in a valid header.
2143          */
2144
2145         /*
2146          * read in the raw header as bytes so we can CRC it, and parse it on the way
2147          */
2148         for(i = 0; i < 2; i++) {
2149                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2150                         return false; /* read_callback_ sets the state for us */
2151                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
2152                         /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
2153                         decoder->private_->lookahead = (FLAC__byte)x;
2154                         decoder->private_->cached = true;
2155                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2156                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2157                         return true;
2158                 }
2159                 raw_header[raw_header_len++] = (FLAC__byte)x;
2160         }
2161
2162         switch(x = raw_header[2] >> 4) {
2163                 case 0:
2164                         if(is_known_fixed_blocksize_stream)
2165                                 decoder->private_->frame.header.blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2166                         else
2167                                 is_unparseable = true;
2168                         break;
2169                 case 1:
2170                         decoder->private_->frame.header.blocksize = 192;
2171                         break;
2172                 case 2:
2173                 case 3:
2174                 case 4:
2175                 case 5:
2176                         decoder->private_->frame.header.blocksize = 576 << (x-2);
2177                         break;
2178                 case 6:
2179                 case 7:
2180                         blocksize_hint = x;
2181                         break;
2182                 case 8:
2183                 case 9:
2184                 case 10:
2185                 case 11:
2186                 case 12:
2187                 case 13:
2188                 case 14:
2189                 case 15:
2190                         decoder->private_->frame.header.blocksize = 256 << (x-8);
2191                         break;
2192                 default:
2193                         FLAC__ASSERT(0);
2194                         break;
2195         }
2196
2197         switch(x = raw_header[2] & 0x0f) {
2198                 case 0:
2199                         if(decoder->private_->has_stream_info)
2200                                 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
2201                         else
2202                                 is_unparseable = true;
2203                         break;
2204                 case 1:
2205                 case 2:
2206                 case 3:
2207                         is_unparseable = true;
2208                         break;
2209                 case 4:
2210                         decoder->private_->frame.header.sample_rate = 8000;
2211                         break;
2212                 case 5:
2213                         decoder->private_->frame.header.sample_rate = 16000;
2214                         break;
2215                 case 6:
2216                         decoder->private_->frame.header.sample_rate = 22050;
2217                         break;
2218                 case 7:
2219                         decoder->private_->frame.header.sample_rate = 24000;
2220                         break;
2221                 case 8:
2222                         decoder->private_->frame.header.sample_rate = 32000;
2223                         break;
2224                 case 9:
2225                         decoder->private_->frame.header.sample_rate = 44100;
2226                         break;
2227                 case 10:
2228                         decoder->private_->frame.header.sample_rate = 48000;
2229                         break;
2230                 case 11:
2231                         decoder->private_->frame.header.sample_rate = 96000;
2232                         break;
2233                 case 12:
2234                 case 13:
2235                 case 14:
2236                         sample_rate_hint = x;
2237                         break;
2238                 case 15:
2239                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2240                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2241                         return true;
2242                 default:
2243                         FLAC__ASSERT(0);
2244         }
2245
2246         x = (unsigned)(raw_header[3] >> 4);
2247         if(x & 8) {
2248                 decoder->private_->frame.header.channels = 2;
2249                 switch(x & 7) {
2250                         case 0:
2251                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2252                                 break;
2253                         case 1:
2254                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2255                                 break;
2256                         case 2:
2257                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2258                                 break;
2259                         default:
2260                                 is_unparseable = true;
2261                                 break;
2262                 }
2263         }
2264         else {
2265                 decoder->private_->frame.header.channels = (unsigned)x + 1;
2266                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2267         }
2268
2269         switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2270                 case 0:
2271                         if(decoder->private_->has_stream_info)
2272                                 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2273                         else
2274                                 is_unparseable = true;
2275                         break;
2276                 case 1:
2277                         decoder->private_->frame.header.bits_per_sample = 8;
2278                         break;
2279                 case 2:
2280                         decoder->private_->frame.header.bits_per_sample = 12;
2281                         break;
2282                 case 4:
2283                         decoder->private_->frame.header.bits_per_sample = 16;
2284                         break;
2285                 case 5:
2286                         decoder->private_->frame.header.bits_per_sample = 20;
2287                         break;
2288                 case 6:
2289                         decoder->private_->frame.header.bits_per_sample = 24;
2290                         break;
2291                 case 3:
2292                 case 7:
2293                         is_unparseable = true;
2294                         break;
2295                 default:
2296                         FLAC__ASSERT(0);
2297                         break;
2298         }
2299
2300         if(raw_header[3] & 0x01) { /* this should be a zero padding bit */
2301                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2302                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2303                 return true;
2304         }
2305
2306         /*
2307          * Now we get to the regrettable consequences of not knowing for sure
2308          * whether we got a frame number or a sample number.  There are no
2309          * encoders that do variable-blocksize encoding so unless we know from
2310          * the STREAMINFO that it is variable-blocksize we will assume it is
2311          * fixed-blocksize.  The trouble comes when we have no STREAMINFO; again
2312          * we will guess that is fixed-blocksize.  Where this can go wrong: 1) a
2313          * variable-blocksize stream with no STREAMINFO; 2) a fixed-blocksize
2314          * stream that was edited such that one or more frames before or
2315          * including this one do not have the same number of samples as the
2316          * STREAMINFO's min and max blocksize.
2317          */
2318         if(is_known_variable_blocksize_stream) {
2319                 if(blocksize_hint) {
2320                         if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
2321                                 return false; /* read_callback_ sets the state for us */
2322                         if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
2323                                 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2324                                 decoder->private_->cached = true;
2325                                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2326                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2327                                 return true;
2328                         }
2329                         decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2330                         decoder->private_->frame.header.number.sample_number = xx;
2331                 }
2332                 else
2333                         is_unparseable = true;
2334         }
2335         else {
2336                 if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
2337                         return false; /* read_callback_ sets the state for us */
2338                 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
2339                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2340                         decoder->private_->cached = true;
2341                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2342                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2343                         return true;
2344                 }
2345                 decoder->private_->last_frame_number = x;
2346                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2347                 if(decoder->private_->has_stream_info) {
2348                         FLAC__ASSERT(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize);
2349                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
2350                         decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2351                 }
2352                 else if(blocksize_hint) {
2353                         if(decoder->private_->last_block_size)
2354                                 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->last_block_size * (FLAC__uint64)x;
2355                         else
2356                                 is_unparseable = true;
2357                 }
2358                 else {
2359                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
2360                         decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2361                 }
2362         }
2363
2364         if(blocksize_hint) {
2365                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2366                         return false; /* read_callback_ sets the state for us */
2367                 raw_header[raw_header_len++] = (FLAC__byte)x;
2368                 if(blocksize_hint == 7) {
2369                         FLAC__uint32 _x;
2370                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2371                                 return false; /* read_callback_ sets the state for us */
2372                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2373                         x = (x << 8) | _x;
2374                 }
2375                 decoder->private_->frame.header.blocksize = x+1;
2376         }
2377
2378         if(sample_rate_hint) {
2379                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2380                         return false; /* read_callback_ sets the state for us */
2381                 raw_header[raw_header_len++] = (FLAC__byte)x;
2382                 if(sample_rate_hint != 12) {
2383                         FLAC__uint32 _x;
2384                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2385                                 return false; /* read_callback_ sets the state for us */
2386                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2387                         x = (x << 8) | _x;
2388                 }
2389                 if(sample_rate_hint == 12)
2390                         decoder->private_->frame.header.sample_rate = x*1000;
2391                 else if(sample_rate_hint == 13)
2392                         decoder->private_->frame.header.sample_rate = x;
2393                 else
2394                         decoder->private_->frame.header.sample_rate = x*10;
2395         }
2396
2397         /* read the CRC-8 byte */
2398         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2399                 return false; /* read_callback_ sets the state for us */
2400         crc8 = (FLAC__byte)x;
2401
2402         if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
2403                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2404                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2405                 return true;
2406         }
2407
2408         if(is_unparseable) {
2409                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2410                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2411                 return true;
2412         }
2413
2414         return true;
2415 }
2416
2417 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2418 {
2419         FLAC__uint32 x;
2420         FLAC__bool wasted_bits;
2421         unsigned i;
2422
2423         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
2424                 return false; /* read_callback_ sets the state for us */
2425
2426         wasted_bits = (x & 1);
2427         x &= 0xfe;
2428
2429         if(wasted_bits) {
2430                 unsigned u;
2431                 if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
2432                         return false; /* read_callback_ sets the state for us */
2433                 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
2434                 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
2435         }
2436         else
2437                 decoder->private_->frame.subframes[channel].wasted_bits = 0;
2438
2439         /*
2440          * Lots of magic numbers here
2441          */
2442         if(x & 0x80) {
2443                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2444                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2445                 return true;
2446         }
2447         else if(x == 0) {
2448                 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2449                         return false;
2450         }
2451         else if(x == 2) {
2452                 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2453                         return false;
2454         }
2455         else if(x < 16) {
2456                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2457                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2458                 return true;
2459         }
2460         else if(x <= 24) {
2461                 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2462                         return false;
2463                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2464                         return true;
2465         }
2466         else if(x < 64) {
2467                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2468                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2469                 return true;
2470         }
2471         else {
2472                 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2473                         return false;
2474                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2475                         return true;
2476         }
2477
2478         if(wasted_bits && do_full_decode) {
2479                 x = decoder->private_->frame.subframes[channel].wasted_bits;
2480                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2481                         decoder->private_->output[channel][i] <<= x;
2482         }
2483
2484         return true;
2485 }
2486
2487 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2488 {
2489         FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2490         FLAC__int32 x;
2491         unsigned i;
2492         FLAC__int32 *output = decoder->private_->output[channel];
2493
2494         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2495
2496         if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2497                 return false; /* read_callback_ sets the state for us */
2498
2499         subframe->value = x;
2500
2501         /* decode the subframe */
2502         if(do_full_decode) {
2503                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2504                         output[i] = x;
2505         }
2506
2507         return true;
2508 }
2509
2510 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2511 {
2512         FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2513         FLAC__int32 i32;
2514         FLAC__uint32 u32;
2515         unsigned u;
2516
2517         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2518
2519         subframe->residual = decoder->private_->residual[channel];
2520         subframe->order = order;
2521
2522         /* read warm-up samples */
2523         for(u = 0; u < order; u++) {
2524                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2525                         return false; /* read_callback_ sets the state for us */
2526                 subframe->warmup[u] = i32;
2527         }
2528
2529         /* read entropy coding method info */
2530         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2531                 return false; /* read_callback_ sets the state for us */
2532         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2533         switch(subframe->entropy_coding_method.type) {
2534                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2535                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2536                                 return false; /* read_callback_ sets the state for us */
2537                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2538                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2539                         break;
2540                 default:
2541                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2542                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2543                         return true;
2544         }
2545
2546         /* read residual */
2547         switch(subframe->entropy_coding_method.type) {
2548                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2549                         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]))
2550                                 return false;
2551                         break;
2552                 default:
2553                         FLAC__ASSERT(0);
2554         }
2555
2556         /* decode the subframe */
2557         if(do_full_decode) {
2558                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2559                 FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
2560         }
2561
2562         return true;
2563 }
2564
2565 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2566 {
2567         FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2568         FLAC__int32 i32;
2569         FLAC__uint32 u32;
2570         unsigned u;
2571
2572         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2573
2574         subframe->residual = decoder->private_->residual[channel];
2575         subframe->order = order;
2576
2577         /* read warm-up samples */
2578         for(u = 0; u < order; u++) {
2579                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2580                         return false; /* read_callback_ sets the state for us */
2581                 subframe->warmup[u] = i32;
2582         }
2583
2584         /* read qlp coeff precision */
2585         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
2586                 return false; /* read_callback_ sets the state for us */
2587         if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
2588                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2589                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2590                 return true;
2591         }
2592         subframe->qlp_coeff_precision = u32+1;
2593
2594         /* read qlp shift */
2595         if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
2596                 return false; /* read_callback_ sets the state for us */
2597         subframe->quantization_level = i32;
2598
2599         /* read quantized lp coefficiencts */
2600         for(u = 0; u < order; u++) {
2601                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
2602                         return false; /* read_callback_ sets the state for us */
2603                 subframe->qlp_coeff[u] = i32;
2604         }
2605
2606         /* read entropy coding method info */
2607         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2608                 return false; /* read_callback_ sets the state for us */
2609         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2610         switch(subframe->entropy_coding_method.type) {
2611                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2612                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2613                                 return false; /* read_callback_ sets the state for us */
2614                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2615                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2616                         break;
2617                 default:
2618                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2619                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2620                         return true;
2621         }
2622
2623         /* read residual */
2624         switch(subframe->entropy_coding_method.type) {
2625                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2626                         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]))
2627                                 return false;
2628                         break;
2629                 default:
2630                         FLAC__ASSERT(0);
2631         }
2632
2633         /* decode the subframe */
2634         if(do_full_decode) {
2635                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2636                 if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2637                         if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2638                                 if(order <= 8)
2639                                         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);
2640                                 else
2641                                         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);
2642                         }
2643                         else
2644                                 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);
2645                 else
2646                         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);
2647         }
2648
2649         return true;
2650 }
2651
2652 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2653 {
2654         FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2655         FLAC__int32 x, *residual = decoder->private_->residual[channel];
2656         unsigned i;
2657
2658         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2659
2660         subframe->data = residual;
2661
2662         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2663                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2664                         return false; /* read_callback_ sets the state for us */
2665                 residual[i] = x;
2666         }
2667
2668         /* decode the subframe */
2669         if(do_full_decode)
2670                 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2671
2672         return true;
2673 }
2674
2675 FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual)
2676 {
2677         FLAC__uint32 rice_parameter;
2678         int i;
2679         unsigned partition, sample, u;
2680         const unsigned partitions = 1u << partition_order;
2681         const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2682
2683         /* sanity checks */
2684         if(partition_order == 0) {
2685                 if(decoder->private_->frame.header.blocksize < predictor_order) {
2686                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2687                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2688                         return true;
2689                 }
2690         }
2691         else {
2692                 if(partition_samples < predictor_order) {
2693                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2694                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2695                         return true;
2696                 }
2697         }
2698
2699         if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2700                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2701                 return false;
2702         }
2703
2704         sample = 0;
2705         for(partition = 0; partition < partitions; partition++) {
2706                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN))
2707                         return false; /* read_callback_ sets the state for us */
2708                 partitioned_rice_contents->parameters[partition] = rice_parameter;
2709                 if(rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2710                         u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2711                         if(!FLAC__bitreader_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter))
2712                                 return false; /* read_callback_ sets the state for us */
2713                         sample += u;
2714                 }
2715                 else {
2716                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
2717                                 return false; /* read_callback_ sets the state for us */
2718                         partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2719                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2720                                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i, rice_parameter))
2721                                         return false; /* read_callback_ sets the state for us */
2722                                 residual[sample] = i;
2723                         }
2724                 }
2725         }
2726
2727         return true;
2728 }
2729
2730 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2731 {
2732         if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
2733                 FLAC__uint32 zero = 0;
2734                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
2735                         return false; /* read_callback_ sets the state for us */
2736                 if(zero != 0) {
2737                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2738                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2739                 }
2740         }
2741         return true;
2742 }
2743
2744 FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
2745 {
2746         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2747
2748         if(
2749 #if FLAC__HAS_OGG
2750                 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2751                 !decoder->private_->is_ogg &&
2752 #endif
2753                 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2754         ) {
2755                 *bytes = 0;
2756                 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2757                 return false;
2758         }
2759         else if(*bytes > 0) {
2760                 /* While seeking, it is possible for our seek to land in the
2761                  * middle of audio data that looks exactly like a frame header
2762                  * from a future version of an encoder.  When that happens, our
2763                  * error callback will get an
2764                  * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
2765                  * unparseable_frame_count.  But there is a remote possibility
2766                  * that it is properly synced at such a "future-codec frame",
2767                  * so to make sure, we wait to see many "unparseable" errors in
2768                  * a row before bailing out.
2769                  */
2770                 if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2771                         decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2772                         return false;
2773                 }
2774                 else {
2775                         const FLAC__StreamDecoderReadStatus status =
2776 #if FLAC__HAS_OGG
2777                                 decoder->private_->is_ogg?
2778                                 read_callback_ogg_aspect_(decoder, buffer, bytes) :
2779 #endif
2780                                 decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
2781                         ;
2782                         if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
2783                                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2784                                 return false;
2785                         }
2786                         else if(*bytes == 0) {
2787                                 if(
2788                                         status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
2789                                         (
2790 #if FLAC__HAS_OGG
2791                                                 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2792                                                 !decoder->private_->is_ogg &&
2793 #endif
2794                                                 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2795                                         )
2796                                 ) {
2797                                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2798                                         return false;
2799                                 }
2800                                 else
2801                                         return true;
2802                         }
2803                         else
2804                                 return true;
2805                 }
2806         }
2807         else {
2808                 /* abort to avoid a deadlock */
2809                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2810                 return false;
2811         }
2812         /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
2813          * for Ogg FLAC.  This is because the ogg decoder aspect can lose sync
2814          * and at the same time hit the end of the stream (for example, seeking
2815          * to a point that is after the beginning of the last Ogg page).  There
2816          * is no way to report an Ogg sync loss through the callbacks (see note
2817          * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
2818          * So to keep the decoder from stopping at this point we gate the call
2819          * to the eof_callback and let the Ogg decoder aspect set the
2820          * end-of-stream state when it is needed.
2821          */
2822 }
2823
2824 #if FLAC__HAS_OGG
2825 FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
2826 {
2827         switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
2828                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
2829                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2830                 /* we don't really have a way to handle lost sync via read
2831                  * callback so we'll let it pass and let the underlying
2832                  * FLAC decoder catch the error
2833                  */
2834                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
2835                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2836                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
2837                         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2838                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
2839                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
2840                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
2841                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
2842                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
2843                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2844                 default:
2845                         FLAC__ASSERT(0);
2846                         /* double protection */
2847                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2848         }
2849 }
2850
2851 FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
2852 {
2853         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
2854
2855         switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
2856                 case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
2857                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
2858                 case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
2859                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
2860                 case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
2861                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2862                 default:
2863                         /* double protection: */
2864                         FLAC__ASSERT(0);
2865                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2866         }
2867 }
2868 #endif
2869
2870 FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2871 {
2872         if(decoder->private_->is_seeking) {
2873                 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
2874                 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
2875                 FLAC__uint64 target_sample = decoder->private_->target_sample;
2876
2877                 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2878
2879 #if FLAC__HAS_OGG
2880                 decoder->private_->got_a_frame = true;
2881 #endif
2882                 decoder->private_->last_frame = *frame; /* save the frame */
2883                 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
2884                         unsigned delta = (unsigned)(target_sample - this_frame_sample);
2885                         /* kick out of seek mode */
2886                         decoder->private_->is_seeking = false;
2887                         /* shift out the samples before target_sample */
2888                         if(delta > 0) {
2889                                 unsigned channel;
2890                                 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
2891                                 for(channel = 0; channel < frame->header.channels; channel++)
2892                                         newbuffer[channel] = buffer[channel] + delta;
2893                                 decoder->private_->last_frame.header.blocksize -= delta;
2894                                 decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
2895                                 /* write the relevant samples */
2896                                 return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
2897                         }
2898                         else {
2899                                 /* write the relevant samples */
2900                                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2901                         }
2902                 }
2903                 else {
2904                         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2905                 }
2906         }
2907         else {
2908                 /*
2909                  * If we never got STREAMINFO, turn off MD5 checking to save
2910                  * cycles since we don't have a sum to compare to anyway
2911                  */
2912                 if(!decoder->private_->has_stream_info)
2913                         decoder->private_->do_md5_checking = false;
2914                 if(decoder->private_->do_md5_checking) {
2915                         if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
2916                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2917                 }
2918                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2919         }
2920 }
2921
2922 void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2923 {
2924         if(!decoder->private_->is_seeking)
2925                 decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
2926         else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
2927                 decoder->private_->unparseable_frame_count++;
2928 }
2929
2930 FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2931 {
2932         FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
2933         FLAC__int64 pos = -1;
2934         int i;
2935         unsigned approx_bytes_per_frame;
2936         FLAC__bool first_seek = true;
2937         const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
2938         const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2939         const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
2940         const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
2941         const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
2942         /* take these from the current frame in case they've changed mid-stream */
2943         unsigned channels = FLAC__stream_decoder_get_channels(decoder);
2944         unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
2945         const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
2946
2947         /* use values from stream info if we didn't decode a frame */
2948         if(channels == 0)
2949                 channels = decoder->private_->stream_info.data.stream_info.channels;
2950         if(bps == 0)
2951                 bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2952
2953         /* we are just guessing here */
2954         if(max_framesize > 0)
2955                 approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
2956
2957         /*
2958          * Check if it's a known fixed-blocksize stream.  Note that though
2959          * the spec doesn't allow zeroes in the STREAMINFO block, we may
2960          * never get a STREAMINFO block when decoding so the value of
2961          * min_blocksize might be zero.
2962          */
2963         else if(min_blocksize == max_blocksize && min_blocksize > 0) {
2964                 /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
2965                 approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
2966         }
2967         else
2968                 approx_bytes_per_frame = 4608 * channels * bps/8 + 64;
2969
2970         /*
2971          * First, we set an upper and lower bound on where in the
2972          * stream we will search.  For now we assume the worst case
2973          * scenario, which is our best guess at the beginning of
2974          * the first frame and end of the stream.
2975          */
2976         lower_bound = first_frame_offset;
2977         lower_bound_sample = 0;
2978         upper_bound = stream_length;
2979         upper_bound_sample = total_samples > 0 ? total_samples : target_sample;
2980         if(upper_bound_sample == 0)
2981                 upper_bound_sample = 1;
2982
2983         /*
2984          * Now we refine the bounds if we have a seektable with
2985          * suitable points.  Note that according to the spec they
2986          * must be ordered by ascending sample number.
2987          */
2988         if(seek_table) {
2989                 /* find the closest seek point <= target_sample, if it exists */
2990                 for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
2991                         if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number <= target_sample)
2992                                 break;
2993                 }
2994                 if(i >= 0) { /* i.e. we found a suitable seek point... */
2995                         lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
2996                         lower_bound_sample = seek_table->points[i].sample_number;
2997                 }
2998
2999                 /* find the closest seek point > target_sample, if it exists */
3000                 for(i = 0; i < (int)seek_table->num_points; i++) {
3001                         if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number > target_sample)
3002                                 break;
3003                 }
3004                 if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
3005                         upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
3006                         upper_bound_sample = seek_table->points[i].sample_number;
3007                 }
3008         }
3009
3010         decoder->private_->target_sample = target_sample;
3011         while(1) {
3012                 /* check if the bounds are still ok */
3013                 if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
3014                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3015                         return false;
3016                 }
3017 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3018 #if defined _MSC_VER || defined __MINGW32__
3019                 /* with VC++ you have to spoon feed it the casting */
3020                 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;
3021 #else
3022                 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;
3023 #endif
3024 #else
3025                 /* a little less accurate: */
3026                 if(upper_bound - lower_bound < 0xffffffff)
3027                         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;
3028                 else /* @@@ WATCHOUT, ~2TB limit */
3029                         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;
3030 #endif
3031                 if(pos >= (FLAC__int64)upper_bound)
3032                         pos = (FLAC__int64)upper_bound - 1;
3033                 if(pos < (FLAC__int64)lower_bound)
3034                         pos = (FLAC__int64)lower_bound;
3035                 if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3036                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3037                         return false;
3038                 }
3039                 if(!FLAC__stream_decoder_flush(decoder)) {
3040                         /* above call sets the state for us */
3041                         return false;
3042                 }
3043                 /* Now we need to get a frame.  First we need to reset our
3044                  * unparseable_frame_count; if we get too many unparseable
3045                  * frames in a row, the read callback will return
3046                  * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
3047                  * FLAC__stream_decoder_process_single() to return false.
3048                  */
3049                 decoder->private_->unparseable_frame_count = 0;
3050                 if(!FLAC__stream_decoder_process_single(decoder)) {
3051                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3052                         return false;
3053                 }
3054                 /* our write callback will change the state when it gets to the target frame */
3055                 /* 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 */
3056 #if 0
3057                 /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
3058                 if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
3059                         break;
3060 #endif
3061                 if(!decoder->private_->is_seeking) {
3062                         break;
3063                 }
3064                 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3065
3066                 if (!decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
3067                         if (pos == (FLAC__int64)lower_bound) {
3068                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3069                                 return false;
3070                         }
3071                         /* our last move backwards wasn't big enough, try again */
3072                         approx_bytes_per_frame *= 2;
3073                         continue;       
3074                 }
3075                 /* allow one seek over upper bound, required for streams with unknown total_samples */
3076                 first_seek = false;
3077                 
3078                 /* make sure we are not seeking in corrupted stream */
3079                 if (this_frame_sample < lower_bound_sample) {
3080                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3081                         return false;
3082                 }
3083
3084                 FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3085
3086                 /* we need to narrow the search */
3087                 if(target_sample < this_frame_sample) {
3088                         upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
3089                         if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
3090                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3091                                 return false;
3092                         }
3093                         approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
3094                 }
3095                 else {
3096                         /* target_sample >= this_frame_sample + this frame's blocksize */
3097
3098                         lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
3099                         if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
3100                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3101                                 return false;
3102                         }
3103                         approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
3104                 }
3105         }
3106
3107         return true;
3108 }
3109
3110 #if FLAC__HAS_OGG
3111 FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
3112 {
3113         FLAC__uint64 left_pos = 0, right_pos = stream_length;
3114         FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
3115         FLAC__uint64 this_frame_sample = 0; /* only initialized to avoid compiler warning */
3116         FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
3117         FLAC__bool did_a_seek;
3118         unsigned iteration = 0;
3119
3120         /* In the first iterations, we will calculate the target byte position 
3121          * by the distance from the target sample to left_sample and
3122          * right_sample (let's call it "proportional search").  After that, we
3123          * will switch to binary search.
3124          */
3125         unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
3126
3127         /* We will switch to a linear search once our current sample is less
3128          * than this number of samples ahead of the target sample
3129          */
3130         static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
3131
3132         /* If the total number of samples is unknown, use a large value, and
3133          * force binary search immediately.
3134          */
3135         if(right_sample == 0) {
3136                 right_sample = (FLAC__uint64)(-1);
3137                 BINARY_SEARCH_AFTER_ITERATION = 0;
3138         }
3139
3140         decoder->private_->target_sample = target_sample;
3141         for( ; ; iteration++) {
3142                 if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
3143                         if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
3144                                 pos = (right_pos + left_pos) / 2;
3145                         }
3146                         else {
3147 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3148 #if defined _MSC_VER || defined __MINGW32__
3149                                 /* with MSVC you have to spoon feed it the casting */
3150                                 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));
3151 #else
3152                                 pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
3153 #endif
3154 #else
3155                                 /* a little less accurate: */
3156                                 if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
3157                                         pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
3158                                 else /* @@@ WATCHOUT, ~2TB limit */
3159                                         pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
3160 #endif
3161                                 /* @@@ TODO: might want to limit pos to some distance
3162                                  * before EOF, to make sure we land before the last frame,
3163                                  * thereby getting a this_frame_sample and so having a better
3164                                  * estimate.  @@@@@@DELETE:this would also mostly (or totally if we could
3165                                  * be sure to land before the last frame) avoid the
3166                                  * end-of-stream case we have to check later.
3167                                  */
3168                         }
3169
3170                         /* physical seek */
3171                         if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3172                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3173                                 return false;
3174                         }
3175                         if(!FLAC__stream_decoder_flush(decoder)) {
3176                                 /* above call sets the state for us */
3177                                 return false;
3178                         }
3179                         did_a_seek = true;
3180                 }
3181                 else
3182                         did_a_seek = false;
3183
3184                 decoder->private_->got_a_frame = false;
3185                 if(!FLAC__stream_decoder_process_single(decoder)) {
3186                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3187                         return false;
3188                 }
3189                 if(!decoder->private_->got_a_frame) {
3190                         if(did_a_seek) {
3191                                 /* this can happen if we seek to a point after the last frame; we drop
3192                                  * to binary search right away in this case to avoid any wasted
3193                                  * iterations of proportional search.
3194                                  */
3195                                 right_pos = pos;
3196                                 BINARY_SEARCH_AFTER_ITERATION = 0;
3197                         }
3198                         else {
3199                                 /* this can probably only happen if total_samples is unknown and the
3200                                  * target_sample is past the end of the stream
3201                                  */
3202                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3203                                 return false;
3204                         }
3205                 }
3206                 /* our write callback will change the state when it gets to the target frame */
3207                 else if(!decoder->private_->is_seeking/*@@@@@@ && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM*/) {
3208                         break;
3209                 }
3210                 else {
3211                         this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3212                         FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3213
3214                         if (did_a_seek) {
3215                                 if (this_frame_sample <= target_sample) {
3216                                         /* The 'equal' case should not happen, since
3217                                          * FLAC__stream_decoder_process_single()
3218                                          * should recognize that it has hit the
3219                                          * target sample and we would exit through
3220                                          * the 'break' above.
3221                                          */
3222                                         FLAC__ASSERT(this_frame_sample != target_sample);
3223
3224                                         left_sample = this_frame_sample;
3225                                         /* sanity check to avoid infinite loop */
3226                                         if (left_pos == pos) {
3227                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3228                                                 return false;
3229                                         }
3230                                         left_pos = pos;
3231                                 }
3232                                 else if(this_frame_sample > target_sample) {
3233                                         right_sample = this_frame_sample;
3234                                         /* sanity check to avoid infinite loop */
3235                                         if (right_pos == pos) {
3236                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3237                                                 return false;
3238                                         }
3239                                         right_pos = pos;
3240                                 }
3241                         }
3242                 }
3243         }
3244
3245         return true;
3246 }
3247 #endif
3248
3249 FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
3250 {
3251         (void)client_data;
3252
3253         if(*bytes > 0) {
3254                 *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
3255                 if(ferror(decoder->private_->file))
3256                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
3257                 else if(*bytes == 0)
3258                         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
3259                 else
3260                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
3261         }
3262         else
3263                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
3264 }
3265
3266 FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
3267 {
3268         (void)client_data;
3269
3270         if(decoder->private_->file == stdin)
3271                 return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
3272         else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
3273                 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
3274         else
3275                 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
3276 }
3277
3278 FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
3279 {
3280         off_t pos;
3281         (void)client_data;
3282
3283         if(decoder->private_->file == stdin)
3284                 return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
3285         else if((pos = ftello(decoder->private_->file)) < 0)
3286                 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
3287         else {
3288                 *absolute_byte_offset = (FLAC__uint64)pos;
3289                 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
3290         }
3291 }
3292
3293 FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
3294 {
3295         struct stat filestats;
3296         (void)client_data;
3297
3298         if(decoder->private_->file == stdin)
3299                 return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
3300         else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
3301                 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
3302         else {
3303                 *stream_length = (FLAC__uint64)filestats.st_size;
3304                 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
3305         }
3306 }
3307
3308 FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
3309 {
3310         (void)client_data;
3311
3312         return feof(decoder->private_->file)? true : false;
3313 }