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