fixes for MSVC6
[platform/upstream/flac.git] / src / libFLAC / stream_decoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006  Josh Coalson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * - Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
11  * - Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * - Neither the name of the Xiph.org Foundation nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #if HAVE_CONFIG_H
33 #  include <config.h>
34 #endif
35
36 #if defined _MSC_VER || defined __MINGW32__
37 #include <io.h> /* for _setmode() */
38 #include <fcntl.h> /* for _O_BINARY */
39 #endif
40 #if defined __CYGWIN__ || defined __EMX__
41 #include <io.h> /* for setmode(), O_BINARY */
42 #include <fcntl.h> /* for _O_BINARY */
43 #endif
44 #include <stdio.h>
45 #include <stdlib.h> /* for malloc() */
46 #include <string.h> /* for memset/memcpy() */
47 #include <sys/stat.h> /* for stat() */
48 #include <sys/types.h> /* for off_t */
49 #if defined _MSC_VER || defined __MINGW32__
50 #if _MSC_VER <= 1200 /* @@@ [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/bitbuffer.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_();
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 #ifdef 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 #ifdef 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 #ifdef 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__BitBuffer *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 #ifdef 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()
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__bitbuffer_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__bitbuffer_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         FLAC__stream_decoder_finish(decoder);
349
350         if(0 != decoder->private_->metadata_filter_ids)
351                 free(decoder->private_->metadata_filter_ids);
352
353         FLAC__bitbuffer_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 #ifndef 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 #ifdef 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__bitbuffer_init(decoder->private_->input)) {
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__bitbuffer_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 #ifdef 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 #ifdef 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 #ifdef 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         FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
943         *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
944         return true;
945 }
946
947 FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
948 {
949         FLAC__ASSERT(0 != decoder);
950         FLAC__ASSERT(0 != decoder->private_);
951         FLAC__ASSERT(0 != decoder->protected_);
952
953         decoder->private_->samples_decoded = 0;
954         decoder->private_->do_md5_checking = false;
955
956 #ifdef FLAC__HAS_OGG
957         if(decoder->private_->is_ogg)
958                 FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
959 #endif
960
961         if(!FLAC__bitbuffer_clear(decoder->private_->input)) {
962                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
963                 return false;
964         }
965         decoder->private_->last_frame_number = 0;
966         decoder->private_->last_block_size = 0;
967         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
968
969         return true;
970 }
971
972 FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
973 {
974         FLAC__ASSERT(0 != decoder);
975         FLAC__ASSERT(0 != decoder->private_);
976         FLAC__ASSERT(0 != decoder->protected_);
977
978         if(!FLAC__stream_decoder_flush(decoder)) {
979                 /* above call sets the state for us */
980                 return false;
981         }
982
983 #ifdef FLAC__HAS_OGG
984         /*@@@ could go in !internal_reset_hack block below */
985         if(decoder->private_->is_ogg)
986                 FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
987 #endif
988
989         /* Rewind if necessary.  If FLAC__stream_decoder_init() is calling us,
990          * (internal_reset_hack) don't try to rewind since we are already at
991          * the beginning of the stream and don't want to fail if the input is
992          * not seekable.
993          */
994         if(!decoder->private_->internal_reset_hack) {
995                 if(decoder->private_->file == stdin)
996                         return false; /* can't rewind stdin, reset fails */
997                 if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
998                         return false; /* seekable and seek fails, reset fails */
999         }
1000         else
1001                 decoder->private_->internal_reset_hack = false;
1002
1003         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
1004
1005         decoder->private_->has_stream_info = false;
1006         if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
1007                 free(decoder->private_->seek_table.data.seek_table.points);
1008                 decoder->private_->seek_table.data.seek_table.points = 0;
1009                 decoder->private_->has_seek_table = false;
1010         }
1011         decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
1012
1013         /* We initialize the FLAC__MD5Context even though we may never use it.  This
1014          * is because md5 checking may be turned on to start and then turned off if
1015          * a seek occurs.  So we init the context here and finalize it in
1016          * FLAC__seekable_stream_decoder_finish() to make sure things are always
1017          * cleaned up properly.
1018          */
1019         FLAC__MD5Init(&decoder->private_->md5context);
1020
1021         decoder->private_->first_frame_offset = 0;
1022         decoder->private_->unparseable_frame_count = 0;
1023
1024         return true;
1025 }
1026
1027 FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
1028 {
1029         FLAC__bool got_a_frame;
1030         FLAC__ASSERT(0 != decoder);
1031         FLAC__ASSERT(0 != decoder->protected_);
1032
1033         while(1) {
1034                 switch(decoder->protected_->state) {
1035                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1036                                 if(!find_metadata_(decoder))
1037                                         return false; /* above function sets the status for us */
1038                                 break;
1039                         case FLAC__STREAM_DECODER_READ_METADATA:
1040                                 if(!read_metadata_(decoder))
1041                                         return false; /* above function sets the status for us */
1042                                 else
1043                                         return true;
1044                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1045                                 if(!frame_sync_(decoder))
1046                                         return true; /* above function sets the status for us */
1047                                 break;
1048                         case FLAC__STREAM_DECODER_READ_FRAME:
1049                                 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
1050                                         return false; /* above function sets the status for us */
1051                                 if(got_a_frame)
1052                                         return true; /* above function sets the status for us */
1053                                 break;
1054                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1055                         case FLAC__STREAM_DECODER_ABORTED:
1056                                 return true;
1057                         default:
1058                                 FLAC__ASSERT(0);
1059                                 return false;
1060                 }
1061         }
1062 }
1063
1064 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
1065 {
1066         FLAC__ASSERT(0 != decoder);
1067         FLAC__ASSERT(0 != decoder->protected_);
1068
1069         while(1) {
1070                 switch(decoder->protected_->state) {
1071                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1072                                 if(!find_metadata_(decoder))
1073                                         return false; /* above function sets the status for us */
1074                                 break;
1075                         case FLAC__STREAM_DECODER_READ_METADATA:
1076                                 if(!read_metadata_(decoder))
1077                                         return false; /* above function sets the status for us */
1078                                 break;
1079                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1080                         case FLAC__STREAM_DECODER_READ_FRAME:
1081                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1082                         case FLAC__STREAM_DECODER_ABORTED:
1083                                 return true;
1084                         default:
1085                                 FLAC__ASSERT(0);
1086                                 return false;
1087                 }
1088         }
1089 }
1090
1091 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
1092 {
1093         FLAC__bool dummy;
1094         FLAC__ASSERT(0 != decoder);
1095         FLAC__ASSERT(0 != decoder->protected_);
1096
1097         while(1) {
1098                 switch(decoder->protected_->state) {
1099                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1100                                 if(!find_metadata_(decoder))
1101                                         return false; /* above function sets the status for us */
1102                                 break;
1103                         case FLAC__STREAM_DECODER_READ_METADATA:
1104                                 if(!read_metadata_(decoder))
1105                                         return false; /* above function sets the status for us */
1106                                 break;
1107                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1108                                 if(!frame_sync_(decoder))
1109                                         return true; /* above function sets the status for us */
1110                                 break;
1111                         case FLAC__STREAM_DECODER_READ_FRAME:
1112                                 if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
1113                                         return false; /* above function sets the status for us */
1114                                 break;
1115                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1116                         case FLAC__STREAM_DECODER_ABORTED:
1117                                 return true;
1118                         default:
1119                                 FLAC__ASSERT(0);
1120                                 return false;
1121                 }
1122         }
1123 }
1124
1125 FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
1126 {
1127         FLAC__bool got_a_frame;
1128         FLAC__ASSERT(0 != decoder);
1129         FLAC__ASSERT(0 != decoder->protected_);
1130
1131         while(1) {
1132                 switch(decoder->protected_->state) {
1133                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1134                         case FLAC__STREAM_DECODER_READ_METADATA:
1135                                 return false; /* above function sets the status for us */
1136                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1137                                 if(!frame_sync_(decoder))
1138                                         return true; /* above function sets the status for us */
1139                                 break;
1140                         case FLAC__STREAM_DECODER_READ_FRAME:
1141                                 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
1142                                         return false; /* above function sets the status for us */
1143                                 if(got_a_frame)
1144                                         return true; /* above function sets the status for us */
1145                                 break;
1146                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1147                         case FLAC__STREAM_DECODER_ABORTED:
1148                                 return true;
1149                         default:
1150                                 FLAC__ASSERT(0);
1151                                 return false;
1152                 }
1153         }
1154 }
1155
1156 FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
1157 {
1158         FLAC__uint64 length;
1159
1160         FLAC__ASSERT(0 != decoder);
1161
1162         if(
1163                 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
1164                 decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
1165                 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
1166                 decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
1167                 decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
1168         )
1169                 return false;
1170
1171         if(0 == decoder->private_->seek_callback)
1172                 return false;
1173
1174         FLAC__ASSERT(decoder->private_->seek_callback);
1175         FLAC__ASSERT(decoder->private_->tell_callback);
1176         FLAC__ASSERT(decoder->private_->length_callback);
1177         FLAC__ASSERT(decoder->private_->eof_callback);
1178
1179         if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
1180                 return false;
1181
1182         decoder->private_->is_seeking = true;
1183
1184         /* turn off md5 checking if a seek is attempted */
1185         decoder->private_->do_md5_checking = false;
1186
1187         /* 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) */
1188         if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
1189                 decoder->private_->is_seeking = false;
1190                 return false;
1191         }
1192
1193         /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
1194         if(
1195                 decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
1196                 decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
1197         ) {
1198                 if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
1199                         /* above call sets the state for us */
1200                         decoder->private_->is_seeking = false;
1201                         return false;
1202                 }
1203                 /* check this again in case we didn't know total_samples the first time */
1204                 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
1205                         decoder->private_->is_seeking = false;
1206                         return false;
1207                 }
1208         }
1209
1210         {
1211                 const FLAC__bool ok =
1212 #ifdef FLAC__HAS_OGG
1213                         decoder->private_->is_ogg?
1214                         seek_to_absolute_sample_ogg_(decoder, length, sample) :
1215 #endif
1216                         seek_to_absolute_sample_(decoder, length, sample)
1217                 ;
1218                 decoder->private_->is_seeking = false;
1219                 return ok;
1220         }
1221 }
1222
1223 /***********************************************************************
1224  *
1225  * Protected class methods
1226  *
1227  ***********************************************************************/
1228
1229 unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
1230 {
1231         FLAC__ASSERT(0 != decoder);
1232         return FLAC__bitbuffer_get_input_bytes_unconsumed(decoder->private_->input);
1233 }
1234
1235 /***********************************************************************
1236  *
1237  * Private class methods
1238  *
1239  ***********************************************************************/
1240
1241 void set_defaults_(FLAC__StreamDecoder *decoder)
1242 {
1243 #ifdef FLAC__HAS_OGG
1244         decoder->private_->is_ogg = false;
1245 #endif
1246         decoder->private_->read_callback = 0;
1247         decoder->private_->seek_callback = 0;
1248         decoder->private_->tell_callback = 0;
1249         decoder->private_->length_callback = 0;
1250         decoder->private_->eof_callback = 0;
1251         decoder->private_->write_callback = 0;
1252         decoder->private_->metadata_callback = 0;
1253         decoder->private_->error_callback = 0;
1254         decoder->private_->client_data = 0;
1255
1256         memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
1257         decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
1258         decoder->private_->metadata_filter_ids_count = 0;
1259
1260         decoder->protected_->md5_checking = false;
1261
1262 #ifdef FLAC__HAS_OGG
1263         FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
1264 #endif
1265 }
1266
1267 /*
1268  * This will forcibly set stdin to binary mode (for OSes that require it)
1269  */
1270 FILE *get_binary_stdin_()
1271 {
1272         /* if something breaks here it is probably due to the presence or
1273          * absence of an underscore before the identifiers 'setmode',
1274          * 'fileno', and/or 'O_BINARY'; check your system header files.
1275          */
1276 #if defined _MSC_VER || defined __MINGW32__
1277         _setmode(_fileno(stdin), _O_BINARY);
1278 #elif defined __CYGWIN__ || defined __EMX__
1279         /* almost certainly not needed for any modern Cygwin, but let's be safe... */
1280         setmode(_fileno(stdin), _O_BINARY);
1281 #endif
1282
1283         return stdin;
1284 }
1285
1286 FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
1287 {
1288         unsigned i;
1289         FLAC__int32 *tmp;
1290
1291         if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
1292                 return true;
1293
1294         /* simply using realloc() is not practical because the number of channels may change mid-stream */
1295
1296         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
1297                 if(0 != decoder->private_->output[i]) {
1298                         free(decoder->private_->output[i]-4);
1299                         decoder->private_->output[i] = 0;
1300                 }
1301                 if(0 != decoder->private_->residual_unaligned[i]) {
1302                         free(decoder->private_->residual_unaligned[i]);
1303                         decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
1304                 }
1305         }
1306
1307         for(i = 0; i < channels; i++) {
1308                 /* WATCHOUT:
1309                  * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
1310                  * output arrays have a buffer of up to 3 zeroes in front
1311                  * (at negative indices) for alignment purposes; we use 4
1312                  * to keep the data well-aligned.
1313                  */
1314                 tmp = (FLAC__int32*)malloc(sizeof(FLAC__int32)*(size+4));
1315                 if(tmp == 0) {
1316                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1317                         return false;
1318                 }
1319                 memset(tmp, 0, sizeof(FLAC__int32)*4);
1320                 decoder->private_->output[i] = tmp + 4;
1321
1322                 /* WATCHOUT:
1323                  * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
1324                  */
1325                 if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
1326                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1327                         return false;
1328                 }
1329         }
1330
1331         decoder->private_->output_capacity = size;
1332         decoder->private_->output_channels = channels;
1333
1334         return true;
1335 }
1336
1337 FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
1338 {
1339         unsigned i;
1340
1341         FLAC__ASSERT(0 != decoder);
1342         FLAC__ASSERT(0 != decoder->private_);
1343
1344         for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
1345                 if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
1346                         return true;
1347
1348         return false;
1349 }
1350
1351 FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
1352 {
1353         FLAC__uint32 x;
1354         unsigned i, id;
1355         FLAC__bool first = true;
1356
1357         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1358
1359         for(i = id = 0; i < 4; ) {
1360                 if(decoder->private_->cached) {
1361                         x = (FLAC__uint32)decoder->private_->lookahead;
1362                         decoder->private_->cached = false;
1363                 }
1364                 else {
1365                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1366                                 return false; /* read_callback_ sets the state for us */
1367                 }
1368                 if(x == FLAC__STREAM_SYNC_STRING[i]) {
1369                         first = true;
1370                         i++;
1371                         id = 0;
1372                         continue;
1373                 }
1374                 if(x == ID3V2_TAG_[id]) {
1375                         id++;
1376                         i = 0;
1377                         if(id == 3) {
1378                                 if(!skip_id3v2_tag_(decoder))
1379                                         return false; /* skip_id3v2_tag_ sets the state for us */
1380                         }
1381                         continue;
1382                 }
1383                 id = 0;
1384                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1385                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1386                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1387                                 return false; /* read_callback_ sets the state for us */
1388
1389                         /* 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 */
1390                         /* else we have to check if the second byte is the end of a sync code */
1391                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1392                                 decoder->private_->lookahead = (FLAC__byte)x;
1393                                 decoder->private_->cached = true;
1394                         }
1395                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1396                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1397                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1398                                 return true;
1399                         }
1400                 }
1401                 i = 0;
1402                 if(first) {
1403                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1404                         first = false;
1405                 }
1406         }
1407
1408         decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
1409         return true;
1410 }
1411
1412 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
1413 {
1414         FLAC__bool is_last;
1415         FLAC__uint32 i, x, type, length;
1416
1417         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1418
1419         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN, read_callback_, decoder))
1420                 return false; /* read_callback_ sets the state for us */
1421         is_last = x? true : false;
1422
1423         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN, read_callback_, decoder))
1424                 return false; /* read_callback_ sets the state for us */
1425
1426         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN, read_callback_, decoder))
1427                 return false; /* read_callback_ sets the state for us */
1428
1429         if(type == FLAC__METADATA_TYPE_STREAMINFO) {
1430                 if(!read_metadata_streaminfo_(decoder, is_last, length))
1431                         return false;
1432
1433                 decoder->private_->has_stream_info = true;
1434                 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))
1435                         decoder->private_->do_md5_checking = false;
1436                 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
1437                         decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
1438         }
1439         else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
1440                 if(!read_metadata_seektable_(decoder, is_last, length))
1441                         return false;
1442
1443                 decoder->private_->has_seek_table = true;
1444                 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
1445                         decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
1446         }
1447         else {
1448                 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
1449                 unsigned real_length = length;
1450                 FLAC__StreamMetadata block;
1451
1452                 block.is_last = is_last;
1453                 block.type = (FLAC__MetadataType)type;
1454                 block.length = length;
1455
1456                 if(type == FLAC__METADATA_TYPE_APPLICATION) {
1457                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8, read_callback_, decoder))
1458                                 return false; /* read_callback_ sets the state for us */
1459
1460                         real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
1461
1462                         if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
1463                                 skip_it = !skip_it;
1464                 }
1465
1466                 if(skip_it) {
1467                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
1468                                 return false; /* read_callback_ sets the state for us */
1469                 }
1470                 else {
1471                         switch(type) {
1472                                 case FLAC__METADATA_TYPE_PADDING:
1473                                         /* skip the padding bytes */
1474                                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
1475                                                 return false; /* read_callback_ sets the state for us */
1476                                         break;
1477                                 case FLAC__METADATA_TYPE_APPLICATION:
1478                                         /* remember, we read the ID already */
1479                                         if(real_length > 0) {
1480                                                 if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
1481                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1482                                                         return false;
1483                                                 }
1484                                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length, read_callback_, decoder))
1485                                                         return false; /* read_callback_ sets the state for us */
1486                                         }
1487                                         else
1488                                                 block.data.application.data = 0;
1489                                         break;
1490                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1491                                         if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
1492                                                 return false;
1493                                         break;
1494                                 case FLAC__METADATA_TYPE_CUESHEET:
1495                                         if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
1496                                                 return false;
1497                                         break;
1498                                 case FLAC__METADATA_TYPE_PICTURE:
1499                                         if(!read_metadata_picture_(decoder, &block.data.picture))
1500                                                 return false;
1501                                         break;
1502                                 case FLAC__METADATA_TYPE_STREAMINFO:
1503                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1504                                         FLAC__ASSERT(0);
1505                                         break;
1506                                 default:
1507                                         if(real_length > 0) {
1508                                                 if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
1509                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1510                                                         return false;
1511                                                 }
1512                                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length, read_callback_, decoder))
1513                                                         return false; /* read_callback_ sets the state for us */
1514                                         }
1515                                         else
1516                                                 block.data.unknown.data = 0;
1517                                         break;
1518                         }
1519                         if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
1520                                 decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1521
1522                         /* now we have to free any malloc'ed data in the block */
1523                         switch(type) {
1524                                 case FLAC__METADATA_TYPE_PADDING:
1525                                         break;
1526                                 case FLAC__METADATA_TYPE_APPLICATION:
1527                                         if(0 != block.data.application.data)
1528                                                 free(block.data.application.data);
1529                                         break;
1530                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1531                                         if(0 != block.data.vorbis_comment.vendor_string.entry)
1532                                                 free(block.data.vorbis_comment.vendor_string.entry);
1533                                         if(block.data.vorbis_comment.num_comments > 0)
1534                                                 for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
1535                                                         if(0 != block.data.vorbis_comment.comments[i].entry)
1536                                                                 free(block.data.vorbis_comment.comments[i].entry);
1537                                         if(0 != block.data.vorbis_comment.comments)
1538                                                 free(block.data.vorbis_comment.comments);
1539                                         break;
1540                                 case FLAC__METADATA_TYPE_CUESHEET:
1541                                         if(block.data.cue_sheet.num_tracks > 0)
1542                                                 for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
1543                                                         if(0 != block.data.cue_sheet.tracks[i].indices)
1544                                                                 free(block.data.cue_sheet.tracks[i].indices);
1545                                         if(0 != block.data.cue_sheet.tracks)
1546                                                 free(block.data.cue_sheet.tracks);
1547                                         break;
1548                                 case FLAC__METADATA_TYPE_PICTURE:
1549                                         if(0 != block.data.picture.mime_type)
1550                                                 free(block.data.picture.mime_type);
1551                                         if(0 != block.data.picture.description)
1552                                                 free(block.data.picture.description);
1553                                         if(0 != block.data.picture.data)
1554                                                 free(block.data.picture.data);
1555                                         break;
1556                                 case FLAC__METADATA_TYPE_STREAMINFO:
1557                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1558                                         FLAC__ASSERT(0);
1559                                 default:
1560                                         if(0 != block.data.unknown.data)
1561                                                 free(block.data.unknown.data);
1562                                         break;
1563                         }
1564                 }
1565         }
1566
1567         if(is_last) {
1568                 /* if this fails, it's OK, it's just a hint for the seek routine */
1569                 if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
1570                         decoder->private_->first_frame_offset = 0;
1571                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1572         }
1573
1574         return true;
1575 }
1576
1577 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1578 {
1579         FLAC__uint32 x;
1580         unsigned bits, used_bits = 0;
1581
1582         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1583
1584         decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
1585         decoder->private_->stream_info.is_last = is_last;
1586         decoder->private_->stream_info.length = length;
1587
1588         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1589         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, bits, read_callback_, decoder))
1590                 return false; /* read_callback_ sets the state for us */
1591         decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1592         used_bits += bits;
1593
1594         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1595         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN, read_callback_, decoder))
1596                 return false; /* read_callback_ sets the state for us */
1597         decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1598         used_bits += bits;
1599
1600         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1601         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN, read_callback_, decoder))
1602                 return false; /* read_callback_ sets the state for us */
1603         decoder->private_->stream_info.data.stream_info.min_framesize = x;
1604         used_bits += bits;
1605
1606         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1607         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN, read_callback_, decoder))
1608                 return false; /* read_callback_ sets the state for us */
1609         decoder->private_->stream_info.data.stream_info.max_framesize = x;
1610         used_bits += bits;
1611
1612         bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1613         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN, read_callback_, decoder))
1614                 return false; /* read_callback_ sets the state for us */
1615         decoder->private_->stream_info.data.stream_info.sample_rate = x;
1616         used_bits += bits;
1617
1618         bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1619         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN, read_callback_, decoder))
1620                 return false; /* read_callback_ sets the state for us */
1621         decoder->private_->stream_info.data.stream_info.channels = x+1;
1622         used_bits += bits;
1623
1624         bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1625         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN, read_callback_, decoder))
1626                 return false; /* read_callback_ sets the state for us */
1627         decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1628         used_bits += bits;
1629
1630         bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1631         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN, read_callback_, decoder))
1632                 return false; /* read_callback_ sets the state for us */
1633         used_bits += bits;
1634
1635         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16, read_callback_, decoder))
1636                 return false; /* read_callback_ sets the state for us */
1637         used_bits += 16*8;
1638
1639         /* skip the rest of the block */
1640         FLAC__ASSERT(used_bits % 8 == 0);
1641         length -= (used_bits / 8);
1642         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1643                 return false; /* read_callback_ sets the state for us */
1644
1645         return true;
1646 }
1647
1648 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1649 {
1650         FLAC__uint32 i, x;
1651         FLAC__uint64 xx;
1652
1653         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1654
1655         decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1656         decoder->private_->seek_table.is_last = is_last;
1657         decoder->private_->seek_table.length = length;
1658
1659         decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1660
1661         /* use realloc since we may pass through here several times (e.g. after seeking) */
1662         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)))) {
1663                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1664                 return false;
1665         }
1666         for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1667                 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN, read_callback_, decoder))
1668                         return false; /* read_callback_ sets the state for us */
1669                 decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1670
1671                 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN, read_callback_, decoder))
1672                         return false; /* read_callback_ sets the state for us */
1673                 decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1674
1675                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN, read_callback_, decoder))
1676                         return false; /* read_callback_ sets the state for us */
1677                 decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1678         }
1679         length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1680         /* if there is a partial point left, skip over it */
1681         if(length > 0) {
1682                 /*@@@ do a send_error_to_client_() here?  there's an argument for either way */
1683                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1684                         return false; /* read_callback_ sets the state for us */
1685         }
1686
1687         return true;
1688 }
1689
1690 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1691 {
1692         FLAC__uint32 i;
1693
1694         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1695
1696         /* read vendor string */
1697         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1698         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length, read_callback_, decoder))
1699                 return false; /* read_callback_ sets the state for us */
1700         if(obj->vendor_string.length > 0) {
1701                 if(0 == (obj->vendor_string.entry = (FLAC__byte*)malloc(obj->vendor_string.length+1))) {
1702                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1703                         return false;
1704                 }
1705                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length, read_callback_, decoder))
1706                         return false; /* read_callback_ sets the state for us */
1707                 obj->vendor_string.entry[obj->vendor_string.length] = '\0';
1708         }
1709         else
1710                 obj->vendor_string.entry = 0;
1711
1712         /* read num comments */
1713         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1714         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->num_comments, read_callback_, decoder))
1715                 return false; /* read_callback_ sets the state for us */
1716
1717         /* read comments */
1718         if(obj->num_comments > 0) {
1719                 if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)malloc(obj->num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1720                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1721                         return false;
1722                 }
1723                 for(i = 0; i < obj->num_comments; i++) {
1724                         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1725                         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->comments[i].length, read_callback_, decoder))
1726                                 return false; /* read_callback_ sets the state for us */
1727                         if(obj->comments[i].length > 0) {
1728                                 if(0 == (obj->comments[i].entry = (FLAC__byte*)malloc(obj->comments[i].length+1))) {
1729                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1730                                         return false;
1731                                 }
1732                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length, read_callback_, decoder))
1733                                         return false; /* read_callback_ sets the state for us */
1734                                 obj->comments[i].entry[obj->comments[i].length] = '\0';
1735                         }
1736                         else
1737                                 obj->comments[i].entry = 0;
1738                 }
1739         }
1740         else {
1741                 obj->comments = 0;
1742         }
1743
1744         return true;
1745 }
1746
1747 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1748 {
1749         FLAC__uint32 i, j, x;
1750
1751         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1752
1753         memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1754
1755         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1756         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8, read_callback_, decoder))
1757                 return false; /* read_callback_ sets the state for us */
1758
1759         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN, read_callback_, decoder))
1760                 return false; /* read_callback_ sets the state for us */
1761
1762         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN, read_callback_, decoder))
1763                 return false; /* read_callback_ sets the state for us */
1764         obj->is_cd = x? true : false;
1765
1766         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN, read_callback_, decoder))
1767                 return false; /* read_callback_ sets the state for us */
1768
1769         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN, read_callback_, decoder))
1770                 return false; /* read_callback_ sets the state for us */
1771         obj->num_tracks = x;
1772
1773         if(obj->num_tracks > 0) {
1774                 if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1775                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1776                         return false;
1777                 }
1778                 for(i = 0; i < obj->num_tracks; i++) {
1779                         FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1780                         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN, read_callback_, decoder))
1781                                 return false; /* read_callback_ sets the state for us */
1782
1783                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN, read_callback_, decoder))
1784                                 return false; /* read_callback_ sets the state for us */
1785                         track->number = (FLAC__byte)x;
1786
1787                         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1788                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8, read_callback_, decoder))
1789                                 return false; /* read_callback_ sets the state for us */
1790
1791                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN, read_callback_, decoder))
1792                                 return false; /* read_callback_ sets the state for us */
1793                         track->type = x;
1794
1795                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN, read_callback_, decoder))
1796                                 return false; /* read_callback_ sets the state for us */
1797                         track->pre_emphasis = x;
1798
1799                         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN, read_callback_, decoder))
1800                                 return false; /* read_callback_ sets the state for us */
1801
1802                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN, read_callback_, decoder))
1803                                 return false; /* read_callback_ sets the state for us */
1804                         track->num_indices = (FLAC__byte)x;
1805
1806                         if(track->num_indices > 0) {
1807                                 if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1808                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1809                                         return false;
1810                                 }
1811                                 for(j = 0; j < track->num_indices; j++) {
1812                                         FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1813                                         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN, read_callback_, decoder))
1814                                                 return false; /* read_callback_ sets the state for us */
1815
1816                                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN, read_callback_, decoder))
1817                                                 return false; /* read_callback_ sets the state for us */
1818                                         index->number = (FLAC__byte)x;
1819
1820                                         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN, read_callback_, decoder))
1821                                                 return false; /* read_callback_ sets the state for us */
1822                                 }
1823                         }
1824                 }
1825         }
1826
1827         return true;
1828 }
1829
1830 FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
1831 {
1832         FLAC__uint32 len;
1833
1834         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1835
1836         /* read type */
1837         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN, read_callback_, decoder))
1838                 return false; /* read_callback_ sets the state for us */
1839
1840         /* read MIME type */
1841         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN, read_callback_, decoder))
1842                 return false; /* read_callback_ sets the state for us */
1843         if(0 == (obj->mime_type = (char*)malloc(len+1))) {
1844                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1845                 return false;
1846         }
1847         if(len > 0) {
1848                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, len, read_callback_, decoder))
1849                         return false; /* read_callback_ sets the state for us */
1850         }
1851         obj->mime_type[len] = '\0';
1852
1853         /* read description */
1854         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN, read_callback_, decoder))
1855                 return false; /* read_callback_ sets the state for us */
1856         if(0 == (obj->description = (FLAC__byte*)malloc(len+1))) {
1857                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1858                 return false;
1859         }
1860         if(len > 0) {
1861                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, len, read_callback_, decoder))
1862                         return false; /* read_callback_ sets the state for us */
1863         }
1864         obj->description[len] = '\0';
1865
1866         /* read width */
1867         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN, read_callback_, decoder))
1868                 return false; /* read_callback_ sets the state for us */
1869
1870         /* read height */
1871         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN, read_callback_, decoder))
1872                 return false; /* read_callback_ sets the state for us */
1873
1874         /* read depth */
1875         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN, read_callback_, decoder))
1876                 return false; /* read_callback_ sets the state for us */
1877
1878         /* read colors */
1879         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN, read_callback_, decoder))
1880                 return false; /* read_callback_ sets the state for us */
1881
1882         /* read data */
1883         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN, read_callback_, decoder))
1884                 return false; /* read_callback_ sets the state for us */
1885         if(0 == (obj->data = (FLAC__byte*)malloc(obj->data_length))) {
1886                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1887                 return false;
1888         }
1889         if(obj->data_length > 0) {
1890                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length, read_callback_, decoder))
1891                         return false; /* read_callback_ sets the state for us */
1892         }
1893
1894         return true;
1895 }
1896
1897 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1898 {
1899         FLAC__uint32 x;
1900         unsigned i, skip;
1901
1902         /* skip the version and flags bytes */
1903         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 24, read_callback_, decoder))
1904                 return false; /* read_callback_ sets the state for us */
1905         /* get the size (in bytes) to skip */
1906         skip = 0;
1907         for(i = 0; i < 4; i++) {
1908                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1909                         return false; /* read_callback_ sets the state for us */
1910                 skip <<= 7;
1911                 skip |= (x & 0x7f);
1912         }
1913         /* skip the rest of the tag */
1914         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, skip, read_callback_, decoder))
1915                 return false; /* read_callback_ sets the state for us */
1916         return true;
1917 }
1918
1919 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1920 {
1921         FLAC__uint32 x;
1922         FLAC__bool first = true;
1923
1924         /* If we know the total number of samples in the stream, stop if we've read that many. */
1925         /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1926         if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
1927                 if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
1928                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1929                         return true;
1930                 }
1931         }
1932
1933         /* make sure we're byte aligned */
1934         if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
1935                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
1936                         return false; /* read_callback_ sets the state for us */
1937         }
1938
1939         while(1) {
1940                 if(decoder->private_->cached) {
1941                         x = (FLAC__uint32)decoder->private_->lookahead;
1942                         decoder->private_->cached = false;
1943                 }
1944                 else {
1945                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1946                                 return false; /* read_callback_ sets the state for us */
1947                 }
1948                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1949                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1950                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1951                                 return false; /* read_callback_ sets the state for us */
1952
1953                         /* 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 */
1954                         /* else we have to check if the second byte is the end of a sync code */
1955                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1956                                 decoder->private_->lookahead = (FLAC__byte)x;
1957                                 decoder->private_->cached = true;
1958                         }
1959                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1960                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1961                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1962                                 return true;
1963                         }
1964                 }
1965                 if(first) {
1966                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1967                         first = false;
1968                 }
1969         }
1970
1971         return true;
1972 }
1973
1974 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
1975 {
1976         unsigned channel;
1977         unsigned i;
1978         FLAC__int32 mid, side, left, right;
1979         FLAC__uint16 frame_crc; /* the one we calculate from the input stream */
1980         FLAC__uint32 x;
1981
1982         *got_a_frame = false;
1983
1984         /* init the CRC */
1985         frame_crc = 0;
1986         FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
1987         FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
1988         FLAC__bitbuffer_reset_read_crc16(decoder->private_->input, frame_crc);
1989
1990         if(!read_frame_header_(decoder))
1991                 return false;
1992         if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
1993                 return true;
1994         if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
1995                 return false;
1996         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1997                 /*
1998                  * first figure the correct bits-per-sample of the subframe
1999                  */
2000                 unsigned bps = decoder->private_->frame.header.bits_per_sample;
2001                 switch(decoder->private_->frame.header.channel_assignment) {
2002                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2003                                 /* no adjustment needed */
2004                                 break;
2005                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2006                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2007                                 if(channel == 1)
2008                                         bps++;
2009                                 break;
2010                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2011                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2012                                 if(channel == 0)
2013                                         bps++;
2014                                 break;
2015                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2016                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2017                                 if(channel == 1)
2018                                         bps++;
2019                                 break;
2020                         default:
2021                                 FLAC__ASSERT(0);
2022                 }
2023                 /*
2024                  * now read it
2025                  */
2026                 if(!read_subframe_(decoder, channel, bps, do_full_decode))
2027                         return false;
2028                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2029                         return true;
2030         }
2031         if(!read_zero_padding_(decoder))
2032                 return false;
2033
2034         /*
2035          * Read the frame CRC-16 from the footer and check
2036          */
2037         frame_crc = FLAC__bitbuffer_get_read_crc16(decoder->private_->input);
2038         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN, read_callback_, decoder))
2039                 return false; /* read_callback_ sets the state for us */
2040         if(frame_crc == (FLAC__uint16)x) {
2041                 if(do_full_decode) {
2042                         /* Undo any special channel coding */
2043                         switch(decoder->private_->frame.header.channel_assignment) {
2044                                 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2045                                         /* do nothing */
2046                                         break;
2047                                 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2048                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2049                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2050                                                 decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
2051                                         break;
2052                                 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2053                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2054                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2055                                                 decoder->private_->output[0][i] += decoder->private_->output[1][i];
2056                                         break;
2057                                 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2058                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2059                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2060                                                 mid = decoder->private_->output[0][i];
2061                                                 side = decoder->private_->output[1][i];
2062                                                 mid <<= 1;
2063                                                 if(side & 1) /* i.e. if 'side' is odd... */
2064                                                         mid++;
2065                                                 left = mid + side;
2066                                                 right = mid - side;
2067                                                 decoder->private_->output[0][i] = left >> 1;
2068                                                 decoder->private_->output[1][i] = right >> 1;
2069                                         }
2070                                         break;
2071                                 default:
2072                                         FLAC__ASSERT(0);
2073                                         break;
2074                         }
2075                 }
2076         }
2077         else {
2078                 /* Bad frame, emit error and zero the output signal */
2079                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
2080                 if(do_full_decode) {
2081                         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2082                                 memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2083                         }
2084                 }
2085         }
2086
2087         *got_a_frame = true;
2088
2089         /* put the latest values into the public section of the decoder instance */
2090         decoder->protected_->channels = decoder->private_->frame.header.channels;
2091         decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
2092         decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
2093         decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
2094         decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
2095
2096         FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2097         decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
2098
2099         /* write it */
2100         if(do_full_decode) {
2101                 if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
2102                         return false;
2103         }
2104
2105         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2106         return true;
2107 }
2108
2109 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
2110 {
2111         FLAC__uint32 x;
2112         FLAC__uint64 xx;
2113         unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
2114         FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
2115         unsigned raw_header_len;
2116         FLAC__bool is_unparseable = false;
2117         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);
2118         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);
2119
2120         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
2121
2122         /* init the raw header with the saved bits from synchronization */
2123         raw_header[0] = decoder->private_->header_warmup[0];
2124         raw_header[1] = decoder->private_->header_warmup[1];
2125         raw_header_len = 2;
2126
2127         /*
2128          * check to make sure that the reserved bits are 0
2129          */
2130         if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
2131                 is_unparseable = true;
2132         }
2133
2134         /*
2135          * Note that along the way as we read the header, we look for a sync
2136          * code inside.  If we find one it would indicate that our original
2137          * sync was bad since there cannot be a sync code in a valid header.
2138          */
2139
2140         /*
2141          * read in the raw header as bytes so we can CRC it, and parse it on the way
2142          */
2143         for(i = 0; i < 2; i++) {
2144                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2145                         return false; /* read_callback_ sets the state for us */
2146                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
2147                         /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
2148                         decoder->private_->lookahead = (FLAC__byte)x;
2149                         decoder->private_->cached = true;
2150                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2151                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2152                         return true;
2153                 }
2154                 raw_header[raw_header_len++] = (FLAC__byte)x;
2155         }
2156
2157         switch(x = raw_header[2] >> 4) {
2158                 case 0:
2159                         if(is_known_fixed_blocksize_stream)
2160                                 decoder->private_->frame.header.blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2161                         else
2162                                 is_unparseable = true;
2163                         break;
2164                 case 1:
2165                         decoder->private_->frame.header.blocksize = 192;
2166                         break;
2167                 case 2:
2168                 case 3:
2169                 case 4:
2170                 case 5:
2171                         decoder->private_->frame.header.blocksize = 576 << (x-2);
2172                         break;
2173                 case 6:
2174                 case 7:
2175                         blocksize_hint = x;
2176                         break;
2177                 case 8:
2178                 case 9:
2179                 case 10:
2180                 case 11:
2181                 case 12:
2182                 case 13:
2183                 case 14:
2184                 case 15:
2185                         decoder->private_->frame.header.blocksize = 256 << (x-8);
2186                         break;
2187                 default:
2188                         FLAC__ASSERT(0);
2189                         break;
2190         }
2191
2192         switch(x = raw_header[2] & 0x0f) {
2193                 case 0:
2194                         if(decoder->private_->has_stream_info)
2195                                 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
2196                         else
2197                                 is_unparseable = true;
2198                         break;
2199                 case 1:
2200                 case 2:
2201                 case 3:
2202                         is_unparseable = true;
2203                         break;
2204                 case 4:
2205                         decoder->private_->frame.header.sample_rate = 8000;
2206                         break;
2207                 case 5:
2208                         decoder->private_->frame.header.sample_rate = 16000;
2209                         break;
2210                 case 6:
2211                         decoder->private_->frame.header.sample_rate = 22050;
2212                         break;
2213                 case 7:
2214                         decoder->private_->frame.header.sample_rate = 24000;
2215                         break;
2216                 case 8:
2217                         decoder->private_->frame.header.sample_rate = 32000;
2218                         break;
2219                 case 9:
2220                         decoder->private_->frame.header.sample_rate = 44100;
2221                         break;
2222                 case 10:
2223                         decoder->private_->frame.header.sample_rate = 48000;
2224                         break;
2225                 case 11:
2226                         decoder->private_->frame.header.sample_rate = 96000;
2227                         break;
2228                 case 12:
2229                 case 13:
2230                 case 14:
2231                         sample_rate_hint = x;
2232                         break;
2233                 case 15:
2234                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2235                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2236                         return true;
2237                 default:
2238                         FLAC__ASSERT(0);
2239         }
2240
2241         x = (unsigned)(raw_header[3] >> 4);
2242         if(x & 8) {
2243                 decoder->private_->frame.header.channels = 2;
2244                 switch(x & 7) {
2245                         case 0:
2246                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2247                                 break;
2248                         case 1:
2249                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2250                                 break;
2251                         case 2:
2252                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2253                                 break;
2254                         default:
2255                                 is_unparseable = true;
2256                                 break;
2257                 }
2258         }
2259         else {
2260                 decoder->private_->frame.header.channels = (unsigned)x + 1;
2261                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2262         }
2263
2264         switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2265                 case 0:
2266                         if(decoder->private_->has_stream_info)
2267                                 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2268                         else
2269                                 is_unparseable = true;
2270                         break;
2271                 case 1:
2272                         decoder->private_->frame.header.bits_per_sample = 8;
2273                         break;
2274                 case 2:
2275                         decoder->private_->frame.header.bits_per_sample = 12;
2276                         break;
2277                 case 4:
2278                         decoder->private_->frame.header.bits_per_sample = 16;
2279                         break;
2280                 case 5:
2281                         decoder->private_->frame.header.bits_per_sample = 20;
2282                         break;
2283                 case 6:
2284                         decoder->private_->frame.header.bits_per_sample = 24;
2285                         break;
2286                 case 3:
2287                 case 7:
2288                         is_unparseable = true;
2289                         break;
2290                 default:
2291                         FLAC__ASSERT(0);
2292                         break;
2293         }
2294
2295         if(raw_header[3] & 0x01) { /* this should be a zero padding bit */
2296                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2297                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2298                 return true;
2299         }
2300
2301         /*
2302          * Now we get to the regrettable consequences of not knowing for sure
2303          * whether we got a frame number or a sample number.  There are no
2304          * encoders that do variable-blocksize encoding so unless we know from
2305          * the STREAMINFO that it is variable-blocksize we will assume it is
2306          * fixed-blocksize.  The trouble comes when we have no STREAMINFO; again
2307          * we will guess that is fixed-blocksize.  Where this can go wrong: 1) a
2308          * variable-blocksize stream with no STREAMINFO; 2) a fixed-blocksize
2309          * stream that was edited such that one or more frames before or
2310          * including this one do not have the same number of samples as the
2311          * STREAMINFO's min and max blocksize.
2312          */
2313         if(is_known_variable_blocksize_stream) {
2314                 if(blocksize_hint) {
2315                         if(!FLAC__bitbuffer_read_utf8_uint64(decoder->private_->input, &xx, read_callback_, decoder, raw_header, &raw_header_len))
2316                                 return false; /* read_callback_ sets the state for us */
2317                         if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
2318                                 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2319                                 decoder->private_->cached = true;
2320                                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2321                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2322                                 return true;
2323                         }
2324                         decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2325                         decoder->private_->frame.header.number.sample_number = xx;
2326                 }
2327                 else
2328                         is_unparseable = true;
2329         }
2330         else {
2331                 if(!FLAC__bitbuffer_read_utf8_uint32(decoder->private_->input, &x, read_callback_, decoder, raw_header, &raw_header_len))
2332                         return false; /* read_callback_ sets the state for us */
2333                 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
2334                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2335                         decoder->private_->cached = true;
2336                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2337                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2338                         return true;
2339                 }
2340                 decoder->private_->last_frame_number = x;
2341                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2342                 if(decoder->private_->has_stream_info) {
2343                         FLAC__ASSERT(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize);
2344                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
2345                         decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2346                 }
2347                 else if(blocksize_hint) {
2348                         if(decoder->private_->last_block_size)
2349                                 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->last_block_size * (FLAC__uint64)x;
2350                         else
2351                                 is_unparseable = true;
2352                 }
2353                 else {
2354                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
2355                         decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2356                 }
2357         }
2358
2359         if(blocksize_hint) {
2360                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2361                         return false; /* read_callback_ sets the state for us */
2362                 raw_header[raw_header_len++] = (FLAC__byte)x;
2363                 if(blocksize_hint == 7) {
2364                         FLAC__uint32 _x;
2365                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
2366                                 return false; /* read_callback_ sets the state for us */
2367                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2368                         x = (x << 8) | _x;
2369                 }
2370                 decoder->private_->frame.header.blocksize = x+1;
2371         }
2372
2373         if(sample_rate_hint) {
2374                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2375                         return false; /* read_callback_ sets the state for us */
2376                 raw_header[raw_header_len++] = (FLAC__byte)x;
2377                 if(sample_rate_hint != 12) {
2378                         FLAC__uint32 _x;
2379                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
2380                                 return false; /* read_callback_ sets the state for us */
2381                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2382                         x = (x << 8) | _x;
2383                 }
2384                 if(sample_rate_hint == 12)
2385                         decoder->private_->frame.header.sample_rate = x*1000;
2386                 else if(sample_rate_hint == 13)
2387                         decoder->private_->frame.header.sample_rate = x;
2388                 else
2389                         decoder->private_->frame.header.sample_rate = x*10;
2390         }
2391
2392         /* read the CRC-8 byte */
2393         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2394                 return false; /* read_callback_ sets the state for us */
2395         crc8 = (FLAC__byte)x;
2396
2397         if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
2398                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2399                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2400                 return true;
2401         }
2402
2403         if(is_unparseable) {
2404                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2405                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2406                 return true;
2407         }
2408
2409         return true;
2410 }
2411
2412 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2413 {
2414         FLAC__uint32 x;
2415         FLAC__bool wasted_bits;
2416         unsigned i;
2417
2418         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder)) /* MAGIC NUMBER */
2419                 return false; /* read_callback_ sets the state for us */
2420
2421         wasted_bits = (x & 1);
2422         x &= 0xfe;
2423
2424         if(wasted_bits) {
2425                 unsigned u;
2426                 if(!FLAC__bitbuffer_read_unary_unsigned(decoder->private_->input, &u, read_callback_, decoder))
2427                         return false; /* read_callback_ sets the state for us */
2428                 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
2429                 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
2430         }
2431         else
2432                 decoder->private_->frame.subframes[channel].wasted_bits = 0;
2433
2434         /*
2435          * Lots of magic numbers here
2436          */
2437         if(x & 0x80) {
2438                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2439                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2440                 return true;
2441         }
2442         else if(x == 0) {
2443                 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2444                         return false;
2445         }
2446         else if(x == 2) {
2447                 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2448                         return false;
2449         }
2450         else if(x < 16) {
2451                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2452                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2453                 return true;
2454         }
2455         else if(x <= 24) {
2456                 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2457                         return false;
2458                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2459                         return true;
2460         }
2461         else if(x < 64) {
2462                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2463                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2464                 return true;
2465         }
2466         else {
2467                 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2468                         return false;
2469                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2470                         return true;
2471         }
2472
2473         if(wasted_bits && do_full_decode) {
2474                 x = decoder->private_->frame.subframes[channel].wasted_bits;
2475                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2476                         decoder->private_->output[channel][i] <<= x;
2477         }
2478
2479         return true;
2480 }
2481
2482 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2483 {
2484         FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2485         FLAC__int32 x;
2486         unsigned i;
2487         FLAC__int32 *output = decoder->private_->output[channel];
2488
2489         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2490
2491         if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
2492                 return false; /* read_callback_ sets the state for us */
2493
2494         subframe->value = x;
2495
2496         /* decode the subframe */
2497         if(do_full_decode) {
2498                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2499                         output[i] = x;
2500         }
2501
2502         return true;
2503 }
2504
2505 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2506 {
2507         FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2508         FLAC__int32 i32;
2509         FLAC__uint32 u32;
2510         unsigned u;
2511
2512         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2513
2514         subframe->residual = decoder->private_->residual[channel];
2515         subframe->order = order;
2516
2517         /* read warm-up samples */
2518         for(u = 0; u < order; u++) {
2519                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
2520                         return false; /* read_callback_ sets the state for us */
2521                 subframe->warmup[u] = i32;
2522         }
2523
2524         /* read entropy coding method info */
2525         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
2526                 return false; /* read_callback_ sets the state for us */
2527         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2528         switch(subframe->entropy_coding_method.type) {
2529                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2530                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
2531                                 return false; /* read_callback_ sets the state for us */
2532                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2533                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2534                         break;
2535                 default:
2536                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2537                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2538                         return true;
2539         }
2540
2541         /* read residual */
2542         switch(subframe->entropy_coding_method.type) {
2543                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2544                         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]))
2545                                 return false;
2546                         break;
2547                 default:
2548                         FLAC__ASSERT(0);
2549         }
2550
2551         /* decode the subframe */
2552         if(do_full_decode) {
2553                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2554                 FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
2555         }
2556
2557         return true;
2558 }
2559
2560 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2561 {
2562         FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2563         FLAC__int32 i32;
2564         FLAC__uint32 u32;
2565         unsigned u;
2566
2567         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2568
2569         subframe->residual = decoder->private_->residual[channel];
2570         subframe->order = order;
2571
2572         /* read warm-up samples */
2573         for(u = 0; u < order; u++) {
2574                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
2575                         return false; /* read_callback_ sets the state for us */
2576                 subframe->warmup[u] = i32;
2577         }
2578
2579         /* read qlp coeff precision */
2580         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN, read_callback_, decoder))
2581                 return false; /* read_callback_ sets the state for us */
2582         if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
2583                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2584                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2585                 return true;
2586         }
2587         subframe->qlp_coeff_precision = u32+1;
2588
2589         /* read qlp shift */
2590         if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN, read_callback_, decoder))
2591                 return false; /* read_callback_ sets the state for us */
2592         subframe->quantization_level = i32;
2593
2594         /* read quantized lp coefficiencts */
2595         for(u = 0; u < order; u++) {
2596                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision, read_callback_, decoder))
2597                         return false; /* read_callback_ sets the state for us */
2598                 subframe->qlp_coeff[u] = i32;
2599         }
2600
2601         /* read entropy coding method info */
2602         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
2603                 return false; /* read_callback_ sets the state for us */
2604         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2605         switch(subframe->entropy_coding_method.type) {
2606                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2607                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
2608                                 return false; /* read_callback_ sets the state for us */
2609                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2610                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2611                         break;
2612                 default:
2613                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2614                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2615                         return true;
2616         }
2617
2618         /* read residual */
2619         switch(subframe->entropy_coding_method.type) {
2620                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2621                         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]))
2622                                 return false;
2623                         break;
2624                 default:
2625                         FLAC__ASSERT(0);
2626         }
2627
2628         /* decode the subframe */
2629         if(do_full_decode) {
2630                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2631                 if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2632                         if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2633                                 if(order <= 8)
2634                                         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);
2635                                 else
2636                                         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);
2637                         }
2638                         else
2639                                 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);
2640                 else
2641                         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);
2642         }
2643
2644         return true;
2645 }
2646
2647 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2648 {
2649         FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2650         FLAC__int32 x, *residual = decoder->private_->residual[channel];
2651         unsigned i;
2652
2653         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2654
2655         subframe->data = residual;
2656
2657         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2658                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
2659                         return false; /* read_callback_ sets the state for us */
2660                 residual[i] = x;
2661         }
2662
2663         /* decode the subframe */
2664         if(do_full_decode)
2665                 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2666
2667         return true;
2668 }
2669
2670 FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual)
2671 {
2672         FLAC__uint32 rice_parameter;
2673         int i;
2674         unsigned partition, sample, u;
2675         const unsigned partitions = 1u << partition_order;
2676         const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2677
2678         /* sanity checks */
2679         if(partition_order == 0) {
2680                 if(decoder->private_->frame.header.blocksize < predictor_order) {
2681                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2682                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2683                         return true;
2684                 }
2685         }
2686         else {
2687                 if(partition_samples < predictor_order) {
2688                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2689                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2690                         return true;
2691                 }
2692         }
2693
2694         if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2695                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2696                 return false;
2697         }
2698
2699         sample = 0;
2700         for(partition = 0; partition < partitions; partition++) {
2701                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN, read_callback_, decoder))
2702                         return false; /* read_callback_ sets the state for us */
2703                 partitioned_rice_contents->parameters[partition] = rice_parameter;
2704                 if(rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2705                         u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2706                         if(!FLAC__bitbuffer_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter, read_callback_, decoder))
2707                                 return false; /* read_callback_ sets the state for us */
2708                         sample += u;
2709                 }
2710                 else {
2711                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN, read_callback_, decoder))
2712                                 return false; /* read_callback_ sets the state for us */
2713                         partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2714                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2715                                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i, rice_parameter, read_callback_, decoder))
2716                                         return false; /* read_callback_ sets the state for us */
2717                                 residual[sample] = i;
2718                         }
2719                 }
2720         }
2721
2722         return true;
2723 }
2724
2725 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2726 {
2727         if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
2728                 FLAC__uint32 zero = 0;
2729                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
2730                         return false; /* read_callback_ sets the state for us */
2731                 if(zero != 0) {
2732                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2733                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2734                 }
2735         }
2736         return true;
2737 }
2738
2739 FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
2740 {
2741         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2742
2743         if(
2744 #if FLAC__HAS_OGG
2745                 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2746                 !decoder->private_->is_ogg &&
2747 #endif
2748                 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2749         ) {
2750                 *bytes = 0;
2751                 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2752                 return false;
2753         }
2754         else if(*bytes > 0) {
2755                 /* While seeking, it is possible for our seek to land in the
2756                  * middle of audio data that looks exactly like a frame header
2757                  * from a future version of an encoder.  When that happens, our
2758                  * error callback will get an
2759                  * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
2760                  * unparseable_frame_count.  But there is a remote possibility
2761                  * that it is properly synced at such a "future-codec frame",
2762                  * so to make sure, we wait to see many "unparseable" errors in
2763                  * a row before bailing out.
2764                  */
2765                 if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2766                         decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2767                         return false;
2768                 }
2769                 else {
2770                         const FLAC__StreamDecoderReadStatus status =
2771 #ifdef FLAC__HAS_OGG
2772                                 decoder->private_->is_ogg?
2773                                 read_callback_ogg_aspect_(decoder, buffer, bytes) :
2774 #endif
2775                                 decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
2776                         ;
2777                         if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
2778                                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2779                                 return false;
2780                         }
2781                         else if(*bytes == 0) {
2782                                 if(
2783                                         status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
2784                                         (
2785 #if FLAC__HAS_OGG
2786                                                 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2787                                                 !decoder->private_->is_ogg &&
2788 #endif
2789                                                 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2790                                         )
2791                                 ) {
2792                                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2793                                         return false;
2794                                 }
2795                                 else
2796                                         return true;
2797                         }
2798                         else
2799                                 return true;
2800                 }
2801         }
2802         else {
2803                 /* abort to avoid a deadlock */
2804                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2805                 return false;
2806         }
2807         /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
2808          * for Ogg FLAC.  This is because the ogg decoder aspect can lose sync
2809          * and at the same time hit the end of the stream.  There is no way to
2810          * report an Ogg sync loss through the callbacks (see note in
2811          * read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
2812          * So to keep the decoder from stopping at this point we gate the call
2813          * to the eof_callback and let the Ogg decoder aspect set the
2814          * end-of-stream state when it is needed.
2815          */
2816 }
2817
2818 #ifdef FLAC__HAS_OGG
2819 FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
2820 {
2821         switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
2822                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
2823                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2824                 /* we don't really have a way to handle lost sync via read
2825                  * callback so we'll let it pass and let the underlying
2826                  * FLAC decoder catch the error
2827                  */
2828                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
2829                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2830                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
2831                         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2832                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
2833                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
2834                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
2835                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
2836                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
2837                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2838                 default:
2839                         FLAC__ASSERT(0);
2840                         /* double protection */
2841                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2842         }
2843 }
2844
2845 FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
2846 {
2847         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
2848
2849         switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
2850                 case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
2851                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
2852                 case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
2853                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
2854                 case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
2855                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2856                 default:
2857                         /* double protection: */
2858                         FLAC__ASSERT(0);
2859                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2860         }
2861 }
2862 #endif
2863
2864 FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2865 {
2866         if(decoder->private_->is_seeking) {
2867                 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
2868                 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
2869                 FLAC__uint64 target_sample = decoder->private_->target_sample;
2870
2871                 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2872
2873 #ifdef FLAC__HAS_OGG
2874                 decoder->private_->got_a_frame = true;
2875 #endif
2876                 decoder->private_->last_frame = *frame; /* save the frame */
2877                 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
2878                         unsigned delta = (unsigned)(target_sample - this_frame_sample);
2879                         /* kick out of seek mode */
2880                         decoder->private_->is_seeking = false;
2881                         /* shift out the samples before target_sample */
2882                         if(delta > 0) {
2883                                 unsigned channel;
2884                                 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
2885                                 for(channel = 0; channel < frame->header.channels; channel++)
2886                                         newbuffer[channel] = buffer[channel] + delta;
2887                                 decoder->private_->last_frame.header.blocksize -= delta;
2888                                 decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
2889                                 /* write the relevant samples */
2890                                 return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
2891                         }
2892                         else {
2893                                 /* write the relevant samples */
2894                                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2895                         }
2896                 }
2897                 else {
2898                         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2899                 }
2900         }
2901         else {
2902                 /*
2903                  * If we never got STREAMINFO, turn off MD5 checking to save
2904                  * cycles since we don't have a sum to compare to anyway
2905                  */
2906                 if(!decoder->private_->has_stream_info)
2907                         decoder->private_->do_md5_checking = false;
2908                 if(decoder->private_->do_md5_checking) {
2909                         if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
2910                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2911                 }
2912                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2913         }
2914 }
2915
2916 void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2917 {
2918         if(!decoder->private_->is_seeking)
2919                 decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
2920         else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
2921                 decoder->private_->unparseable_frame_count++;
2922 }
2923
2924 FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2925 {
2926         FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound;
2927         FLAC__int64 pos = -1, last_pos = -1;
2928         int i, lower_seek_point = -1, upper_seek_point = -1;
2929         unsigned approx_bytes_per_frame;
2930         FLAC__uint64 last_frame_sample = FLAC__U64L(0xffffffffffffffff);
2931         FLAC__bool needs_seek;
2932         const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
2933         const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2934         const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
2935         const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
2936         const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
2937         const unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
2938         const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
2939
2940         /* we are just guessing here, but we want to guess high, not low */
2941         if(max_framesize > 0)
2942                 approx_bytes_per_frame = max_framesize;
2943
2944         /*
2945          * Check if it's a known fixed-blocksize stream.  Note that though
2946          * the spec doesn't allow zeroes in the STREAMINFO block, we may
2947          * never get a STREAMINFO block when decoding so the value of
2948          * min_blocksize might be zero.
2949          */
2950         else if(min_blocksize == max_blocksize && min_blocksize > 0) {
2951                 /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
2952                 approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
2953         }
2954         else
2955                 approx_bytes_per_frame = 4608 * channels * bps/8 + 64;
2956
2957         /*
2958          * First, we set an upper and lower bound on where in the
2959          * stream we will search.  For now we assume the worst case
2960          * scenario, which is our best guess at the beginning of
2961          * the first and last frames.
2962          */
2963         lower_bound = first_frame_offset;
2964
2965         /* calc the upper_bound, beyond which we never want to seek */
2966         if(max_framesize > 0)
2967                 upper_bound = stream_length - (max_framesize + 128 + 2); /* 128 for a possible ID3V1 tag, 2 for indexing differences */
2968         else
2969                 upper_bound = stream_length - ((channels * bps * FLAC__MAX_BLOCK_SIZE) / 8 + 128 + 2);
2970
2971         /*
2972          * Now we refine the bounds if we have a seektable with
2973          * suitable points.  Note that according to the spec they
2974          * must be ordered by ascending sample number.
2975          */
2976         if(seek_table) {
2977                 /* find the closest seek point <= target_sample, if it exists */
2978                 for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
2979                         if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number <= target_sample)
2980                                 break;
2981                 }
2982                 if(i >= 0) { /* i.e. we found a suitable seek point... */
2983                         lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
2984                         lower_seek_point = i;
2985                 }
2986
2987                 /* find the closest seek point > target_sample, if it exists */
2988                 for(i = 0; i < (int)seek_table->num_points; i++) {
2989                         if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number > target_sample)
2990                                 break;
2991                 }
2992                 if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
2993                         upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
2994                         upper_seek_point = i;
2995                 }
2996         }
2997
2998         /*
2999          * Now guess at where within those bounds our target
3000          * sample will be.
3001          */
3002         if(seek_table && lower_seek_point >= 0) {
3003                 /* first see if our sample is within a few frames of the lower seekpoint */
3004                 if(seek_table->points[lower_seek_point].sample_number <= target_sample && target_sample < seek_table->points[lower_seek_point].sample_number + (seek_table->points[lower_seek_point].frame_samples * 4)) {
3005                         pos = (FLAC__int64)lower_bound;
3006                 }
3007                 else if(upper_seek_point >= 0) {
3008                         const FLAC__uint64 target_offset = target_sample - seek_table->points[lower_seek_point].sample_number;
3009                         const FLAC__uint64 range_samples = seek_table->points[upper_seek_point].sample_number - seek_table->points[lower_seek_point].sample_number;
3010                         const FLAC__uint64 range_bytes = (upper_bound>lower_bound? upper_bound - lower_bound - 1 : 0);
3011 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3012 #if defined _MSC_VER || defined __MINGW32__
3013                         /* with MSVC you have to spoon feed it the casting */
3014                         pos = (FLAC__int64)lower_bound + (FLAC__int64)(((FLAC__double)(FLAC__int64)target_offset / (FLAC__double)(FLAC__int64)range_samples) * (FLAC__double)(FLAC__int64)(range_bytes-1)) - approx_bytes_per_frame;
3015 #else
3016                         pos = (FLAC__int64)lower_bound + (FLAC__int64)(((FLAC__double)target_offset / (FLAC__double)range_samples) * (FLAC__double)range_bytes) - approx_bytes_per_frame;
3017 #endif
3018 #else
3019                         /* a little less accurate: */
3020                         if (range_bytes <= 0xffffffff)
3021                                 pos = (FLAC__int64)lower_bound + (FLAC__int64)((target_offset * range_bytes) / range_samples) - approx_bytes_per_frame;
3022                         else /* @@@ WATCHOUT, ~2TB limit */
3023                                 pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_offset>>8) * (range_bytes>>8)) / (range_samples>>16)) - approx_bytes_per_frame;
3024 #endif
3025                 }
3026         }
3027
3028         /*
3029          * If there's no seek table, we need to use the metadata (if we
3030          * have it) and the filelength to estimate the position of the
3031          * frame with the correct sample.
3032          */
3033         if(pos < 0 && total_samples > 0) {
3034                 /*
3035                  * For max accuracy we should be using
3036                  * (stream_length-first_frame_offset-1) in the divisor, but the
3037                  * difference is trivial and (stream_length-first_frame_offset)
3038                  * has no chance of underflow.
3039                  */
3040 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3041 #if defined _MSC_VER || defined __MINGW32__
3042                 /* with VC++ you have to spoon feed it the casting */
3043                 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)(((FLAC__double)(FLAC__int64)target_sample / (FLAC__double)(FLAC__int64)total_samples) * (FLAC__double)(FLAC__int64)(stream_length-first_frame_offset)) - approx_bytes_per_frame;
3044 #else
3045                 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)(((FLAC__double)target_sample / (FLAC__double)total_samples) * (FLAC__double)(stream_length-first_frame_offset)) - approx_bytes_per_frame;
3046 #endif
3047 #else
3048                 /* a little less accurate: */
3049                 if (stream_length < 0xffffffff)
3050                         pos = (FLAC__int64)first_frame_offset + (FLAC__int64)((target_sample * (stream_length-first_frame_offset)) / total_samples) - approx_bytes_per_frame;
3051                 else /* @@@ WATCHOUT, ~2TB limit */
3052                         pos = (FLAC__int64)first_frame_offset + (FLAC__int64)(((target_sample>>8) * ((stream_length-first_frame_offset)>>8)) / (total_samples>>16)) - approx_bytes_per_frame;
3053 #endif
3054         }
3055
3056         /*
3057          * If there's no seek table and total_samples is unknown, we
3058          * don't even bother trying to figure out a target, we just use
3059          * our current position.
3060          */
3061         if(pos < 0) {
3062                 FLAC__uint64 upos;
3063                 if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK) {
3064                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3065                         return false;
3066                 }
3067                 pos = (FLAC__int64)upos;
3068                 needs_seek = false;
3069         }
3070         else
3071                 needs_seek = true;
3072
3073         /* clip the position to the bounds, lower bound takes precedence */
3074         if(pos >= (FLAC__int64)upper_bound) {
3075                 pos = (FLAC__int64)upper_bound-1;
3076                 needs_seek = true;
3077         }
3078         if(pos < (FLAC__int64)lower_bound) {
3079                 pos = (FLAC__int64)lower_bound;
3080                 needs_seek = true;
3081         }
3082
3083         decoder->private_->target_sample = target_sample;
3084         while(1) {
3085                 if(needs_seek) {
3086                         if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3087                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3088                                 return false;
3089                         }
3090                         if(!FLAC__stream_decoder_flush(decoder)) {
3091                                 /* above call sets the state for us */
3092                                 return false;
3093                         }
3094                 }
3095                 /* Now we need to get a frame.  First we need to reset our
3096                  * unparseable_frame_count; if we get too many unparseable
3097                  * frames in a row, the read callback will return
3098                  * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
3099                  * FLAC__stream_decoder_process_single() to return false.
3100                  */
3101                 decoder->private_->unparseable_frame_count = 0;
3102                 if(!FLAC__stream_decoder_process_single(decoder)) {
3103                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3104                         return false;
3105                 }
3106                 /* our write callback will change the state when it gets to the target frame */
3107                 /* 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 */
3108 #if 0
3109                 /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
3110                 if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
3111                         break;
3112 #endif
3113                 if(!decoder->private_->is_seeking) {
3114                         break;
3115                 }
3116                 else { /* we need to narrow the search */
3117                         const FLAC__uint64 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3118                         FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3119                         if(this_frame_sample == last_frame_sample && pos < last_pos) {
3120                                 /* our last move backwards wasn't big enough, double it */
3121                                 pos -= (last_pos - pos);
3122                                 needs_seek = true;
3123                         }
3124                         else {
3125                                 if(target_sample < this_frame_sample) {
3126                                         last_pos = pos;
3127                                         approx_bytes_per_frame = decoder->private_->last_frame.header.blocksize * channels * bps/8 + 64;
3128                                         pos -= approx_bytes_per_frame;
3129                                         needs_seek = true;
3130                                 }
3131                                 else { /* target_sample >= this_frame_sample + this frame's blocksize */
3132                                         FLAC__uint64 upos;
3133                                         if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK) {
3134                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3135                                                 return false;
3136                                         }
3137                                         last_pos = pos;
3138                                         pos = (FLAC__int64)upos;
3139                                         pos -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
3140                                         needs_seek = false;
3141                                         /*
3142                                          * if we haven't hit the target frame yet and our position hasn't changed,
3143                                          * it means we're at the end of the stream and the seek target does not exist.
3144                                          */
3145                                         if(last_pos == pos) {
3146                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3147                                                 return false;
3148                                         }
3149                                 }
3150                         }
3151                         if(pos < (FLAC__int64)lower_bound)
3152                                 pos = (FLAC__int64)lower_bound;
3153                         last_frame_sample = this_frame_sample;
3154                 }
3155         }
3156
3157         return true;
3158 }
3159
3160 #ifdef FLAC__HAS_OGG
3161 FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
3162 {
3163         FLAC__uint64 left_pos = 0, right_pos = stream_length;
3164         FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
3165         FLAC__uint64 this_frame_sample = 0; /* only initialized to avoid compiler warning */
3166         FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
3167         FLAC__bool did_a_seek;
3168         unsigned iteration = 0;
3169
3170         /* In the first iterations, we will calculate the target byte position 
3171          * by the distance from the target sample to left_sample and
3172          * right_sample (let's call it "proportional search").  After that, we
3173          * will switch to binary search.
3174          */
3175         unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
3176
3177         /* We will switch to a linear search once our current sample is less
3178          * than this number of samples ahead of the target sample
3179          */
3180         static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
3181
3182         /* If the total number of samples is unknown, use a large value, and
3183          * force binary search immediately.
3184          */
3185         if(right_sample == 0) {
3186                 right_sample = (FLAC__uint64)(-1);
3187                 BINARY_SEARCH_AFTER_ITERATION = 0;
3188         }
3189
3190         decoder->private_->target_sample = target_sample;
3191         for( ; ; iteration++) {
3192                 if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
3193                         if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
3194                                 pos = (right_pos + left_pos) / 2;
3195                         }
3196                         else {
3197 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3198 #if defined _MSC_VER || defined __MINGW32__
3199                                 /* with MSVC you have to spoon feed it the casting */
3200                                 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));
3201 #else
3202                                 pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
3203 #endif
3204 #else
3205                                 /* a little less accurate: */
3206                                 if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
3207                                         pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
3208                                 else /* @@@ WATCHOUT, ~2TB limit */
3209                                         pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
3210 #endif
3211                                 /* @@@ TODO: might want to limit pos to some distance
3212                                  * before EOF, to make sure we land before the last frame,
3213                                  * thereby getting a this_frame_sample and so having a better
3214                                  * estimate.  @@@@@@DELETE:this would also mostly (or totally if we could
3215                                  * be sure to land before the last frame) avoid the
3216                                  * end-of-stream case we have to check later.
3217                                  */
3218                         }
3219
3220                         /* physical seek */
3221                         if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3222                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3223                                 return false;
3224                         }
3225                         if(!FLAC__stream_decoder_flush(decoder)) {
3226                                 /* above call sets the state for us */
3227                                 return false;
3228                         }
3229                         did_a_seek = true;
3230                 }
3231                 else
3232                         did_a_seek = false;
3233
3234                 decoder->private_->got_a_frame = false;
3235                 if(!FLAC__stream_decoder_process_single(decoder)) {
3236                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3237                         return false;
3238                 }
3239                 if(!decoder->private_->got_a_frame) {
3240                         if(did_a_seek) {
3241                                 /* this can happen if we seek to a point after the last frame; we drop
3242                                  * to binary search right away in this case to avoid any wasted
3243                                  * iterations of proportional search.
3244                                  */
3245                                 right_pos = pos;
3246                                 BINARY_SEARCH_AFTER_ITERATION = 0;
3247                         }
3248                         else {
3249                                 /* this can probably only happen if total_samples is unknown and the
3250                                  * target_sample is past the end of the stream
3251                                  */
3252                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3253                                 return false;
3254                         }
3255                 }
3256                 /* our write callback will change the state when it gets to the target frame */
3257                 else if(!decoder->private_->is_seeking/*@@@@@@ && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM*/) {
3258                         break;
3259                 }
3260                 else {
3261                         this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3262                         FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3263
3264                         if (did_a_seek) {
3265                                 if (this_frame_sample <= target_sample) {
3266                                         /* The 'equal' case should not happen, since
3267                                          * FLAC__stream_decoder_process_single()
3268                                          * should recognize that it has hit the
3269                                          * target sample and we would exit through
3270                                          * the 'break' above.
3271                                          */
3272                                         FLAC__ASSERT(this_frame_sample != target_sample);
3273
3274                                         left_sample = this_frame_sample;
3275                                         /* sanity check to avoid infinite loop */
3276                                         if (left_pos == pos) {
3277                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3278                                                 return false;
3279                                         }
3280                                         left_pos = pos;
3281                                 }
3282                                 else if(this_frame_sample > target_sample) {
3283                                         right_sample = this_frame_sample;
3284                                         /* sanity check to avoid infinite loop */
3285                                         if (right_pos == pos) {
3286                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3287                                                 return false;
3288                                         }
3289                                         right_pos = pos;
3290                                 }
3291                         }
3292                 }
3293         }
3294
3295         return true;
3296 }
3297 #endif
3298
3299 FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
3300 {
3301         (void)client_data;
3302
3303         if(*bytes > 0) {
3304                 *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
3305                 if(ferror(decoder->private_->file))
3306                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
3307                 else if(*bytes == 0)
3308                         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
3309                 else
3310                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
3311         }
3312         else
3313                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
3314 }
3315
3316 FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
3317 {
3318         (void)client_data;
3319
3320         if(decoder->private_->file == stdin)
3321                 return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
3322         else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
3323                 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
3324         else
3325                 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
3326 }
3327
3328 FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
3329 {
3330         off_t pos;
3331         (void)client_data;
3332
3333         if(decoder->private_->file == stdin)
3334                 return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
3335         else if((pos = ftello(decoder->private_->file)) < 0)
3336                 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
3337         else {
3338                 *absolute_byte_offset = (FLAC__uint64)pos;
3339                 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
3340         }
3341 }
3342
3343 FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
3344 {
3345         struct stat filestats;
3346         (void)client_data;
3347
3348         if(decoder->private_->file == stdin)
3349                 return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
3350         else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
3351                 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
3352         else {
3353                 *stream_length = (FLAC__uint64)filestats.st_size;
3354                 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
3355         }
3356 }
3357
3358 FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
3359 {
3360         (void)client_data;
3361
3362         return feof(decoder->private_->file)? true : false;
3363 }