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