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