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