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