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