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