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