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