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