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