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