be more precise in long long int literal specification for ANSI compilers (gcc3 requi...
[flac.git] / src / libFLAC / stream_decoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002,2003,2004  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 #include <stdio.h>
33 #include <stdlib.h> /* for malloc() */
34 #include <string.h> /* for memset/memcpy() */
35 #include "FLAC/assert.h"
36 #include "protected/stream_decoder.h"
37 #include "private/bitbuffer.h"
38 #include "private/bitmath.h"
39 #include "private/cpu.h"
40 #include "private/crc.h"
41 #include "private/fixed.h"
42 #include "private/format.h"
43 #include "private/lpc.h"
44 #include "private/memory.h"
45
46 #ifdef HAVE_CONFIG_H
47 #include <config.h>
48 #endif
49
50 #ifdef max
51 #undef max
52 #endif
53 #define max(a,b) ((a)>(b)?(a):(b))
54
55 /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
56 #ifdef _MSC_VER
57 #define FLAC__U64L(x) x
58 #else
59 #define FLAC__U64L(x) x##LLU
60 #endif
61
62 /***********************************************************************
63  *
64  * Private static data
65  *
66  ***********************************************************************/
67
68 static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
69
70 /***********************************************************************
71  *
72  * Private class method prototypes
73  *
74  ***********************************************************************/
75
76 static void set_defaults_(FLAC__StreamDecoder *decoder);
77 static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
78 static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
79 static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
80 static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
81 static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
82 static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
83 static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
84 static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
85 static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
86 static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
87 static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
88 static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
89 static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
90 static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
91 static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
92 static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
93 static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
94 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);
95 static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
96 static FLAC__bool read_callback_(FLAC__byte buffer[], unsigned *bytes, void *client_data);
97
98 /***********************************************************************
99  *
100  * Private class data
101  *
102  ***********************************************************************/
103
104 typedef struct FLAC__StreamDecoderPrivate {
105         FLAC__StreamDecoderReadCallback read_callback;
106         FLAC__StreamDecoderWriteCallback write_callback;
107         FLAC__StreamDecoderMetadataCallback metadata_callback;
108         FLAC__StreamDecoderErrorCallback error_callback;
109         /* generic 32-bit datapath: */
110         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[]);
111         /* generic 64-bit datapath: */
112         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[]);
113         /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
114         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[]);
115         /* 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: */
116         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[]);
117         void *client_data;
118         FLAC__BitBuffer *input;
119         FLAC__int32 *output[FLAC__MAX_CHANNELS];
120         FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
121         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
122         unsigned output_capacity, output_channels;
123         FLAC__uint32 last_frame_number;
124         FLAC__uint64 samples_decoded;
125         FLAC__bool has_stream_info, has_seek_table;
126         FLAC__StreamMetadata stream_info;
127         FLAC__StreamMetadata seek_table;
128         FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
129         FLAC__byte *metadata_filter_ids;
130         unsigned metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
131         FLAC__Frame frame;
132         FLAC__bool cached; /* true if there is a byte in lookahead */
133         FLAC__CPUInfo cpuinfo;
134         FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
135         FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
136         /* unaligned (original) pointers to allocated data */
137         FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
138 } FLAC__StreamDecoderPrivate;
139
140 /***********************************************************************
141  *
142  * Public static class data
143  *
144  ***********************************************************************/
145
146 FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
147         "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
148         "FLAC__STREAM_DECODER_READ_METADATA",
149         "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
150         "FLAC__STREAM_DECODER_READ_FRAME",
151         "FLAC__STREAM_DECODER_END_OF_STREAM",
152         "FLAC__STREAM_DECODER_ABORTED",
153         "FLAC__STREAM_DECODER_UNPARSEABLE_STREAM",
154         "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
155         "FLAC__STREAM_DECODER_ALREADY_INITIALIZED",
156         "FLAC__STREAM_DECODER_INVALID_CALLBACK",
157         "FLAC__STREAM_DECODER_UNINITIALIZED"
158 };
159
160 FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
161         "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
162         "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
163         "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
164 };
165
166 FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
167         "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
168         "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
169 };
170
171 FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
172         "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
173         "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
174         "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH"
175 };
176
177 /***********************************************************************
178  *
179  * Class constructor/destructor
180  *
181  ***********************************************************************/
182 FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new()
183 {
184         FLAC__StreamDecoder *decoder;
185         unsigned i;
186
187         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
188
189         decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
190         if(decoder == 0) {
191                 return 0;
192         }
193
194         decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
195         if(decoder->protected_ == 0) {
196                 free(decoder);
197                 return 0;
198         }
199
200         decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
201         if(decoder->private_ == 0) {
202                 free(decoder->protected_);
203                 free(decoder);
204                 return 0;
205         }
206
207         decoder->private_->input = FLAC__bitbuffer_new();
208         if(decoder->private_->input == 0) {
209                 free(decoder->private_);
210                 free(decoder->protected_);
211                 free(decoder);
212                 return 0;
213         }
214
215         decoder->private_->metadata_filter_ids_capacity = 16;
216         if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
217                 FLAC__bitbuffer_delete(decoder->private_->input);
218                 free(decoder->private_);
219                 free(decoder->protected_);
220                 free(decoder);
221                 return 0;
222         }
223
224         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
225                 decoder->private_->output[i] = 0;
226                 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
227         }
228
229         decoder->private_->output_capacity = 0;
230         decoder->private_->output_channels = 0;
231         decoder->private_->has_seek_table = false;
232
233         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
234                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
235
236         set_defaults_(decoder);
237
238         decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
239
240         return decoder;
241 }
242
243 FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
244 {
245         unsigned i;
246
247         FLAC__ASSERT(0 != decoder);
248         FLAC__ASSERT(0 != decoder->protected_);
249         FLAC__ASSERT(0 != decoder->private_);
250         FLAC__ASSERT(0 != decoder->private_->input);
251
252         FLAC__stream_decoder_finish(decoder);
253
254         if(0 != decoder->private_->metadata_filter_ids)
255                 free(decoder->private_->metadata_filter_ids);
256
257         FLAC__bitbuffer_delete(decoder->private_->input);
258
259         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
260                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
261
262         free(decoder->private_);
263         free(decoder->protected_);
264         free(decoder);
265 }
266
267 /***********************************************************************
268  *
269  * Public class methods
270  *
271  ***********************************************************************/
272
273 FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_init(FLAC__StreamDecoder *decoder)
274 {
275         FLAC__ASSERT(0 != decoder);
276
277         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
278                 return decoder->protected_->state = FLAC__STREAM_DECODER_ALREADY_INITIALIZED;
279
280         if(0 == decoder->private_->read_callback || 0 == decoder->private_->write_callback || 0 == decoder->private_->metadata_callback || 0 == decoder->private_->error_callback)
281                 return decoder->protected_->state = FLAC__STREAM_DECODER_INVALID_CALLBACK;
282
283         if(!FLAC__bitbuffer_init(decoder->private_->input))
284                 return decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
285
286         decoder->private_->last_frame_number = 0;
287         decoder->private_->samples_decoded = 0;
288         decoder->private_->has_stream_info = false;
289         decoder->private_->cached = false;
290
291         /*
292          * get the CPU info and set the function pointers
293          */
294         FLAC__cpu_info(&decoder->private_->cpuinfo);
295         /* first default to the non-asm routines */
296         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
297         decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
298         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
299         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
300         /* now override with asm where appropriate */
301 #ifndef FLAC__NO_ASM
302         if(decoder->private_->cpuinfo.use_asm) {
303 #ifdef FLAC__CPU_IA32
304                 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
305 #ifdef FLAC__HAS_NASM
306                 if(decoder->private_->cpuinfo.data.ia32.mmx) {
307                         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
308                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
309                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
310                 }
311                 else {
312                         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
313                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
314                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
315                 }
316 #endif
317 #elif defined FLAC__CPU_PPC
318                 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
319                 if(decoder->private_->cpuinfo.data.ppc.altivec) {
320                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
321                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
322                 }
323 #endif
324         }
325 #endif
326
327         if(!FLAC__stream_decoder_reset(decoder))
328                 return decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
329
330         return decoder->protected_->state;
331 }
332
333 FLAC_API void FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
334 {
335         unsigned i;
336         FLAC__ASSERT(0 != decoder);
337         if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
338                 return;
339         if(0 != decoder->private_->seek_table.data.seek_table.points) {
340                 free(decoder->private_->seek_table.data.seek_table.points);
341                 decoder->private_->seek_table.data.seek_table.points = 0;
342                 decoder->private_->has_seek_table = false;
343         }
344         FLAC__bitbuffer_free(decoder->private_->input);
345         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
346                 /* WATCHOUT:
347                  * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
348                  * output arrays have a buffer of up to 3 zeroes in front
349                  * (at negative indices) for alignment purposes; we use 4
350                  * to keep the data well-aligned.
351                  */
352                 if(0 != decoder->private_->output[i]) {
353                         free(decoder->private_->output[i]-4);
354                         decoder->private_->output[i] = 0;
355                 }
356                 if(0 != decoder->private_->residual_unaligned[i]) {
357                         free(decoder->private_->residual_unaligned[i]);
358                         decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
359                 }
360         }
361         decoder->private_->output_capacity = 0;
362         decoder->private_->output_channels = 0;
363
364         set_defaults_(decoder);
365
366         decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
367 }
368
369 FLAC_API FLAC__bool FLAC__stream_decoder_set_read_callback(FLAC__StreamDecoder *decoder, FLAC__StreamDecoderReadCallback value)
370 {
371         FLAC__ASSERT(0 != decoder);
372         FLAC__ASSERT(0 != decoder->private_);
373         FLAC__ASSERT(0 != decoder->protected_);
374         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
375                 return false;
376         decoder->private_->read_callback = value;
377         return true;
378 }
379
380 FLAC_API FLAC__bool FLAC__stream_decoder_set_write_callback(FLAC__StreamDecoder *decoder, FLAC__StreamDecoderWriteCallback value)
381 {
382         FLAC__ASSERT(0 != decoder);
383         FLAC__ASSERT(0 != decoder->private_);
384         FLAC__ASSERT(0 != decoder->protected_);
385         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
386                 return false;
387         decoder->private_->write_callback = value;
388         return true;
389 }
390
391 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_callback(FLAC__StreamDecoder *decoder, FLAC__StreamDecoderMetadataCallback value)
392 {
393         FLAC__ASSERT(0 != decoder);
394         FLAC__ASSERT(0 != decoder->private_);
395         FLAC__ASSERT(0 != decoder->protected_);
396         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
397                 return false;
398         decoder->private_->metadata_callback = value;
399         return true;
400 }
401
402 FLAC_API FLAC__bool FLAC__stream_decoder_set_error_callback(FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorCallback value)
403 {
404         FLAC__ASSERT(0 != decoder);
405         FLAC__ASSERT(0 != decoder->private_);
406         FLAC__ASSERT(0 != decoder->protected_);
407         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
408                 return false;
409         decoder->private_->error_callback = value;
410         return true;
411 }
412
413 FLAC_API FLAC__bool FLAC__stream_decoder_set_client_data(FLAC__StreamDecoder *decoder, void *value)
414 {
415         FLAC__ASSERT(0 != decoder);
416         FLAC__ASSERT(0 != decoder->private_);
417         FLAC__ASSERT(0 != decoder->protected_);
418         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
419                 return false;
420         decoder->private_->client_data = value;
421         return true;
422 }
423
424 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
425 {
426         FLAC__ASSERT(0 != decoder);
427         FLAC__ASSERT(0 != decoder->private_);
428         FLAC__ASSERT(0 != decoder->protected_);
429         FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
430         /* double protection */
431         if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
432                 return false;
433         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
434                 return false;
435         decoder->private_->metadata_filter[type] = true;
436         if(type == FLAC__METADATA_TYPE_APPLICATION)
437                 decoder->private_->metadata_filter_ids_count = 0;
438         return true;
439 }
440
441 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
442 {
443         FLAC__ASSERT(0 != decoder);
444         FLAC__ASSERT(0 != decoder->private_);
445         FLAC__ASSERT(0 != decoder->protected_);
446         FLAC__ASSERT(0 != id);
447         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
448                 return false;
449
450         if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
451                 return true;
452
453         FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
454
455         if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
456                 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2)))
457                         return decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
458                 decoder->private_->metadata_filter_ids_capacity *= 2;
459         }
460
461         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));
462         decoder->private_->metadata_filter_ids_count++;
463
464         return true;
465 }
466
467 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
468 {
469         unsigned i;
470         FLAC__ASSERT(0 != decoder);
471         FLAC__ASSERT(0 != decoder->private_);
472         FLAC__ASSERT(0 != decoder->protected_);
473         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
474                 return false;
475         for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
476                 decoder->private_->metadata_filter[i] = true;
477         decoder->private_->metadata_filter_ids_count = 0;
478         return true;
479 }
480
481 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
482 {
483         FLAC__ASSERT(0 != decoder);
484         FLAC__ASSERT(0 != decoder->private_);
485         FLAC__ASSERT(0 != decoder->protected_);
486         FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
487         /* double protection */
488         if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
489                 return false;
490         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
491                 return false;
492         decoder->private_->metadata_filter[type] = false;
493         if(type == FLAC__METADATA_TYPE_APPLICATION)
494                 decoder->private_->metadata_filter_ids_count = 0;
495         return true;
496 }
497
498 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
499 {
500         FLAC__ASSERT(0 != decoder);
501         FLAC__ASSERT(0 != decoder->private_);
502         FLAC__ASSERT(0 != decoder->protected_);
503         FLAC__ASSERT(0 != id);
504         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
505                 return false;
506
507         if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
508                 return true;
509
510         FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
511
512         if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
513                 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2)))
514                         return decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
515                 decoder->private_->metadata_filter_ids_capacity *= 2;
516         }
517
518         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));
519         decoder->private_->metadata_filter_ids_count++;
520
521         return true;
522 }
523
524 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
525 {
526         FLAC__ASSERT(0 != decoder);
527         FLAC__ASSERT(0 != decoder->private_);
528         FLAC__ASSERT(0 != decoder->protected_);
529         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
530                 return false;
531         memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
532         decoder->private_->metadata_filter_ids_count = 0;
533         return true;
534 }
535
536 FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
537 {
538         FLAC__ASSERT(0 != decoder);
539         FLAC__ASSERT(0 != decoder->protected_);
540         return decoder->protected_->state;
541 }
542
543 FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
544 {
545         return FLAC__StreamDecoderStateString[decoder->protected_->state];
546 }
547
548 FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
549 {
550         FLAC__ASSERT(0 != decoder);
551         FLAC__ASSERT(0 != decoder->protected_);
552         return decoder->protected_->channels;
553 }
554
555 FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
556 {
557         FLAC__ASSERT(0 != decoder);
558         FLAC__ASSERT(0 != decoder->protected_);
559         return decoder->protected_->channel_assignment;
560 }
561
562 FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
563 {
564         FLAC__ASSERT(0 != decoder);
565         FLAC__ASSERT(0 != decoder->protected_);
566         return decoder->protected_->bits_per_sample;
567 }
568
569 FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
570 {
571         FLAC__ASSERT(0 != decoder);
572         FLAC__ASSERT(0 != decoder->protected_);
573         return decoder->protected_->sample_rate;
574 }
575
576 FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
577 {
578         FLAC__ASSERT(0 != decoder);
579         FLAC__ASSERT(0 != decoder->protected_);
580         return decoder->protected_->blocksize;
581 }
582
583 FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
584 {
585         FLAC__ASSERT(0 != decoder);
586         FLAC__ASSERT(0 != decoder->private_);
587         FLAC__ASSERT(0 != decoder->protected_);
588
589         if(!FLAC__bitbuffer_clear(decoder->private_->input)) {
590                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
591                 return false;
592         }
593         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
594
595         return true;
596 }
597
598 FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
599 {
600         FLAC__ASSERT(0 != decoder);
601         FLAC__ASSERT(0 != decoder->private_);
602         FLAC__ASSERT(0 != decoder->protected_);
603
604         if(!FLAC__stream_decoder_flush(decoder)) {
605                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
606                 return false;
607         }
608         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
609
610         decoder->private_->samples_decoded = 0;
611
612         return true;
613 }
614
615 FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
616 {
617         FLAC__bool got_a_frame;
618         FLAC__ASSERT(0 != decoder);
619         FLAC__ASSERT(0 != decoder->protected_);
620
621         while(1) {
622                 switch(decoder->protected_->state) {
623                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
624                                 if(!find_metadata_(decoder))
625                                         return false; /* above function sets the status for us */
626                                 break;
627                         case FLAC__STREAM_DECODER_READ_METADATA:
628                                 if(!read_metadata_(decoder))
629                                         return false; /* above function sets the status for us */
630                                 else
631                                         return true;
632                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
633                                 if(!frame_sync_(decoder))
634                                         return true; /* above function sets the status for us */
635                                 break;
636                         case FLAC__STREAM_DECODER_READ_FRAME:
637                                 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
638                                         return false; /* above function sets the status for us */
639                                 if(got_a_frame)
640                                         return true; /* above function sets the status for us */
641                                 break;
642                         case FLAC__STREAM_DECODER_END_OF_STREAM:
643                         case FLAC__STREAM_DECODER_ABORTED:
644                                 return true;
645                         default:
646                                 FLAC__ASSERT(0);
647                                 return false;
648                 }
649         }
650 }
651
652 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
653 {
654         FLAC__ASSERT(0 != decoder);
655         FLAC__ASSERT(0 != decoder->protected_);
656
657         while(1) {
658                 switch(decoder->protected_->state) {
659                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
660                                 if(!find_metadata_(decoder))
661                                         return false; /* above function sets the status for us */
662                                 break;
663                         case FLAC__STREAM_DECODER_READ_METADATA:
664                                 if(!read_metadata_(decoder))
665                                         return false; /* above function sets the status for us */
666                                 break;
667                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
668                         case FLAC__STREAM_DECODER_READ_FRAME:
669                         case FLAC__STREAM_DECODER_END_OF_STREAM:
670                         case FLAC__STREAM_DECODER_ABORTED:
671                                 return true;
672                         default:
673                                 FLAC__ASSERT(0);
674                                 return false;
675                 }
676         }
677 }
678
679 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
680 {
681         FLAC__bool dummy;
682         FLAC__ASSERT(0 != decoder);
683         FLAC__ASSERT(0 != decoder->protected_);
684
685         while(1) {
686                 switch(decoder->protected_->state) {
687                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
688                                 if(!find_metadata_(decoder))
689                                         return false; /* above function sets the status for us */
690                                 break;
691                         case FLAC__STREAM_DECODER_READ_METADATA:
692                                 if(!read_metadata_(decoder))
693                                         return false; /* above function sets the status for us */
694                                 break;
695                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
696                                 if(!frame_sync_(decoder))
697                                         return true; /* above function sets the status for us */
698                                 break;
699                         case FLAC__STREAM_DECODER_READ_FRAME:
700                                 if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
701                                         return false; /* above function sets the status for us */
702                                 break;
703                         case FLAC__STREAM_DECODER_END_OF_STREAM:
704                         case FLAC__STREAM_DECODER_ABORTED:
705                                 return true;
706                         default:
707                                 FLAC__ASSERT(0);
708                                 return false;
709                 }
710         }
711 }
712
713 FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
714 {
715         FLAC__bool got_a_frame;
716         FLAC__ASSERT(0 != decoder);
717         FLAC__ASSERT(0 != decoder->protected_);
718
719         while(1) {
720                 switch(decoder->protected_->state) {
721                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
722                         case FLAC__STREAM_DECODER_READ_METADATA:
723                                 return false; /* above function sets the status for us */
724                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
725                                 if(!frame_sync_(decoder))
726                                         return true; /* above function sets the status for us */
727                                 break;
728                         case FLAC__STREAM_DECODER_READ_FRAME:
729                                 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
730                                         return false; /* above function sets the status for us */
731                                 if(got_a_frame)
732                                         return true; /* above function sets the status for us */
733                                 break;
734                         case FLAC__STREAM_DECODER_END_OF_STREAM:
735                         case FLAC__STREAM_DECODER_ABORTED:
736                                 return true;
737                         default:
738                                 FLAC__ASSERT(0);
739                                 return false;
740                 }
741         }
742 }
743
744 /***********************************************************************
745  *
746  * Protected class methods
747  *
748  ***********************************************************************/
749
750 unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
751 {
752         FLAC__ASSERT(0 != decoder);
753         return FLAC__bitbuffer_get_input_bytes_unconsumed(decoder->private_->input);
754 }
755
756 /***********************************************************************
757  *
758  * Private class methods
759  *
760  ***********************************************************************/
761
762 void set_defaults_(FLAC__StreamDecoder *decoder)
763 {
764         decoder->private_->read_callback = 0;
765         decoder->private_->write_callback = 0;
766         decoder->private_->metadata_callback = 0;
767         decoder->private_->error_callback = 0;
768         decoder->private_->client_data = 0;
769
770         memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
771         decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
772         decoder->private_->metadata_filter_ids_count = 0;
773 }
774
775 FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
776 {
777         unsigned i;
778         FLAC__int32 *tmp;
779
780         if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
781                 return true;
782
783         /* simply using realloc() is not practical because the number of channels may change mid-stream */
784
785         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
786                 if(0 != decoder->private_->output[i]) {
787                         free(decoder->private_->output[i]-4);
788                         decoder->private_->output[i] = 0;
789                 }
790                 if(0 != decoder->private_->residual_unaligned[i]) {
791                         free(decoder->private_->residual_unaligned[i]);
792                         decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
793                 }
794         }
795
796         for(i = 0; i < channels; i++) {
797                 /* WATCHOUT:
798                  * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
799                  * output arrays have a buffer of up to 3 zeroes in front
800                  * (at negative indices) for alignment purposes; we use 4
801                  * to keep the data well-aligned.
802                  */
803                 tmp = (FLAC__int32*)malloc(sizeof(FLAC__int32)*(size+4));
804                 if(tmp == 0) {
805                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
806                         return false;
807                 }
808                 memset(tmp, 0, sizeof(FLAC__int32)*4);
809                 decoder->private_->output[i] = tmp + 4;
810
811                 /* WATCHOUT:
812                  * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
813                  */
814                 if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
815                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
816                         return false;
817                 }
818         }
819
820         decoder->private_->output_capacity = size;
821         decoder->private_->output_channels = channels;
822
823         return true;
824 }
825
826 FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
827 {
828         unsigned i;
829
830         FLAC__ASSERT(0 != decoder);
831         FLAC__ASSERT(0 != decoder->private_);
832
833         for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
834                 if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
835                         return true;
836
837         return false;
838 }
839
840 FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
841 {
842         FLAC__uint32 x;
843         unsigned i, id;
844         FLAC__bool first = true;
845
846         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
847
848         for(i = id = 0; i < 4; ) {
849                 if(decoder->private_->cached) {
850                         x = (FLAC__uint32)decoder->private_->lookahead;
851                         decoder->private_->cached = false;
852                 }
853                 else {
854                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
855                                 return false; /* the read_callback_ sets the state for us */
856                 }
857                 if(x == FLAC__STREAM_SYNC_STRING[i]) {
858                         first = true;
859                         i++;
860                         id = 0;
861                         continue;
862                 }
863                 if(x == ID3V2_TAG_[id]) {
864                         id++;
865                         i = 0;
866                         if(id == 3) {
867                                 if(!skip_id3v2_tag_(decoder))
868                                         return false; /* the read_callback_ sets the state for us */
869                         }
870                         continue;
871                 }
872                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
873                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
874                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
875                                 return false; /* the read_callback_ sets the state for us */
876
877                         /* 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 */
878                         /* else we have to check if the second byte is the end of a sync code */
879                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
880                                 decoder->private_->lookahead = (FLAC__byte)x;
881                                 decoder->private_->cached = true;
882                         }
883                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
884                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
885                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
886                                 return true;
887                         }
888                 }
889                 i = 0;
890                 if(first) {
891                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, decoder->private_->client_data);
892                         first = false;
893                 }
894         }
895
896         decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
897         return true;
898 }
899
900 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
901 {
902         FLAC__bool is_last;
903         FLAC__uint32 i, x, type, length;
904
905         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
906
907         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN, read_callback_, decoder))
908                 return false; /* the read_callback_ sets the state for us */
909         is_last = x? true : false;
910
911         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN, read_callback_, decoder))
912                 return false; /* the read_callback_ sets the state for us */
913
914         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN, read_callback_, decoder))
915                 return false; /* the read_callback_ sets the state for us */
916
917         if(type == FLAC__METADATA_TYPE_STREAMINFO) {
918                 if(!read_metadata_streaminfo_(decoder, is_last, length))
919                         return false;
920
921                 decoder->private_->has_stream_info = true;
922                 if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO])
923                         decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
924         }
925         else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
926                 if(!read_metadata_seektable_(decoder, is_last, length))
927                         return false;
928
929                 decoder->private_->has_seek_table = true;
930                 if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE])
931                         decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
932         }
933         else {
934                 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
935                 unsigned real_length = length;
936                 FLAC__StreamMetadata block;
937
938                 block.is_last = is_last;
939                 block.type = (FLAC__MetadataType)type;
940                 block.length = length;
941
942                 if(type == FLAC__METADATA_TYPE_APPLICATION) {
943                         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))
944                                 return false; /* the read_callback_ sets the state for us */
945
946                         real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
947
948                         if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
949                                 skip_it = !skip_it;
950                 }
951
952                 if(skip_it) {
953                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
954                                 return false; /* the read_callback_ sets the state for us */
955                 }
956                 else {
957                         switch(type) {
958                                 case FLAC__METADATA_TYPE_PADDING:
959                                         /* skip the padding bytes */
960                                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
961                                                 return false; /* the read_callback_ sets the state for us */
962                                         break;
963                                 case FLAC__METADATA_TYPE_APPLICATION:
964                                         /* remember, we read the ID already */
965                                         if(real_length > 0) {
966                                                 if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
967                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
968                                                         return false;
969                                                 }
970                                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length, read_callback_, decoder))
971                                                         return false; /* the read_callback_ sets the state for us */
972                                         }
973                                         else
974                                                 block.data.application.data = 0;
975                                         break;
976                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
977                                         if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
978                                                 return false;
979                                         break;
980                                 case FLAC__METADATA_TYPE_CUESHEET:
981                                         if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
982                                                 return false;
983                                         break;
984                                 case FLAC__METADATA_TYPE_STREAMINFO:
985                                 case FLAC__METADATA_TYPE_SEEKTABLE:
986                                         FLAC__ASSERT(0);
987                                         break;
988                                 default:
989                                         if(real_length > 0) {
990                                                 if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
991                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
992                                                         return false;
993                                                 }
994                                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length, read_callback_, decoder))
995                                                         return false; /* the read_callback_ sets the state for us */
996                                         }
997                                         else
998                                                 block.data.unknown.data = 0;
999                                         break;
1000                         }
1001                         decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1002
1003                         /* now we have to free any malloc'ed data in the block */
1004                         switch(type) {
1005                                 case FLAC__METADATA_TYPE_PADDING:
1006                                         break;
1007                                 case FLAC__METADATA_TYPE_APPLICATION:
1008                                         if(0 != block.data.application.data)
1009                                                 free(block.data.application.data);
1010                                         break;
1011                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1012                                         if(0 != block.data.vorbis_comment.vendor_string.entry)
1013                                                 free(block.data.vorbis_comment.vendor_string.entry);
1014                                         if(block.data.vorbis_comment.num_comments > 0)
1015                                                 for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
1016                                                         if(0 != block.data.vorbis_comment.comments[i].entry)
1017                                                                 free(block.data.vorbis_comment.comments[i].entry);
1018                                         if(0 != block.data.vorbis_comment.comments)
1019                                                 free(block.data.vorbis_comment.comments);
1020                                         break;
1021                                 case FLAC__METADATA_TYPE_CUESHEET:
1022                                         if(block.data.cue_sheet.num_tracks > 0)
1023                                                 for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
1024                                                         if(0 != block.data.cue_sheet.tracks[i].indices)
1025                                                                 free(block.data.cue_sheet.tracks[i].indices);
1026                                         if(0 != block.data.cue_sheet.tracks)
1027                                                 free(block.data.cue_sheet.tracks);
1028                                         break;
1029                                 case FLAC__METADATA_TYPE_STREAMINFO:
1030                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1031                                         FLAC__ASSERT(0);
1032                                 default:
1033                                         if(0 != block.data.unknown.data)
1034                                                 free(block.data.unknown.data);
1035                                         break;
1036                         }
1037                 }
1038         }
1039
1040         if(is_last)
1041                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1042
1043         return true;
1044 }
1045
1046 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1047 {
1048         FLAC__uint32 x;
1049         unsigned bits, used_bits = 0;
1050
1051         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1052
1053         decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
1054         decoder->private_->stream_info.is_last = is_last;
1055         decoder->private_->stream_info.length = length;
1056
1057         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1058         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, bits, read_callback_, decoder))
1059                 return false; /* the read_callback_ sets the state for us */
1060         decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1061         used_bits += bits;
1062
1063         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1064         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN, read_callback_, decoder))
1065                 return false; /* the read_callback_ sets the state for us */
1066         decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1067         used_bits += bits;
1068
1069         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1070         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN, read_callback_, decoder))
1071                 return false; /* the read_callback_ sets the state for us */
1072         decoder->private_->stream_info.data.stream_info.min_framesize = x;
1073         used_bits += bits;
1074
1075         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1076         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN, read_callback_, decoder))
1077                 return false; /* the read_callback_ sets the state for us */
1078         decoder->private_->stream_info.data.stream_info.max_framesize = x;
1079         used_bits += bits;
1080
1081         bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1082         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN, read_callback_, decoder))
1083                 return false; /* the read_callback_ sets the state for us */
1084         decoder->private_->stream_info.data.stream_info.sample_rate = x;
1085         used_bits += bits;
1086
1087         bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1088         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN, read_callback_, decoder))
1089                 return false; /* the read_callback_ sets the state for us */
1090         decoder->private_->stream_info.data.stream_info.channels = x+1;
1091         used_bits += bits;
1092
1093         bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1094         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN, read_callback_, decoder))
1095                 return false; /* the read_callback_ sets the state for us */
1096         decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1097         used_bits += bits;
1098
1099         bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1100         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))
1101                 return false; /* the read_callback_ sets the state for us */
1102         used_bits += bits;
1103
1104         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16, read_callback_, decoder))
1105                 return false; /* the read_callback_ sets the state for us */
1106         used_bits += 16*8;
1107
1108         /* skip the rest of the block */
1109         FLAC__ASSERT(used_bits % 8 == 0);
1110         length -= (used_bits / 8);
1111         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1112                 return false; /* the read_callback_ sets the state for us */
1113
1114         return true;
1115 }
1116
1117 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1118 {
1119         FLAC__uint32 i, x;
1120         FLAC__uint64 xx;
1121
1122         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1123
1124         decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1125         decoder->private_->seek_table.is_last = is_last;
1126         decoder->private_->seek_table.length = length;
1127
1128         decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1129
1130         /* use realloc since we may pass through here several times (e.g. after seeking) */
1131         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)))) {
1132                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1133                 return false;
1134         }
1135         for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1136                 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN, read_callback_, decoder))
1137                         return false; /* the read_callback_ sets the state for us */
1138                 decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1139
1140                 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN, read_callback_, decoder))
1141                         return false; /* the read_callback_ sets the state for us */
1142                 decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1143
1144                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN, read_callback_, decoder))
1145                         return false; /* the read_callback_ sets the state for us */
1146                 decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1147         }
1148         length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1149         /* if there is a partial point left, skip over it */
1150         if(length > 0) {
1151                 /*@@@ do an error_callback() here?  there's an argument for either way */
1152                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1153                         return false; /* the read_callback_ sets the state for us */
1154         }
1155
1156         return true;
1157 }
1158
1159 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1160 {
1161         FLAC__uint32 i;
1162
1163         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1164
1165         /* read vendor string */
1166         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1167         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length, read_callback_, decoder))
1168                 return false; /* the read_callback_ sets the state for us */
1169         if(obj->vendor_string.length > 0) {
1170                 if(0 == (obj->vendor_string.entry = (FLAC__byte*)malloc(obj->vendor_string.length))) {
1171                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1172                         return false;
1173                 }
1174                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length, read_callback_, decoder))
1175                         return false; /* the read_callback_ sets the state for us */
1176         }
1177         else
1178                 obj->vendor_string.entry = 0;
1179
1180         /* read num comments */
1181         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1182         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->num_comments, read_callback_, decoder))
1183                 return false; /* the read_callback_ sets the state for us */
1184
1185         /* read comments */
1186         if(obj->num_comments > 0) {
1187                 if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)malloc(obj->num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1188                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1189                         return false;
1190                 }
1191                 for(i = 0; i < obj->num_comments; i++) {
1192                         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1193                         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->comments[i].length, read_callback_, decoder))
1194                                 return false; /* the read_callback_ sets the state for us */
1195                         if(obj->comments[i].length > 0) {
1196                                 if(0 == (obj->comments[i].entry = (FLAC__byte*)malloc(obj->comments[i].length))) {
1197                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1198                                         return false;
1199                                 }
1200                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length, read_callback_, decoder))
1201                                         return false; /* the read_callback_ sets the state for us */
1202                         }
1203                         else
1204                                 obj->comments[i].entry = 0;
1205                 }
1206         }
1207         else {
1208                 obj->comments = 0;
1209         }
1210
1211         return true;
1212 }
1213
1214 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1215 {
1216         FLAC__uint32 i, j, x;
1217
1218         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1219
1220         memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1221
1222         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1223         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))
1224                 return false; /* the read_callback_ sets the state for us */
1225
1226         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN, read_callback_, decoder))
1227                 return false; /* the read_callback_ sets the state for us */
1228
1229         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN, read_callback_, decoder))
1230                 return false; /* the read_callback_ sets the state for us */
1231         obj->is_cd = x? true : false;
1232
1233         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN, read_callback_, decoder))
1234                 return false; /* the read_callback_ sets the state for us */
1235
1236         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN, read_callback_, decoder))
1237                 return false; /* the read_callback_ sets the state for us */
1238         obj->num_tracks = x;
1239
1240         if(obj->num_tracks > 0) {
1241                 if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1242                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1243                         return false;
1244                 }
1245                 for(i = 0; i < obj->num_tracks; i++) {
1246                         FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1247                         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN, read_callback_, decoder))
1248                                 return false; /* the read_callback_ sets the state for us */
1249
1250                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN, read_callback_, decoder))
1251                                 return false; /* the read_callback_ sets the state for us */
1252                         track->number = (FLAC__byte)x;
1253
1254                         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1255                         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))
1256                                 return false; /* the read_callback_ sets the state for us */
1257
1258                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN, read_callback_, decoder))
1259                                 return false; /* the read_callback_ sets the state for us */
1260                         track->type = x;
1261
1262                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN, read_callback_, decoder))
1263                                 return false; /* the read_callback_ sets the state for us */
1264                         track->pre_emphasis = x;
1265
1266                         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN, read_callback_, decoder))
1267                                 return false; /* the read_callback_ sets the state for us */
1268
1269                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN, read_callback_, decoder))
1270                                 return false; /* the read_callback_ sets the state for us */
1271                         track->num_indices = (FLAC__byte)x;
1272
1273                         if(track->num_indices > 0) {
1274                                 if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1275                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1276                                         return false;
1277                                 }
1278                                 for(j = 0; j < track->num_indices; j++) {
1279                                         FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1280                                         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN, read_callback_, decoder))
1281                                                 return false; /* the read_callback_ sets the state for us */
1282
1283                                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN, read_callback_, decoder))
1284                                                 return false; /* the read_callback_ sets the state for us */
1285                                         index->number = (FLAC__byte)x;
1286
1287                                         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN, read_callback_, decoder))
1288                                                 return false; /* the read_callback_ sets the state for us */
1289                                 }
1290                         }
1291                 }
1292         }
1293
1294         return true;
1295 }
1296
1297 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1298 {
1299         FLAC__uint32 x;
1300         unsigned i, skip;
1301
1302         /* skip the version and flags bytes */
1303         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 24, read_callback_, decoder))
1304                 return false; /* the read_callback_ sets the state for us */
1305         /* get the size (in bytes) to skip */
1306         skip = 0;
1307         for(i = 0; i < 4; i++) {
1308                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1309                         return false; /* the read_callback_ sets the state for us */
1310                 skip <<= 7;
1311                 skip |= (x & 0x7f);
1312         }
1313         /* skip the rest of the tag */
1314         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, skip, read_callback_, decoder))
1315                 return false; /* the read_callback_ sets the state for us */
1316         return true;
1317 }
1318
1319 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1320 {
1321         FLAC__uint32 x;
1322         FLAC__bool first = true;
1323
1324         /* If we know the total number of samples in the stream, stop if we've read that many. */
1325         /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1326         if(decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.total_samples) {
1327                 if(decoder->private_->samples_decoded >= decoder->private_->stream_info.data.stream_info.total_samples) {
1328                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1329                         return true;
1330                 }
1331         }
1332
1333         /* make sure we're byte aligned */
1334         if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
1335                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
1336                         return false; /* the read_callback_ sets the state for us */
1337         }
1338
1339         while(1) {
1340                 if(decoder->private_->cached) {
1341                         x = (FLAC__uint32)decoder->private_->lookahead;
1342                         decoder->private_->cached = false;
1343                 }
1344                 else {
1345                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1346                                 return false; /* the read_callback_ sets the state for us */
1347                 }
1348                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1349                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1350                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1351                                 return false; /* the read_callback_ sets the state for us */
1352
1353                         /* 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 */
1354                         /* else we have to check if the second byte is the end of a sync code */
1355                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1356                                 decoder->private_->lookahead = (FLAC__byte)x;
1357                                 decoder->private_->cached = true;
1358                         }
1359                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1360                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1361                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1362                                 return true;
1363                         }
1364                 }
1365                 if(first) {
1366                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, decoder->private_->client_data);
1367                         first = false;
1368                 }
1369         }
1370
1371         return true;
1372 }
1373
1374 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
1375 {
1376         unsigned channel;
1377         unsigned i;
1378         FLAC__int32 mid, side, left, right;
1379         FLAC__uint16 frame_crc; /* the one we calculate from the input stream */
1380         FLAC__uint32 x;
1381
1382         *got_a_frame = false;
1383
1384         /* init the CRC */
1385         frame_crc = 0;
1386         FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
1387         FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
1388         FLAC__bitbuffer_reset_read_crc16(decoder->private_->input, frame_crc);
1389
1390         if(!read_frame_header_(decoder))
1391                 return false;
1392         if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC)
1393                 return true;
1394         if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
1395                 return false;
1396         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1397                 /*
1398                  * first figure the correct bits-per-sample of the subframe
1399                  */
1400                 unsigned bps = decoder->private_->frame.header.bits_per_sample;
1401                 switch(decoder->private_->frame.header.channel_assignment) {
1402                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1403                                 /* no adjustment needed */
1404                                 break;
1405                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1406                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1407                                 if(channel == 1)
1408                                         bps++;
1409                                 break;
1410                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1411                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1412                                 if(channel == 0)
1413                                         bps++;
1414                                 break;
1415                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1416                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1417                                 if(channel == 1)
1418                                         bps++;
1419                                 break;
1420                         default:
1421                                 FLAC__ASSERT(0);
1422                 }
1423                 /*
1424                  * now read it
1425                  */
1426                 if(!read_subframe_(decoder, channel, bps, do_full_decode))
1427                         return false;
1428                 if(decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME) {
1429                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1430                         return true;
1431                 }
1432         }
1433         if(!read_zero_padding_(decoder))
1434                 return false;
1435
1436         /*
1437          * Read the frame CRC-16 from the footer and check
1438          */
1439         frame_crc = FLAC__bitbuffer_get_read_crc16(decoder->private_->input);
1440         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN, read_callback_, decoder))
1441                 return false; /* the read_callback_ sets the state for us */
1442         if(frame_crc == (FLAC__uint16)x) {
1443                 if(do_full_decode) {
1444                         /* Undo any special channel coding */
1445                         switch(decoder->private_->frame.header.channel_assignment) {
1446                                 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1447                                         /* do nothing */
1448                                         break;
1449                                 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1450                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1451                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1452                                                 decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
1453                                         break;
1454                                 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1455                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1456                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1457                                                 decoder->private_->output[0][i] += decoder->private_->output[1][i];
1458                                         break;
1459                                 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1460                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1461                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
1462                                                 mid = decoder->private_->output[0][i];
1463                                                 side = decoder->private_->output[1][i];
1464                                                 mid <<= 1;
1465                                                 if(side & 1) /* i.e. if 'side' is odd... */
1466                                                         mid++;
1467                                                 left = mid + side;
1468                                                 right = mid - side;
1469                                                 decoder->private_->output[0][i] = left >> 1;
1470                                                 decoder->private_->output[1][i] = right >> 1;
1471                                         }
1472                                         break;
1473                                 default:
1474                                         FLAC__ASSERT(0);
1475                                         break;
1476                         }
1477                 }
1478         }
1479         else {
1480                 /* Bad frame, emit error and zero the output signal */
1481                 decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH, decoder->private_->client_data);
1482                 if(do_full_decode) {
1483                         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1484                                 memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
1485                         }
1486                 }
1487         }
1488
1489         *got_a_frame = true;
1490
1491         /* put the latest values into the public section of the decoder instance */
1492         decoder->protected_->channels = decoder->private_->frame.header.channels;
1493         decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
1494         decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
1495         decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
1496         decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
1497
1498         FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1499         decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
1500
1501         /* write it */
1502         if(do_full_decode) {
1503                 if(decoder->private_->write_callback(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output, decoder->private_->client_data) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
1504                         return false;
1505         }
1506
1507         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1508         return true;
1509 }
1510
1511 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
1512 {
1513         FLAC__uint32 x;
1514         FLAC__uint64 xx;
1515         unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
1516         FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
1517         unsigned raw_header_len;
1518         FLAC__bool is_unparseable = false;
1519         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);
1520         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);
1521
1522         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1523
1524         /* init the raw header with the saved bits from synchronization */
1525         raw_header[0] = decoder->private_->header_warmup[0];
1526         raw_header[1] = decoder->private_->header_warmup[1];
1527         raw_header_len = 2;
1528
1529         /*
1530          * check to make sure that the reserved bits are 0
1531          */
1532         if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
1533                 is_unparseable = true;
1534         }
1535
1536         /*
1537          * Note that along the way as we read the header, we look for a sync
1538          * code inside.  If we find one it would indicate that our original
1539          * sync was bad since there cannot be a sync code in a valid header.
1540          */
1541
1542         /*
1543          * read in the raw header as bytes so we can CRC it, and parse it on the way
1544          */
1545         for(i = 0; i < 2; i++) {
1546                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1547                         return false; /* the read_callback_ sets the state for us */
1548                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1549                         /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
1550                         decoder->private_->lookahead = (FLAC__byte)x;
1551                         decoder->private_->cached = true;
1552                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1553                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1554                         return true;
1555                 }
1556                 raw_header[raw_header_len++] = (FLAC__byte)x;
1557         }
1558
1559         switch(x = raw_header[2] >> 4) {
1560                 case 0:
1561                         if(is_known_fixed_blocksize_stream)
1562                                 decoder->private_->frame.header.blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
1563                         else
1564                                 is_unparseable = true;
1565                         break;
1566                 case 1:
1567                         decoder->private_->frame.header.blocksize = 192;
1568                         break;
1569                 case 2:
1570                 case 3:
1571                 case 4:
1572                 case 5:
1573                         decoder->private_->frame.header.blocksize = 576 << (x-2);
1574                         break;
1575                 case 6:
1576                 case 7:
1577                         blocksize_hint = x;
1578                         break;
1579                 case 8:
1580                 case 9:
1581                 case 10:
1582                 case 11:
1583                 case 12:
1584                 case 13:
1585                 case 14:
1586                 case 15:
1587                         decoder->private_->frame.header.blocksize = 256 << (x-8);
1588                         break;
1589                 default:
1590                         FLAC__ASSERT(0);
1591                         break;
1592         }
1593
1594         switch(x = raw_header[2] & 0x0f) {
1595                 case 0:
1596                         if(decoder->private_->has_stream_info)
1597                                 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
1598                         else
1599                                 is_unparseable = true;
1600                         break;
1601                 case 1:
1602                 case 2:
1603                 case 3:
1604                         is_unparseable = true;
1605                         break;
1606                 case 4:
1607                         decoder->private_->frame.header.sample_rate = 8000;
1608                         break;
1609                 case 5:
1610                         decoder->private_->frame.header.sample_rate = 16000;
1611                         break;
1612                 case 6:
1613                         decoder->private_->frame.header.sample_rate = 22050;
1614                         break;
1615                 case 7:
1616                         decoder->private_->frame.header.sample_rate = 24000;
1617                         break;
1618                 case 8:
1619                         decoder->private_->frame.header.sample_rate = 32000;
1620                         break;
1621                 case 9:
1622                         decoder->private_->frame.header.sample_rate = 44100;
1623                         break;
1624                 case 10:
1625                         decoder->private_->frame.header.sample_rate = 48000;
1626                         break;
1627                 case 11:
1628                         decoder->private_->frame.header.sample_rate = 96000;
1629                         break;
1630                 case 12:
1631                 case 13:
1632                 case 14:
1633                         sample_rate_hint = x;
1634                         break;
1635                 case 15:
1636                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1637                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1638                         return true;
1639                 default:
1640                         FLAC__ASSERT(0);
1641         }
1642
1643         x = (unsigned)(raw_header[3] >> 4);
1644         if(x & 8) {
1645                 decoder->private_->frame.header.channels = 2;
1646                 switch(x & 7) {
1647                         case 0:
1648                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
1649                                 break;
1650                         case 1:
1651                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
1652                                 break;
1653                         case 2:
1654                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
1655                                 break;
1656                         default:
1657                                 is_unparseable = true;
1658                                 break;
1659                 }
1660         }
1661         else {
1662                 decoder->private_->frame.header.channels = (unsigned)x + 1;
1663                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
1664         }
1665
1666         switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
1667                 case 0:
1668                         if(decoder->private_->has_stream_info)
1669                                 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
1670                         else
1671                                 is_unparseable = true;
1672                         break;
1673                 case 1:
1674                         decoder->private_->frame.header.bits_per_sample = 8;
1675                         break;
1676                 case 2:
1677                         decoder->private_->frame.header.bits_per_sample = 12;
1678                         break;
1679                 case 4:
1680                         decoder->private_->frame.header.bits_per_sample = 16;
1681                         break;
1682                 case 5:
1683                         decoder->private_->frame.header.bits_per_sample = 20;
1684                         break;
1685                 case 6:
1686                         decoder->private_->frame.header.bits_per_sample = 24;
1687                         break;
1688                 case 3:
1689                 case 7:
1690                         is_unparseable = true;
1691                         break;
1692                 default:
1693                         FLAC__ASSERT(0);
1694                         break;
1695         }
1696
1697         if(raw_header[3] & 0x01) { /* this should be a zero padding bit */
1698                 decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1699                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1700                 return true;
1701         }
1702
1703         if(blocksize_hint && is_known_variable_blocksize_stream) {
1704                 if(!FLAC__bitbuffer_read_utf8_uint64(decoder->private_->input, &xx, read_callback_, decoder, raw_header, &raw_header_len))
1705                         return false; /* the read_callback_ sets the state for us */
1706                 if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
1707                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
1708                         decoder->private_->cached = true;
1709                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1710                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1711                         return true;
1712                 }
1713                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
1714                 decoder->private_->frame.header.number.sample_number = xx;
1715         }
1716         else {
1717                 if(!FLAC__bitbuffer_read_utf8_uint32(decoder->private_->input, &x, read_callback_, decoder, raw_header, &raw_header_len))
1718                         return false; /* the read_callback_ sets the state for us */
1719                 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
1720                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
1721                         decoder->private_->cached = true;
1722                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1723                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1724                         return true;
1725                 }
1726                 decoder->private_->last_frame_number = x;
1727                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
1728                 if(blocksize_hint) {
1729                         if(decoder->private_->has_stream_info)
1730                                 decoder->private_->frame.header.number.sample_number = (FLAC__int64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__int64)x;
1731                         else
1732                                 is_unparseable = true;
1733                 }
1734                 else    
1735                         decoder->private_->frame.header.number.sample_number = (FLAC__int64)decoder->private_->frame.header.blocksize * (FLAC__int64)x;
1736         }
1737
1738         if(blocksize_hint) {
1739                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1740                         return false; /* the read_callback_ sets the state for us */
1741                 raw_header[raw_header_len++] = (FLAC__byte)x;
1742                 if(blocksize_hint == 7) {
1743                         FLAC__uint32 _x;
1744                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
1745                                 return false; /* the read_callback_ sets the state for us */
1746                         raw_header[raw_header_len++] = (FLAC__byte)_x;
1747                         x = (x << 8) | _x;
1748                 }
1749                 decoder->private_->frame.header.blocksize = x+1;
1750         }
1751
1752         if(sample_rate_hint) {
1753                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1754                         return false; /* the read_callback_ sets the state for us */
1755                 raw_header[raw_header_len++] = (FLAC__byte)x;
1756                 if(sample_rate_hint != 12) {
1757                         FLAC__uint32 _x;
1758                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
1759                                 return false; /* the read_callback_ sets the state for us */
1760                         raw_header[raw_header_len++] = (FLAC__byte)_x;
1761                         x = (x << 8) | _x;
1762                 }
1763                 if(sample_rate_hint == 12)
1764                         decoder->private_->frame.header.sample_rate = x*1000;
1765                 else if(sample_rate_hint == 13)
1766                         decoder->private_->frame.header.sample_rate = x;
1767                 else
1768                         decoder->private_->frame.header.sample_rate = x*10;
1769         }
1770
1771         /* read the CRC-8 byte */
1772         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1773                 return false; /* the read_callback_ sets the state for us */
1774         crc8 = (FLAC__byte)x;
1775
1776         if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
1777                 decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1778                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1779                 return true;
1780         }
1781
1782         if(is_unparseable) {
1783                 decoder->protected_->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1784                 return false;
1785         }
1786
1787         return true;
1788 }
1789
1790 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
1791 {
1792         FLAC__uint32 x;
1793         FLAC__bool wasted_bits;
1794
1795         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder)) /* MAGIC NUMBER */
1796                 return false; /* the read_callback_ sets the state for us */
1797
1798         wasted_bits = (x & 1);
1799         x &= 0xfe;
1800
1801         if(wasted_bits) {
1802                 unsigned u;
1803                 if(!FLAC__bitbuffer_read_unary_unsigned(decoder->private_->input, &u, read_callback_, decoder))
1804                         return false; /* the read_callback_ sets the state for us */
1805                 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
1806                 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
1807         }
1808         else
1809                 decoder->private_->frame.subframes[channel].wasted_bits = 0;
1810
1811         /*
1812          * Lots of magic numbers here
1813          */
1814         if(x & 0x80) {
1815                 decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, decoder->private_->client_data);
1816                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1817                 return true;
1818         }
1819         else if(x == 0) {
1820                 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
1821                         return false;
1822         }
1823         else if(x == 2) {
1824                 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
1825                         return false;
1826         }
1827         else if(x < 16) {
1828                 decoder->protected_->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1829                 return false;
1830         }
1831         else if(x <= 24) {
1832                 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
1833                         return false;
1834         }
1835         else if(x < 64) {
1836                 decoder->protected_->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1837                 return false;
1838         }
1839         else {
1840                 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
1841                         return false;
1842         }
1843
1844         if(wasted_bits && do_full_decode) {
1845                 unsigned i;
1846                 x = decoder->private_->frame.subframes[channel].wasted_bits;
1847                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1848                         decoder->private_->output[channel][i] <<= x;
1849         }
1850
1851         return true;
1852 }
1853
1854 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
1855 {
1856         FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
1857         FLAC__int32 x;
1858         unsigned i;
1859         FLAC__int32 *output = decoder->private_->output[channel];
1860
1861         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
1862
1863         if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
1864                 return false; /* the read_callback_ sets the state for us */
1865
1866         subframe->value = x;
1867
1868         /* decode the subframe */
1869         if(do_full_decode) {
1870                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1871                         output[i] = x;
1872         }
1873
1874         return true;
1875 }
1876
1877 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
1878 {
1879         FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
1880         FLAC__int32 i32;
1881         FLAC__uint32 u32;
1882         unsigned u;
1883
1884         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
1885
1886         subframe->residual = decoder->private_->residual[channel];
1887         subframe->order = order;
1888
1889         /* read warm-up samples */
1890         for(u = 0; u < order; u++) {
1891                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
1892                         return false; /* the read_callback_ sets the state for us */
1893                 subframe->warmup[u] = i32;
1894         }
1895
1896         /* read entropy coding method info */
1897         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
1898                 return false; /* the read_callback_ sets the state for us */
1899         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
1900         switch(subframe->entropy_coding_method.type) {
1901                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1902                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
1903                                 return false; /* the read_callback_ sets the state for us */
1904                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
1905                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
1906                         break;
1907                 default:
1908                         decoder->protected_->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1909                         return false;
1910         }
1911
1912         /* read residual */
1913         switch(subframe->entropy_coding_method.type) {
1914                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1915                         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]))
1916                                 return false;
1917                         break;
1918                 default:
1919                         FLAC__ASSERT(0);
1920         }
1921
1922         /* decode the subframe */
1923         if(do_full_decode) {
1924                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
1925                 FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
1926         }
1927
1928         return true;
1929 }
1930
1931 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
1932 {
1933         FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
1934         FLAC__int32 i32;
1935         FLAC__uint32 u32;
1936         unsigned u;
1937
1938         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
1939
1940         subframe->residual = decoder->private_->residual[channel];
1941         subframe->order = order;
1942
1943         /* read warm-up samples */
1944         for(u = 0; u < order; u++) {
1945                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
1946                         return false; /* the read_callback_ sets the state for us */
1947                 subframe->warmup[u] = i32;
1948         }
1949
1950         /* read qlp coeff precision */
1951         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN, read_callback_, decoder))
1952                 return false; /* the read_callback_ sets the state for us */
1953         if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
1954                 decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, decoder->private_->client_data);
1955                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1956                 return true;
1957         }
1958         subframe->qlp_coeff_precision = u32+1;
1959
1960         /* read qlp shift */
1961         if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN, read_callback_, decoder))
1962                 return false; /* the read_callback_ sets the state for us */
1963         subframe->quantization_level = i32;
1964
1965         /* read quantized lp coefficiencts */
1966         for(u = 0; u < order; u++) {
1967                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision, read_callback_, decoder))
1968                         return false; /* the read_callback_ sets the state for us */
1969                 subframe->qlp_coeff[u] = i32;
1970         }
1971
1972         /* read entropy coding method info */
1973         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
1974                 return false; /* the read_callback_ sets the state for us */
1975         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
1976         switch(subframe->entropy_coding_method.type) {
1977                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1978                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
1979                                 return false; /* the read_callback_ sets the state for us */
1980                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
1981                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
1982                         break;
1983                 default:
1984                         decoder->protected_->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1985                         return false;
1986         }
1987
1988         /* read residual */
1989         switch(subframe->entropy_coding_method.type) {
1990                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1991                         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]))
1992                                 return false;
1993                         break;
1994                 default:
1995                         FLAC__ASSERT(0);
1996         }
1997
1998         /* decode the subframe */
1999         if(do_full_decode) {
2000                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2001                 if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2002                         if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2003                                 if(order <= 8)
2004                                         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);
2005                                 else
2006                                         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);
2007                         }
2008                         else
2009                                 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);
2010                 else
2011                         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);
2012         }
2013
2014         return true;
2015 }
2016
2017 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2018 {
2019         FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2020         FLAC__int32 x, *residual = decoder->private_->residual[channel];
2021         unsigned i;
2022
2023         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2024
2025         subframe->data = residual;
2026
2027         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2028                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
2029                         return false; /* the read_callback_ sets the state for us */
2030                 residual[i] = x;
2031         }
2032
2033         /* decode the subframe */
2034         if(do_full_decode)
2035                 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2036
2037         return true;
2038 }
2039
2040 FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual)
2041 {
2042         FLAC__uint32 rice_parameter;
2043         int i;
2044         unsigned partition, sample, u;
2045         const unsigned partitions = 1u << partition_order;
2046         const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2047
2048         if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2049                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2050                 return false;
2051         }
2052
2053         sample = 0;
2054         for(partition = 0; partition < partitions; partition++) {
2055                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN, read_callback_, decoder))
2056                         return false; /* the read_callback_ sets the state for us */
2057                 partitioned_rice_contents->parameters[partition] = rice_parameter;
2058                 if(rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2059 #ifdef FLAC__SYMMETRIC_RICE
2060                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2061                                 if(!FLAC__bitbuffer_read_symmetric_rice_signed(decoder->private_->input, &i, rice_parameter, read_callback_, decoder))
2062                                         return false; /* the read_callback_ sets the state for us */
2063                                 residual[sample] = i;
2064                         }
2065 #else
2066                         u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2067                         if(!FLAC__bitbuffer_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter, read_callback_, decoder))
2068                                 return false; /* the read_callback_ sets the state for us */
2069                         sample += u;
2070 #endif
2071                 }
2072                 else {
2073                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN, read_callback_, decoder))
2074                                 return false; /* the read_callback_ sets the state for us */
2075                         partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2076                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2077                                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i, rice_parameter, read_callback_, decoder))
2078                                         return false; /* the read_callback_ sets the state for us */
2079                                 residual[sample] = i;
2080                         }
2081                 }
2082         }
2083
2084         return true;
2085 }
2086
2087 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2088 {
2089         if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
2090                 FLAC__uint32 zero = 0;
2091                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
2092                         return false; /* the read_callback_ sets the state for us */
2093                 if(zero != 0) {
2094                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, decoder->private_->client_data);
2095                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2096                 }
2097         }
2098         return true;
2099 }
2100
2101 FLAC__bool read_callback_(FLAC__byte buffer[], unsigned *bytes, void *client_data)
2102 {
2103         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2104         FLAC__StreamDecoderReadStatus status;
2105
2106         status = decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data);
2107         if(status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM)
2108                 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2109         else if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT)
2110                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2111         return status == FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2112 }