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