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