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