7674fa777b6ac767851c1c4564e2e4da30876c2e
[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 const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
520 {
521         return FLAC__StreamDecoderStateString[decoder->protected_->state];
522 }
523
524 FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
525 {
526         FLAC__ASSERT(0 != decoder);
527         FLAC__ASSERT(0 != decoder->protected_);
528         return decoder->protected_->channels;
529 }
530
531 FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
532 {
533         FLAC__ASSERT(0 != decoder);
534         FLAC__ASSERT(0 != decoder->protected_);
535         return decoder->protected_->channel_assignment;
536 }
537
538 FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
539 {
540         FLAC__ASSERT(0 != decoder);
541         FLAC__ASSERT(0 != decoder->protected_);
542         return decoder->protected_->bits_per_sample;
543 }
544
545 FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
546 {
547         FLAC__ASSERT(0 != decoder);
548         FLAC__ASSERT(0 != decoder->protected_);
549         return decoder->protected_->sample_rate;
550 }
551
552 FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
553 {
554         FLAC__ASSERT(0 != decoder);
555         FLAC__ASSERT(0 != decoder->protected_);
556         return decoder->protected_->blocksize;
557 }
558
559 FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
560 {
561         FLAC__ASSERT(0 != decoder);
562         FLAC__ASSERT(0 != decoder->private_);
563         FLAC__ASSERT(0 != decoder->protected_);
564
565         if(!FLAC__bitbuffer_clear(decoder->private_->input)) {
566                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
567                 return false;
568         }
569         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
570
571         return true;
572 }
573
574 FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
575 {
576         FLAC__ASSERT(0 != decoder);
577         FLAC__ASSERT(0 != decoder->private_);
578         FLAC__ASSERT(0 != decoder->protected_);
579
580         if(!FLAC__stream_decoder_flush(decoder)) {
581                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
582                 return false;
583         }
584         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
585
586         decoder->private_->samples_decoded = 0;
587
588         return true;
589 }
590
591 FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
592 {
593         FLAC__bool got_a_frame;
594         FLAC__ASSERT(0 != decoder);
595         FLAC__ASSERT(0 != decoder->protected_);
596
597         while(1) {
598                 switch(decoder->protected_->state) {
599                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
600                                 if(!find_metadata_(decoder))
601                                         return false; /* above function sets the status for us */
602                                 break;
603                         case FLAC__STREAM_DECODER_READ_METADATA:
604                                 if(!read_metadata_(decoder))
605                                         return false; /* above function sets the status for us */
606                                 else
607                                         return true;
608                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
609                                 if(!frame_sync_(decoder))
610                                         return true; /* above function sets the status for us */
611                                 break;
612                         case FLAC__STREAM_DECODER_READ_FRAME:
613                                 if(!read_frame_(decoder, &got_a_frame))
614                                         return false; /* above function sets the status for us */
615                                 if(got_a_frame)
616                                         return true; /* above function sets the status for us */
617                                 break;
618                         case FLAC__STREAM_DECODER_END_OF_STREAM:
619                         case FLAC__STREAM_DECODER_ABORTED:
620                                 return true;
621                         default:
622                                 FLAC__ASSERT(0);
623                                 return false;
624                 }
625         }
626 }
627
628 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
629 {
630         FLAC__ASSERT(0 != decoder);
631         FLAC__ASSERT(0 != decoder->protected_);
632
633         while(1) {
634                 switch(decoder->protected_->state) {
635                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
636                                 if(!find_metadata_(decoder))
637                                         return false; /* above function sets the status for us */
638                                 break;
639                         case FLAC__STREAM_DECODER_READ_METADATA:
640                                 if(!read_metadata_(decoder))
641                                         return false; /* above function sets the status for us */
642                                 break;
643                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
644                         case FLAC__STREAM_DECODER_READ_FRAME:
645                         case FLAC__STREAM_DECODER_END_OF_STREAM:
646                         case FLAC__STREAM_DECODER_ABORTED:
647                                 return true;
648                         default:
649                                 FLAC__ASSERT(0);
650                                 return false;
651                 }
652         }
653 }
654
655 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
656 {
657         FLAC__bool dummy;
658         FLAC__ASSERT(0 != decoder);
659         FLAC__ASSERT(0 != decoder->protected_);
660
661         while(1) {
662                 switch(decoder->protected_->state) {
663                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
664                                 if(!find_metadata_(decoder))
665                                         return false; /* above function sets the status for us */
666                                 break;
667                         case FLAC__STREAM_DECODER_READ_METADATA:
668                                 if(!read_metadata_(decoder))
669                                         return false; /* above function sets the status for us */
670                                 break;
671                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
672                                 if(!frame_sync_(decoder))
673                                         return true; /* above function sets the status for us */
674                                 break;
675                         case FLAC__STREAM_DECODER_READ_FRAME:
676                                 if(!read_frame_(decoder, &dummy))
677                                         return false; /* above function sets the status for us */
678                                 break;
679                         case FLAC__STREAM_DECODER_END_OF_STREAM:
680                         case FLAC__STREAM_DECODER_ABORTED:
681                                 return true;
682                         default:
683                                 FLAC__ASSERT(0);
684                                 return false;
685                 }
686         }
687 }
688
689 /***********************************************************************
690  *
691  * Protected class methods
692  *
693  ***********************************************************************/
694
695 unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
696 {
697         FLAC__ASSERT(0 != decoder);
698         return FLAC__bitbuffer_get_input_bytes_unconsumed(decoder->private_->input);
699 }
700
701 /***********************************************************************
702  *
703  * Private class methods
704  *
705  ***********************************************************************/
706
707 void set_defaults_(FLAC__StreamDecoder *decoder)
708 {
709         decoder->private_->read_callback = 0;
710         decoder->private_->write_callback = 0;
711         decoder->private_->metadata_callback = 0;
712         decoder->private_->error_callback = 0;
713         decoder->private_->client_data = 0;
714
715         memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
716         decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
717         decoder->private_->metadata_filter_ids_count = 0;
718 }
719
720 FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
721 {
722         unsigned i;
723         FLAC__int32 *tmp;
724
725         if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
726                 return true;
727
728         /* simply using realloc() is not practical because the number of channels may change mid-stream */
729
730         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
731                 if(0 != decoder->private_->output[i]) {
732                         free(decoder->private_->output[i]-4);
733                         decoder->private_->output[i] = 0;
734                 }
735                 if(0 != decoder->private_->residual[i]) {
736                         free(decoder->private_->residual[i]);
737                         decoder->private_->residual[i] = 0;
738                 }
739         }
740
741         for(i = 0; i < channels; i++) {
742                 /* WATCHOUT:
743                  * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
744                  * output arrays have a buffer of up to 3 zeroes in front
745                  * (at negative indices) for alignment purposes; we use 4
746                  * to keep the data well-aligned.
747                  */
748                 tmp = (FLAC__int32*)malloc(sizeof(FLAC__int32)*(size+4));
749                 if(tmp == 0) {
750                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
751                         return false;
752                 }
753                 memset(tmp, 0, sizeof(FLAC__int32)*4);
754                 decoder->private_->output[i] = tmp + 4;
755
756                 tmp = (FLAC__int32*)malloc(sizeof(FLAC__int32)*size);
757                 if(tmp == 0) {
758                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
759                         return false;
760                 }
761                 decoder->private_->residual[i] = tmp;
762         }
763
764         decoder->private_->output_capacity = size;
765         decoder->private_->output_channels = channels;
766
767         return true;
768 }
769
770 FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
771 {
772         unsigned i;
773
774         FLAC__ASSERT(0 != decoder);
775         FLAC__ASSERT(0 != decoder->private_);
776
777         for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
778                 if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
779                         return true;
780
781         return false;
782 }
783
784 FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
785 {
786         FLAC__uint32 x;
787         unsigned i, id;
788         FLAC__bool first = true;
789
790         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
791
792         for(i = id = 0; i < 4; ) {
793                 if(decoder->private_->cached) {
794                         x = (FLAC__uint32)decoder->private_->lookahead;
795                         decoder->private_->cached = false;
796                 }
797                 else {
798                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
799                                 return false; /* the read_callback_ sets the state for us */
800                 }
801                 if(x == FLAC__STREAM_SYNC_STRING[i]) {
802                         first = true;
803                         i++;
804                         id = 0;
805                         continue;
806                 }
807                 if(x == ID3V2_TAG_[id]) {
808                         id++;
809                         i = 0;
810                         if(id == 3) {
811                                 if(!skip_id3v2_tag_(decoder))
812                                         return false; /* the read_callback_ sets the state for us */
813                         }
814                         continue;
815                 }
816                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
817                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
818                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
819                                 return false; /* the read_callback_ sets the state for us */
820
821                         /* 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 */
822                         /* else we have to check if the second byte is the end of a sync code */
823                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
824                                 decoder->private_->lookahead = (FLAC__byte)x;
825                                 decoder->private_->cached = true;
826                         }
827                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
828                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
829                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
830                                 return true;
831                         }
832                 }
833                 i = 0;
834                 if(first) {
835                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, decoder->private_->client_data);
836                         first = false;
837                 }
838         }
839
840         decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
841         return true;
842 }
843
844 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
845 {
846         FLAC__bool is_last;
847         FLAC__uint32 i, x, type, length;
848
849         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
850
851         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN, read_callback_, decoder))
852                 return false; /* the read_callback_ sets the state for us */
853         is_last = x? true : false;
854
855         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN, read_callback_, decoder))
856                 return false; /* the read_callback_ sets the state for us */
857
858         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN, read_callback_, decoder))
859                 return false; /* the read_callback_ sets the state for us */
860
861         if(type == FLAC__METADATA_TYPE_STREAMINFO) {
862                 if(!read_metadata_streaminfo_(decoder, is_last, length))
863                         return false;
864
865                 decoder->private_->has_stream_info = true;
866                 if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO])
867                         decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
868         }
869         else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
870                 if(!read_metadata_seektable_(decoder, is_last, length))
871                         return false;
872
873                 decoder->private_->has_seek_table = true;
874                 if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE])
875                         decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
876         }
877         else {
878                 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
879                 unsigned real_length = length;
880                 FLAC__StreamMetadata block;
881
882                 block.is_last = is_last;
883                 block.type = (FLAC__MetadataType)type;
884                 block.length = length;
885
886                 if(type == FLAC__METADATA_TYPE_APPLICATION) {
887                         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))
888                                 return false; /* the read_callback_ sets the state for us */
889
890                         real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
891
892                         if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
893                                 skip_it = !skip_it;
894                 }
895
896                 if(skip_it) {
897                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
898                                 return false; /* the read_callback_ sets the state for us */
899                 }
900                 else {
901                         switch(type) {
902                                 case FLAC__METADATA_TYPE_PADDING:
903                                         /* skip the padding bytes */
904                                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
905                                                 return false; /* the read_callback_ sets the state for us */
906                                         break;
907                                 case FLAC__METADATA_TYPE_APPLICATION:
908                                         /* remember, we read the ID already */
909                                         if(real_length > 0) {
910                                                 if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
911                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
912                                                         return false;
913                                                 }
914                                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length, read_callback_, decoder))
915                                                         return false; /* the read_callback_ sets the state for us */
916                                         }
917                                         else
918                                                 block.data.application.data = 0;
919                                         break;
920                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
921                                         if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
922                                                 return false;
923                                         break;
924                                 case FLAC__METADATA_TYPE_CUESHEET:
925                                         if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
926                                                 return false;
927                                         break;
928                                 case FLAC__METADATA_TYPE_STREAMINFO:
929                                 case FLAC__METADATA_TYPE_SEEKTABLE:
930                                         FLAC__ASSERT(0);
931                                         break;
932                                 default:
933                                         if(real_length > 0) {
934                                                 if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
935                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
936                                                         return false;
937                                                 }
938                                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length, read_callback_, decoder))
939                                                         return false; /* the read_callback_ sets the state for us */
940                                         }
941                                         else
942                                                 block.data.unknown.data = 0;
943                                         break;
944                         }
945                         decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
946
947                         /* now we have to free any malloc'ed data in the block */
948                         switch(type) {
949                                 case FLAC__METADATA_TYPE_PADDING:
950                                         break;
951                                 case FLAC__METADATA_TYPE_APPLICATION:
952                                         if(0 != block.data.application.data)
953                                                 free(block.data.application.data);
954                                         break;
955                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
956                                         if(0 != block.data.vorbis_comment.vendor_string.entry)
957                                                 free(block.data.vorbis_comment.vendor_string.entry);
958                                         if(block.data.vorbis_comment.num_comments > 0)
959                                                 for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
960                                                         if(0 != block.data.vorbis_comment.comments[i].entry)
961                                                                 free(block.data.vorbis_comment.comments[i].entry);
962                                         if(0 != block.data.vorbis_comment.comments)
963                                                 free(block.data.vorbis_comment.comments);
964                                         break;
965                                 case FLAC__METADATA_TYPE_CUESHEET:
966                                         if(block.data.cue_sheet.num_tracks > 0)
967                                                 for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
968                                                         if(0 != block.data.cue_sheet.tracks[i].indices)
969                                                                 free(block.data.cue_sheet.tracks[i].indices);
970                                         if(0 != block.data.cue_sheet.tracks)
971                                                 free(block.data.cue_sheet.tracks);
972                                         break;
973                                 case FLAC__METADATA_TYPE_STREAMINFO:
974                                 case FLAC__METADATA_TYPE_SEEKTABLE:
975                                         FLAC__ASSERT(0);
976                                 default:
977                                         if(0 != block.data.unknown.data)
978                                                 free(block.data.unknown.data);
979                                         break;
980                         }
981                 }
982         }
983
984         if(is_last)
985                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
986
987         return true;
988 }
989
990 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
991 {
992         FLAC__uint32 x;
993         unsigned bits, used_bits = 0;
994
995         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
996
997         decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
998         decoder->private_->stream_info.is_last = is_last;
999         decoder->private_->stream_info.length = length;
1000
1001         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1002         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, bits, read_callback_, decoder))
1003                 return false; /* the read_callback_ sets the state for us */
1004         decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1005         used_bits += bits;
1006
1007         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1008         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN, read_callback_, decoder))
1009                 return false; /* the read_callback_ sets the state for us */
1010         decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1011         used_bits += bits;
1012
1013         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1014         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN, read_callback_, decoder))
1015                 return false; /* the read_callback_ sets the state for us */
1016         decoder->private_->stream_info.data.stream_info.min_framesize = x;
1017         used_bits += bits;
1018
1019         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1020         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN, read_callback_, decoder))
1021                 return false; /* the read_callback_ sets the state for us */
1022         decoder->private_->stream_info.data.stream_info.max_framesize = x;
1023         used_bits += bits;
1024
1025         bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1026         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN, read_callback_, decoder))
1027                 return false; /* the read_callback_ sets the state for us */
1028         decoder->private_->stream_info.data.stream_info.sample_rate = x;
1029         used_bits += bits;
1030
1031         bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1032         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN, read_callback_, decoder))
1033                 return false; /* the read_callback_ sets the state for us */
1034         decoder->private_->stream_info.data.stream_info.channels = x+1;
1035         used_bits += bits;
1036
1037         bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1038         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN, read_callback_, decoder))
1039                 return false; /* the read_callback_ sets the state for us */
1040         decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1041         used_bits += bits;
1042
1043         bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1044         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))
1045                 return false; /* the read_callback_ sets the state for us */
1046         used_bits += bits;
1047
1048         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16, read_callback_, decoder))
1049                 return false; /* the read_callback_ sets the state for us */
1050         used_bits += 16*8;
1051
1052         /* skip the rest of the block */
1053         FLAC__ASSERT(used_bits % 8 == 0);
1054         length -= (used_bits / 8);
1055         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1056                 return false; /* the read_callback_ sets the state for us */
1057
1058         return true;
1059 }
1060
1061 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1062 {
1063         FLAC__uint32 i, x;
1064         FLAC__uint64 xx;
1065
1066         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1067
1068         decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1069         decoder->private_->seek_table.is_last = is_last;
1070         decoder->private_->seek_table.length = length;
1071
1072         decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1073
1074         /* use realloc since we may pass through here several times (e.g. after seeking) */
1075         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)))) {
1076                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1077                 return false;
1078         }
1079         for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1080                 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN, read_callback_, decoder))
1081                         return false; /* the read_callback_ sets the state for us */
1082                 decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1083
1084                 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN, read_callback_, decoder))
1085                         return false; /* the read_callback_ sets the state for us */
1086                 decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1087
1088                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN, read_callback_, decoder))
1089                         return false; /* the read_callback_ sets the state for us */
1090                 decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1091         }
1092         length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1093         /* if there is a partial point left, skip over it */
1094         if(length > 0) {
1095                 /*@@@ do an error_callback() here?  there's an argument for either way */
1096                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1097                         return false; /* the read_callback_ sets the state for us */
1098         }
1099
1100         return true;
1101 }
1102
1103 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1104 {
1105         FLAC__uint32 i;
1106
1107         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1108
1109         /* read vendor string */
1110         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1111         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length, read_callback_, decoder))
1112                 return false; /* the read_callback_ sets the state for us */
1113         if(obj->vendor_string.length > 0) {
1114                 if(0 == (obj->vendor_string.entry = (FLAC__byte*)malloc(obj->vendor_string.length))) {
1115                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1116                         return false;
1117                 }
1118                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length, read_callback_, decoder))
1119                         return false; /* the read_callback_ sets the state for us */
1120         }
1121         else
1122                 obj->vendor_string.entry = 0;
1123
1124         /* read num comments */
1125         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1126         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->num_comments, read_callback_, decoder))
1127                 return false; /* the read_callback_ sets the state for us */
1128
1129         /* read comments */
1130         if(obj->num_comments > 0) {
1131                 if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)malloc(obj->num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1132                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1133                         return false;
1134                 }
1135                 for(i = 0; i < obj->num_comments; i++) {
1136                         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1137                         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->comments[i].length, read_callback_, decoder))
1138                                 return false; /* the read_callback_ sets the state for us */
1139                         if(obj->comments[i].length > 0) {
1140                                 if(0 == (obj->comments[i].entry = (FLAC__byte*)malloc(obj->comments[i].length))) {
1141                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1142                                         return false;
1143                                 }
1144                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length, read_callback_, decoder))
1145                                         return false; /* the read_callback_ sets the state for us */
1146                         }
1147                         else
1148                                 obj->comments[i].entry = 0;
1149                 }
1150         }
1151         else {
1152                 obj->comments = 0;
1153         }
1154
1155         return true;
1156 }
1157
1158 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1159 {
1160         FLAC__uint32 i, j, x;
1161
1162         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1163
1164         memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1165
1166         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1167         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8, read_callback_, decoder))
1168                 return false; /* the read_callback_ sets the state for us */
1169
1170         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN, read_callback_, decoder))
1171                 return false; /* the read_callback_ sets the state for us */
1172
1173         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN, read_callback_, decoder))
1174                 return false; /* the read_callback_ sets the state for us */
1175         obj->is_cd = x? true : false;
1176
1177         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN, read_callback_, decoder))
1178                 return false; /* the read_callback_ sets the state for us */
1179
1180         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN, read_callback_, decoder))
1181                 return false; /* the read_callback_ sets the state for us */
1182         obj->num_tracks = x;
1183
1184         if(obj->num_tracks > 0) {
1185                 if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1186                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1187                         return false;
1188                 }
1189                 for(i = 0; i < obj->num_tracks; i++) {
1190                         FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1191                         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN, read_callback_, decoder))
1192                                 return false; /* the read_callback_ sets the state for us */
1193
1194                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN, read_callback_, decoder))
1195                                 return false; /* the read_callback_ sets the state for us */
1196                         track->number = (FLAC__byte)x;
1197
1198                         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1199                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8, read_callback_, decoder))
1200                                 return false; /* the read_callback_ sets the state for us */
1201
1202                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN, read_callback_, decoder))
1203                                 return false; /* the read_callback_ sets the state for us */
1204                         track->type = x;
1205
1206                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN, read_callback_, decoder))
1207                                 return false; /* the read_callback_ sets the state for us */
1208                         track->pre_emphasis = x;
1209
1210                         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN, read_callback_, decoder))
1211                                 return false; /* the read_callback_ sets the state for us */
1212
1213                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN, read_callback_, decoder))
1214                                 return false; /* the read_callback_ sets the state for us */
1215                         track->num_indices = (FLAC__byte)x;
1216
1217                         if(track->num_indices > 0) {
1218                                 if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1219                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1220                                         return false;
1221                                 }
1222                                 for(j = 0; j < track->num_indices; j++) {
1223                                         FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1224                                         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN, read_callback_, decoder))
1225                                                 return false; /* the read_callback_ sets the state for us */
1226
1227                                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN, read_callback_, decoder))
1228                                                 return false; /* the read_callback_ sets the state for us */
1229                                         index->number = (FLAC__byte)x;
1230
1231                                         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN, read_callback_, decoder))
1232                                                 return false; /* the read_callback_ sets the state for us */
1233                                 }
1234                         }
1235                 }
1236         }
1237
1238         return true;
1239 }
1240
1241 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1242 {
1243         FLAC__uint32 x;
1244         unsigned i, skip;
1245
1246         /* skip the version and flags bytes */
1247         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 24, read_callback_, decoder))
1248                 return false; /* the read_callback_ sets the state for us */
1249         /* get the size (in bytes) to skip */
1250         skip = 0;
1251         for(i = 0; i < 4; i++) {
1252                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1253                         return false; /* the read_callback_ sets the state for us */
1254                 skip <<= 7;
1255                 skip |= (x & 0x7f);
1256         }
1257         /* skip the rest of the tag */
1258         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, skip, read_callback_, decoder))
1259                 return false; /* the read_callback_ sets the state for us */
1260         return true;
1261 }
1262
1263 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1264 {
1265         FLAC__uint32 x;
1266         FLAC__bool first = true;
1267
1268         /* If we know the total number of samples in the stream, stop if we've read that many. */
1269         /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1270         if(decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.total_samples) {
1271                 if(decoder->private_->samples_decoded >= decoder->private_->stream_info.data.stream_info.total_samples) {
1272                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1273                         return true;
1274                 }
1275         }
1276
1277         /* make sure we're byte aligned */
1278         if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
1279                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
1280                         return false; /* the read_callback_ sets the state for us */
1281         }
1282
1283         while(1) {
1284                 if(decoder->private_->cached) {
1285                         x = (FLAC__uint32)decoder->private_->lookahead;
1286                         decoder->private_->cached = false;
1287                 }
1288                 else {
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                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1293                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1294                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1295                                 return false; /* the read_callback_ sets the state for us */
1296
1297                         /* 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 */
1298                         /* else we have to check if the second byte is the end of a sync code */
1299                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1300                                 decoder->private_->lookahead = (FLAC__byte)x;
1301                                 decoder->private_->cached = true;
1302                         }
1303                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1304                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1305                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1306                                 return true;
1307                         }
1308                 }
1309                 if(first) {
1310                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, decoder->private_->client_data);
1311                         first = false;
1312                 }
1313         }
1314
1315         return true;
1316 }
1317
1318 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame)
1319 {
1320         unsigned channel;
1321         unsigned i;
1322         FLAC__int32 mid, side, left, right;
1323         FLAC__uint16 frame_crc; /* the one we calculate from the input stream */
1324         FLAC__uint32 x;
1325
1326         *got_a_frame = false;
1327
1328         /* init the CRC */
1329         frame_crc = 0;
1330         FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
1331         FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
1332         FLAC__bitbuffer_reset_read_crc16(decoder->private_->input, frame_crc);
1333
1334         if(!read_frame_header_(decoder))
1335                 return false;
1336         if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC)
1337                 return true;
1338         if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
1339                 return false;
1340         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1341                 /*
1342                  * first figure the correct bits-per-sample of the subframe
1343                  */
1344                 unsigned bps = decoder->private_->frame.header.bits_per_sample;
1345                 switch(decoder->private_->frame.header.channel_assignment) {
1346                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1347                                 /* no adjustment needed */
1348                                 break;
1349                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1350                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1351                                 if(channel == 1)
1352                                         bps++;
1353                                 break;
1354                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1355                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1356                                 if(channel == 0)
1357                                         bps++;
1358                                 break;
1359                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1360                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1361                                 if(channel == 1)
1362                                         bps++;
1363                                 break;
1364                         default:
1365                                 FLAC__ASSERT(0);
1366                 }
1367                 /*
1368                  * now read it
1369                  */
1370                 if(!read_subframe_(decoder, channel, bps))
1371                         return false;
1372                 if(decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME) {
1373                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1374                         return true;
1375                 }
1376         }
1377         if(!read_zero_padding_(decoder))
1378                 return false;
1379
1380         /*
1381          * Read the frame CRC-16 from the footer and check
1382          */
1383         frame_crc = FLAC__bitbuffer_get_read_crc16(decoder->private_->input);
1384         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN, read_callback_, decoder))
1385                 return false; /* the read_callback_ sets the state for us */
1386         if(frame_crc == (FLAC__uint16)x) {
1387                 /* Undo any special channel coding */
1388                 switch(decoder->private_->frame.header.channel_assignment) {
1389                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1390                                 /* do nothing */
1391                                 break;
1392                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_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[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
1396                                 break;
1397                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1398                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1399                                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1400                                         decoder->private_->output[0][i] += decoder->private_->output[1][i];
1401                                 break;
1402                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1403                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1404                                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
1405                                         mid = decoder->private_->output[0][i];
1406                                         side = decoder->private_->output[1][i];
1407                                         mid <<= 1;
1408                                         if(side & 1) /* i.e. if 'side' is odd... */
1409                                                 mid++;
1410                                         left = mid + side;
1411                                         right = mid - side;
1412                                         decoder->private_->output[0][i] = left >> 1;
1413                                         decoder->private_->output[1][i] = right >> 1;
1414                                 }
1415                                 break;
1416                         default:
1417                                 FLAC__ASSERT(0);
1418                                 break;
1419                 }
1420         }
1421         else {
1422                 /* Bad frame, emit error and zero the output signal */
1423                 decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH, decoder->private_->client_data);
1424                 for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1425                         memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
1426                 }
1427         }
1428
1429         *got_a_frame = true;
1430
1431         /* put the latest values into the public section of the decoder instance */
1432         decoder->protected_->channels = decoder->private_->frame.header.channels;
1433         decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
1434         decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
1435         decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
1436         decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
1437
1438         FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1439         decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
1440
1441         /* write it */
1442         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)
1443                 return false;
1444
1445         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1446         return true;
1447 }
1448
1449 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
1450 {
1451         FLAC__uint32 x;
1452         FLAC__uint64 xx;
1453         unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
1454         FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
1455         unsigned raw_header_len;
1456         FLAC__bool is_unparseable = false;
1457         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);
1458         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);
1459
1460         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1461
1462         /* init the raw header with the saved bits from synchronization */
1463         raw_header[0] = decoder->private_->header_warmup[0];
1464         raw_header[1] = decoder->private_->header_warmup[1];
1465         raw_header_len = 2;
1466
1467         /*
1468          * check to make sure that the reserved bits are 0
1469          */
1470         if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
1471                 is_unparseable = true;
1472         }
1473
1474         /*
1475          * Note that along the way as we read the header, we look for a sync
1476          * code inside.  If we find one it would indicate that our original
1477          * sync was bad since there cannot be a sync code in a valid header.
1478          */
1479
1480         /*
1481          * read in the raw header as bytes so we can CRC it, and parse it on the way
1482          */
1483         for(i = 0; i < 2; i++) {
1484                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1485                         return false; /* the read_callback_ sets the state for us */
1486                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1487                         /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
1488                         decoder->private_->lookahead = (FLAC__byte)x;
1489                         decoder->private_->cached = true;
1490                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1491                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1492                         return true;
1493                 }
1494                 raw_header[raw_header_len++] = (FLAC__byte)x;
1495         }
1496
1497         switch(x = raw_header[2] >> 4) {
1498                 case 0:
1499                         if(is_known_fixed_blocksize_stream)
1500                                 decoder->private_->frame.header.blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
1501                         else
1502                                 is_unparseable = true;
1503                         break;
1504                 case 1:
1505                         decoder->private_->frame.header.blocksize = 192;
1506                         break;
1507                 case 2:
1508                 case 3:
1509                 case 4:
1510                 case 5:
1511                         decoder->private_->frame.header.blocksize = 576 << (x-2);
1512                         break;
1513                 case 6:
1514                 case 7:
1515                         blocksize_hint = x;
1516                         break;
1517                 case 8:
1518                 case 9:
1519                 case 10:
1520                 case 11:
1521                 case 12:
1522                 case 13:
1523                 case 14:
1524                 case 15:
1525                         decoder->private_->frame.header.blocksize = 256 << (x-8);
1526                         break;
1527                 default:
1528                         FLAC__ASSERT(0);
1529                         break;
1530         }
1531
1532         switch(x = raw_header[2] & 0x0f) {
1533                 case 0:
1534                         if(decoder->private_->has_stream_info)
1535                                 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
1536                         else
1537                                 is_unparseable = true;
1538                         break;
1539                 case 1:
1540                 case 2:
1541                 case 3:
1542                         is_unparseable = true;
1543                         break;
1544                 case 4:
1545                         decoder->private_->frame.header.sample_rate = 8000;
1546                         break;
1547                 case 5:
1548                         decoder->private_->frame.header.sample_rate = 16000;
1549                         break;
1550                 case 6:
1551                         decoder->private_->frame.header.sample_rate = 22050;
1552                         break;
1553                 case 7:
1554                         decoder->private_->frame.header.sample_rate = 24000;
1555                         break;
1556                 case 8:
1557                         decoder->private_->frame.header.sample_rate = 32000;
1558                         break;
1559                 case 9:
1560                         decoder->private_->frame.header.sample_rate = 44100;
1561                         break;
1562                 case 10:
1563                         decoder->private_->frame.header.sample_rate = 48000;
1564                         break;
1565                 case 11:
1566                         decoder->private_->frame.header.sample_rate = 96000;
1567                         break;
1568                 case 12:
1569                 case 13:
1570                 case 14:
1571                         sample_rate_hint = x;
1572                         break;
1573                 case 15:
1574                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1575                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1576                         return true;
1577                 default:
1578                         FLAC__ASSERT(0);
1579         }
1580
1581         x = (unsigned)(raw_header[3] >> 4);
1582         if(x & 8) {
1583                 decoder->private_->frame.header.channels = 2;
1584                 switch(x & 7) {
1585                         case 0:
1586                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
1587                                 break;
1588                         case 1:
1589                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
1590                                 break;
1591                         case 2:
1592                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
1593                                 break;
1594                         default:
1595                                 is_unparseable = true;
1596                                 break;
1597                 }
1598         }
1599         else {
1600                 decoder->private_->frame.header.channels = (unsigned)x + 1;
1601                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
1602         }
1603
1604         switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
1605                 case 0:
1606                         if(decoder->private_->has_stream_info)
1607                                 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
1608                         else
1609                                 is_unparseable = true;
1610                         break;
1611                 case 1:
1612                         decoder->private_->frame.header.bits_per_sample = 8;
1613                         break;
1614                 case 2:
1615                         decoder->private_->frame.header.bits_per_sample = 12;
1616                         break;
1617                 case 4:
1618                         decoder->private_->frame.header.bits_per_sample = 16;
1619                         break;
1620                 case 5:
1621                         decoder->private_->frame.header.bits_per_sample = 20;
1622                         break;
1623                 case 6:
1624                         decoder->private_->frame.header.bits_per_sample = 24;
1625                         break;
1626                 case 3:
1627                 case 7:
1628                         is_unparseable = true;
1629                         break;
1630                 default:
1631                         FLAC__ASSERT(0);
1632                         break;
1633         }
1634
1635         if(raw_header[3] & 0x01) { /* this should be a zero padding bit */
1636                 decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1637                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1638                 return true;
1639         }
1640
1641         if(blocksize_hint && is_known_variable_blocksize_stream) {
1642                 if(!FLAC__bitbuffer_read_utf8_uint64(decoder->private_->input, &xx, read_callback_, decoder, raw_header, &raw_header_len))
1643                         return false; /* the read_callback_ sets the state for us */
1644                 if(xx == 0xffffffffffffffff) { /* i.e. non-UTF8 code... */
1645                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
1646                         decoder->private_->cached = true;
1647                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1648                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1649                         return true;
1650                 }
1651                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
1652                 decoder->private_->frame.header.number.sample_number = xx;
1653         }
1654         else {
1655                 if(!FLAC__bitbuffer_read_utf8_uint32(decoder->private_->input, &x, read_callback_, decoder, raw_header, &raw_header_len))
1656                         return false; /* the read_callback_ sets the state for us */
1657                 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
1658                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
1659                         decoder->private_->cached = true;
1660                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1661                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1662                         return true;
1663                 }
1664                 decoder->private_->last_frame_number = x;
1665                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
1666                 if(blocksize_hint) {
1667                         if(decoder->private_->has_stream_info)
1668                                 decoder->private_->frame.header.number.sample_number = (FLAC__int64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__int64)x;
1669                         else
1670                                 is_unparseable = true;
1671                 }
1672                 else    
1673                         decoder->private_->frame.header.number.sample_number = (FLAC__int64)decoder->private_->frame.header.blocksize * (FLAC__int64)x;
1674         }
1675
1676         if(blocksize_hint) {
1677                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1678                         return false; /* the read_callback_ sets the state for us */
1679                 raw_header[raw_header_len++] = (FLAC__byte)x;
1680                 if(blocksize_hint == 7) {
1681                         FLAC__uint32 _x;
1682                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
1683                                 return false; /* the read_callback_ sets the state for us */
1684                         raw_header[raw_header_len++] = (FLAC__byte)_x;
1685                         x = (x << 8) | _x;
1686                 }
1687                 decoder->private_->frame.header.blocksize = x+1;
1688         }
1689
1690         if(sample_rate_hint) {
1691                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1692                         return false; /* the read_callback_ sets the state for us */
1693                 raw_header[raw_header_len++] = (FLAC__byte)x;
1694                 if(sample_rate_hint != 12) {
1695                         FLAC__uint32 _x;
1696                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
1697                                 return false; /* the read_callback_ sets the state for us */
1698                         raw_header[raw_header_len++] = (FLAC__byte)_x;
1699                         x = (x << 8) | _x;
1700                 }
1701                 if(sample_rate_hint == 12)
1702                         decoder->private_->frame.header.sample_rate = x*1000;
1703                 else if(sample_rate_hint == 13)
1704                         decoder->private_->frame.header.sample_rate = x;
1705                 else
1706                         decoder->private_->frame.header.sample_rate = x*10;
1707         }
1708
1709         /* read the CRC-8 byte */
1710         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1711                 return false; /* the read_callback_ sets the state for us */
1712         crc8 = (FLAC__byte)x;
1713
1714         if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
1715                 decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, decoder->private_->client_data);
1716                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1717                 return true;
1718         }
1719
1720         if(is_unparseable) {
1721                 decoder->protected_->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1722                 return false;
1723         }
1724
1725         return true;
1726 }
1727
1728 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps)
1729 {
1730         FLAC__uint32 x;
1731         FLAC__bool wasted_bits;
1732
1733         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder)) /* MAGIC NUMBER */
1734                 return false; /* the read_callback_ sets the state for us */
1735
1736         wasted_bits = (x & 1);
1737         x &= 0xfe;
1738
1739         if(wasted_bits) {
1740                 unsigned u;
1741                 if(!FLAC__bitbuffer_read_unary_unsigned(decoder->private_->input, &u, read_callback_, decoder))
1742                         return false; /* the read_callback_ sets the state for us */
1743                 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
1744                 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
1745         }
1746         else
1747                 decoder->private_->frame.subframes[channel].wasted_bits = 0;
1748
1749         /*
1750          * Lots of magic numbers here
1751          */
1752         if(x & 0x80) {
1753                 decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, decoder->private_->client_data);
1754                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1755                 return true;
1756         }
1757         else if(x == 0) {
1758                 if(!read_subframe_constant_(decoder, channel, bps))
1759                         return false;
1760         }
1761         else if(x == 2) {
1762                 if(!read_subframe_verbatim_(decoder, channel, bps))
1763                         return false;
1764         }
1765         else if(x < 16) {
1766                 decoder->protected_->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1767                 return false;
1768         }
1769         else if(x <= 24) {
1770                 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7))
1771                         return false;
1772         }
1773         else if(x < 64) {
1774                 decoder->protected_->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1775                 return false;
1776         }
1777         else {
1778                 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1))
1779                         return false;
1780         }
1781
1782         if(wasted_bits) {
1783                 unsigned i;
1784                 x = decoder->private_->frame.subframes[channel].wasted_bits;
1785                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1786                         decoder->private_->output[channel][i] <<= x;
1787         }
1788
1789         return true;
1790 }
1791
1792 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps)
1793 {
1794         FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
1795         FLAC__int32 x;
1796         unsigned i;
1797         FLAC__int32 *output = decoder->private_->output[channel];
1798
1799         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
1800
1801         if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
1802                 return false; /* the read_callback_ sets the state for us */
1803
1804         subframe->value = x;
1805
1806         /* decode the subframe */
1807         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1808                 output[i] = x;
1809
1810         return true;
1811 }
1812
1813 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order)
1814 {
1815         FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
1816         FLAC__int32 i32;
1817         FLAC__uint32 u32;
1818         unsigned u;
1819
1820         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
1821
1822         subframe->residual = decoder->private_->residual[channel];
1823         subframe->order = order;
1824
1825         /* read warm-up samples */
1826         for(u = 0; u < order; u++) {
1827                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
1828                         return false; /* the read_callback_ sets the state for us */
1829                 subframe->warmup[u] = i32;
1830         }
1831
1832         /* read entropy coding method info */
1833         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
1834                 return false; /* the read_callback_ sets the state for us */
1835         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
1836         switch(subframe->entropy_coding_method.type) {
1837                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1838                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
1839                                 return false; /* the read_callback_ sets the state for us */
1840                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
1841                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
1842                         break;
1843                 default:
1844                         decoder->protected_->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1845                         return false;
1846         }
1847
1848         /* read residual */
1849         switch(subframe->entropy_coding_method.type) {
1850                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1851                         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]))
1852                                 return false;
1853                         break;
1854                 default:
1855                         FLAC__ASSERT(0);
1856         }
1857
1858         /* decode the subframe */
1859         memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
1860         FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
1861
1862         return true;
1863 }
1864
1865 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order)
1866 {
1867         FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
1868         FLAC__int32 i32;
1869         FLAC__uint32 u32;
1870         unsigned u;
1871
1872         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
1873
1874         subframe->residual = decoder->private_->residual[channel];
1875         subframe->order = order;
1876
1877         /* read warm-up samples */
1878         for(u = 0; u < order; u++) {
1879                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
1880                         return false; /* the read_callback_ sets the state for us */
1881                 subframe->warmup[u] = i32;
1882         }
1883
1884         /* read qlp coeff precision */
1885         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN, read_callback_, decoder))
1886                 return false; /* the read_callback_ sets the state for us */
1887         if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
1888                 decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, decoder->private_->client_data);
1889                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1890                 return true;
1891         }
1892         subframe->qlp_coeff_precision = u32+1;
1893
1894         /* read qlp shift */
1895         if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN, read_callback_, decoder))
1896                 return false; /* the read_callback_ sets the state for us */
1897         subframe->quantization_level = i32;
1898
1899         /* read quantized lp coefficiencts */
1900         for(u = 0; u < order; u++) {
1901                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision, read_callback_, decoder))
1902                         return false; /* the read_callback_ sets the state for us */
1903                 subframe->qlp_coeff[u] = i32;
1904         }
1905
1906         /* read entropy coding method info */
1907         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
1908                 return false; /* the read_callback_ sets the state for us */
1909         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
1910         switch(subframe->entropy_coding_method.type) {
1911                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1912                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
1913                                 return false; /* the read_callback_ sets the state for us */
1914                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
1915                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
1916                         break;
1917                 default:
1918                         decoder->protected_->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1919                         return false;
1920         }
1921
1922         /* read residual */
1923         switch(subframe->entropy_coding_method.type) {
1924                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1925                         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]))
1926                                 return false;
1927                         break;
1928                 default:
1929                         FLAC__ASSERT(0);
1930         }
1931
1932         /* decode the subframe */
1933         memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
1934         if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
1935                 if(bps <= 16 && subframe->qlp_coeff_precision <= 16)
1936                         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);
1937                 else
1938                         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);
1939         else
1940                 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);
1941
1942         return true;
1943 }
1944
1945 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps)
1946 {
1947         FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
1948         FLAC__int32 x, *residual = decoder->private_->residual[channel];
1949         unsigned i;
1950
1951         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
1952
1953         subframe->data = residual;
1954
1955         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
1956                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
1957                         return false; /* the read_callback_ sets the state for us */
1958                 residual[i] = x;
1959         }
1960
1961         /* decode the subframe */
1962         memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
1963
1964         return true;
1965 }
1966
1967 FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual)
1968 {
1969         FLAC__uint32 rice_parameter;
1970         int i;
1971         unsigned partition, sample, u;
1972         const unsigned partitions = 1u << partition_order;
1973         const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
1974
1975         if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
1976                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1977                 return false;
1978         }
1979
1980         sample = 0;
1981         for(partition = 0; partition < partitions; partition++) {
1982                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN, read_callback_, decoder))
1983                         return false; /* the read_callback_ sets the state for us */
1984                 partitioned_rice_contents->parameters[partition] = rice_parameter;
1985                 if(rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1986 #ifdef FLAC__SYMMETRIC_RICE
1987                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
1988                                 if(!FLAC__bitbuffer_read_symmetric_rice_signed(decoder->private_->input, &i, rice_parameter, read_callback_, decoder))
1989                                         return false; /* the read_callback_ sets the state for us */
1990                                 residual[sample] = i;
1991                         }
1992 #else
1993                         u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
1994                         if(!FLAC__bitbuffer_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter, read_callback_, decoder))
1995                                 return false; /* the read_callback_ sets the state for us */
1996                         sample += u;
1997 #endif
1998                 }
1999                 else {
2000                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN, read_callback_, decoder))
2001                                 return false; /* the read_callback_ sets the state for us */
2002                         partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2003                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2004                                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i, rice_parameter, read_callback_, decoder))
2005                                         return false; /* the read_callback_ sets the state for us */
2006                                 residual[sample] = i;
2007                         }
2008                 }
2009         }
2010
2011         return true;
2012 }
2013
2014 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2015 {
2016         if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
2017                 FLAC__uint32 zero = 0;
2018                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
2019                         return false; /* the read_callback_ sets the state for us */
2020                 if(zero != 0) {
2021                         decoder->private_->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, decoder->private_->client_data);
2022                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2023                 }
2024         }
2025         return true;
2026 }
2027
2028 FLAC__bool read_callback_(FLAC__byte buffer[], unsigned *bytes, void *client_data)
2029 {
2030         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2031         FLAC__StreamDecoderReadStatus status;
2032
2033         status = decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data);
2034         if(status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM)
2035                 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2036         else if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT)
2037                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2038         return status == FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2039 }