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