remove debug printouts
[platform/upstream/flac.git] / src / libFLAC / stream_decoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001  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 "FLAC/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 typedef struct FLAC__StreamDecoderPrivate {
32         FLAC__StreamDecoderReadStatus (*read_callback)(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data);
33         FLAC__StreamDecoderWriteStatus (*write_callback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data);
34         void (*metadata_callback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
35         void (*error_callback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
36         void (*local_lpc_restore_signal)(const int32 residual[], unsigned data_len, const int32 qlp_coeff[], unsigned order, int lp_quantization, int32 data[]);
37         void (*local_lpc_restore_signal_16bit)(const int32 residual[], unsigned data_len, const int32 qlp_coeff[], unsigned order, int lp_quantization, int32 data[]);
38         void *client_data;
39         FLAC__BitBuffer input;
40         int32 *output[FLAC__MAX_CHANNELS];
41         int32 *residual[FLAC__MAX_CHANNELS];
42         unsigned output_capacity, output_channels;
43         uint32 last_frame_number;
44         uint64 samples_decoded;
45         bool has_stream_info, has_seek_table;
46         FLAC__StreamMetaData stream_info;
47         FLAC__StreamMetaData seek_table;
48         FLAC__Frame frame;
49         bool cached; /* true if there is a byte in lookahead */
50         FLAC__CPUInfo cpuinfo;
51         byte header_warmup[2]; /* contains the sync code and reserved bits */
52         byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
53 } FLAC__StreamDecoderPrivate;
54
55 static byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
56
57 static bool stream_decoder_allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
58 static bool stream_decoder_find_metadata_(FLAC__StreamDecoder *decoder);
59 static bool stream_decoder_read_metadata_(FLAC__StreamDecoder *decoder);
60 static bool stream_decoder_skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
61 static bool stream_decoder_frame_sync_(FLAC__StreamDecoder *decoder);
62 static bool stream_decoder_read_frame_(FLAC__StreamDecoder *decoder, bool *got_a_frame);
63 static bool stream_decoder_read_frame_header_(FLAC__StreamDecoder *decoder);
64 static bool stream_decoder_read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps);
65 static bool stream_decoder_read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps);
66 static bool stream_decoder_read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order);
67 static bool stream_decoder_read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order);
68 static bool stream_decoder_read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps);
69 static bool stream_decoder_read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, int32 *residual);
70 static bool stream_decoder_read_zero_padding_(FLAC__StreamDecoder *decoder);
71 static bool read_callback_(byte buffer[], unsigned *bytes, void *client_data);
72
73 const char *FLAC__StreamDecoderStateString[] = {
74         "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
75         "FLAC__STREAM_DECODER_READ_METADATA",
76         "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
77         "FLAC__STREAM_DECODER_READ_FRAME",
78         "FLAC__STREAM_DECODER_END_OF_STREAM",
79         "FLAC__STREAM_DECODER_ABORTED",
80         "FLAC__STREAM_DECODER_UNPARSEABLE_STREAM",
81         "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
82         "FLAC__STREAM_DECODER_UNINITIALIZED"
83 };
84
85 const char *FLAC__StreamDecoderReadStatusString[] = {
86         "FLAC__STREAM_DECODER_READ_CONTINUE",
87         "FLAC__STREAM_DECODER_READ_END_OF_STREAM",
88         "FLAC__STREAM_DECODER_READ_ABORT"
89 };
90
91 const char *FLAC__StreamDecoderWriteStatusString[] = {
92         "FLAC__STREAM_DECODER_WRITE_CONTINUE",
93         "FLAC__STREAM_DECODER_WRITE_ABORT"
94 };
95
96 const char *FLAC__StreamDecoderErrorStatusString[] = {
97         "FLAC__STREAM_DECODER_ERROR_LOST_SYNC",
98         "FLAC__STREAM_DECODER_ERROR_BAD_HEADER",
99         "FLAC__STREAM_DECODER_ERROR_FRAME_CRC_MISMATCH"
100 };
101
102 FLAC__StreamDecoder *FLAC__stream_decoder_get_new_instance()
103 {
104         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)malloc(sizeof(FLAC__StreamDecoder));
105         if(decoder != 0) {
106                 decoder->state = FLAC__STREAM_DECODER_UNINITIALIZED;
107                 decoder->guts = 0;
108         }
109         return decoder;
110 }
111
112 void FLAC__stream_decoder_free_instance(FLAC__StreamDecoder *decoder)
113 {
114         free(decoder);
115 }
116
117 FLAC__StreamDecoderState FLAC__stream_decoder_init(
118         FLAC__StreamDecoder *decoder,
119         FLAC__StreamDecoderReadStatus (*read_callback)(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data),
120         FLAC__StreamDecoderWriteStatus (*write_callback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data),
121         void (*metadata_callback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data),
122         void (*error_callback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data),
123         void *client_data
124 )
125 {
126         unsigned i;
127
128         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
129         FLAC__ASSERT(decoder != 0);
130         FLAC__ASSERT(read_callback != 0);
131         FLAC__ASSERT(write_callback != 0);
132         FLAC__ASSERT(metadata_callback != 0);
133         FLAC__ASSERT(error_callback != 0);
134         FLAC__ASSERT(decoder->state == FLAC__STREAM_DECODER_UNINITIALIZED);
135         FLAC__ASSERT(decoder->guts == 0);
136
137         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
138
139         decoder->guts = (FLAC__StreamDecoderPrivate*)malloc(sizeof(FLAC__StreamDecoderPrivate));
140         if(decoder->guts == 0)
141                 return decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
142
143         decoder->guts->read_callback = read_callback;
144         decoder->guts->write_callback = write_callback;
145         decoder->guts->metadata_callback = metadata_callback;
146         decoder->guts->error_callback = error_callback;
147         decoder->guts->client_data = client_data;
148
149         FLAC__bitbuffer_init(&decoder->guts->input);
150
151         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
152                 decoder->guts->output[i] = 0;
153                 decoder->guts->residual[i] = 0;
154         }
155
156         decoder->guts->output_capacity = 0;
157         decoder->guts->output_channels = 0;
158         decoder->guts->last_frame_number = 0;
159         decoder->guts->samples_decoded = 0;
160         decoder->guts->has_stream_info = false;
161         decoder->guts->has_seek_table = false;
162         decoder->guts->cached = false;
163
164         /*
165          * get the CPU info and set the function pointers
166          */
167         FLAC__cpu_info(&decoder->guts->cpuinfo);
168         /* first default to the non-asm routines */
169         decoder->guts->local_lpc_restore_signal = FLAC__lpc_restore_signal;
170         decoder->guts->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
171         /* now override with asm where appropriate */
172 #ifndef FLAC__NO_ASM
173         FLAC__ASSERT(decoder->guts->cpuinfo.use_asm);
174 #ifdef FLAC__CPU_IA32
175         FLAC__ASSERT(decoder->guts->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
176 #ifdef FLAC__HAS_NASM
177         if(decoder->guts->cpuinfo.data.ia32.mmx) {
178                 decoder->guts->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_i386;
179                 decoder->guts->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_i386_mmx;
180         }
181         else {
182                 decoder->guts->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_i386;
183                 decoder->guts->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_i386;
184         }
185 #endif
186 #endif
187 #endif
188
189         return decoder->state;
190 }
191
192 void FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
193 {
194         unsigned i;
195         FLAC__ASSERT(decoder != 0);
196         if(decoder->state == FLAC__STREAM_DECODER_UNINITIALIZED)
197                 return;
198         if(decoder->guts != 0) {
199                 if(decoder->guts->has_seek_table) {
200                         free(decoder->guts->seek_table.data.seek_table.points);
201                         decoder->guts->seek_table.data.seek_table.points = 0;
202                 }
203                 FLAC__bitbuffer_free(&decoder->guts->input);
204                 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
205                         if(decoder->guts->output[i] != 0) {
206                                 free(decoder->guts->output[i]);
207                                 decoder->guts->output[i] = 0;
208                         }
209                         if(decoder->guts->residual[i] != 0) {
210                                 free(decoder->guts->residual[i]);
211                                 decoder->guts->residual[i] = 0;
212                         }
213                 }
214                 free(decoder->guts);
215                 decoder->guts = 0;
216         }
217         decoder->state = FLAC__STREAM_DECODER_UNINITIALIZED;
218 }
219
220 bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
221 {
222         FLAC__ASSERT(decoder != 0);
223
224         if(!FLAC__bitbuffer_clear(&decoder->guts->input)) {
225                 decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
226                 return false;
227         }
228
229         return true;
230 }
231
232 bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
233 {
234         FLAC__ASSERT(decoder != 0);
235
236         if(!FLAC__stream_decoder_flush(decoder)) {
237                 decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
238                 return false;
239         }
240         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
241
242         decoder->guts->samples_decoded = 0;
243
244         return true;
245 }
246
247 bool FLAC__stream_decoder_process_whole_stream(FLAC__StreamDecoder *decoder)
248 {
249         bool dummy;
250         FLAC__ASSERT(decoder != 0);
251
252         if(decoder->state == FLAC__STREAM_DECODER_END_OF_STREAM)
253                 return true;
254
255         FLAC__ASSERT(decoder->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA);
256
257         if(!FLAC__stream_decoder_reset(decoder)) {
258                 decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
259                 return false;
260         }
261
262         while(1) {
263                 switch(decoder->state) {
264                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
265                                 if(!stream_decoder_find_metadata_(decoder))
266                                         return false; /* above function sets the status for us */
267                                 break;
268                         case FLAC__STREAM_DECODER_READ_METADATA:
269                                 if(!stream_decoder_read_metadata_(decoder))
270                                         return false; /* above function sets the status for us */
271                                 break;
272                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
273                                 if(!stream_decoder_frame_sync_(decoder))
274                                         return true; /* above function sets the status for us */
275                                 break;
276                         case FLAC__STREAM_DECODER_READ_FRAME:
277                                 if(!stream_decoder_read_frame_(decoder, &dummy))
278                                         return false; /* above function sets the status for us */
279                                 break;
280                         case FLAC__STREAM_DECODER_END_OF_STREAM:
281                                 return true;
282                         default:
283                                 FLAC__ASSERT(0);
284                 }
285         }
286 }
287
288 bool FLAC__stream_decoder_process_metadata(FLAC__StreamDecoder *decoder)
289 {
290         FLAC__ASSERT(decoder != 0);
291
292         if(decoder->state == FLAC__STREAM_DECODER_END_OF_STREAM)
293                 return true;
294
295         FLAC__ASSERT(decoder->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA);
296
297         if(!FLAC__stream_decoder_reset(decoder)) {
298                 decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
299                 return false;
300         }
301
302         while(1) {
303                 switch(decoder->state) {
304                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
305                                 if(!stream_decoder_find_metadata_(decoder))
306                                         return false; /* above function sets the status for us */
307                                 break;
308                         case FLAC__STREAM_DECODER_READ_METADATA:
309                                 if(!stream_decoder_read_metadata_(decoder))
310                                         return false; /* above function sets the status for us */
311                                 break;
312                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
313                                 return true;
314                                 break;
315                         case FLAC__STREAM_DECODER_END_OF_STREAM:
316                                 return true;
317                         default:
318                                 FLAC__ASSERT(0);
319                 }
320         }
321 }
322
323 bool FLAC__stream_decoder_process_one_frame(FLAC__StreamDecoder *decoder)
324 {
325         bool got_a_frame;
326         FLAC__ASSERT(decoder != 0);
327
328         if(decoder->state == FLAC__STREAM_DECODER_END_OF_STREAM)
329                 return true;
330
331         FLAC__ASSERT(decoder->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC);
332
333         while(1) {
334                 switch(decoder->state) {
335                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
336                                 if(!stream_decoder_frame_sync_(decoder))
337                                         return true; /* above function sets the status for us */
338                                 break;
339                         case FLAC__STREAM_DECODER_READ_FRAME:
340                                 if(!stream_decoder_read_frame_(decoder, &got_a_frame))
341                                         return false; /* above function sets the status for us */
342                                 if(got_a_frame)
343                                         return true; /* above function sets the status for us */
344                                 break;
345                         case FLAC__STREAM_DECODER_END_OF_STREAM:
346                                 return true;
347                         default:
348                                 FLAC__ASSERT(0);
349                 }
350         }
351 }
352
353 bool FLAC__stream_decoder_process_remaining_frames(FLAC__StreamDecoder *decoder)
354 {
355         bool dummy;
356         FLAC__ASSERT(decoder != 0);
357
358         if(decoder->state == FLAC__STREAM_DECODER_END_OF_STREAM)
359                 return true;
360
361         FLAC__ASSERT(decoder->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC);
362
363         while(1) {
364                 switch(decoder->state) {
365                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
366                                 if(!stream_decoder_frame_sync_(decoder))
367                                         return true; /* above function sets the status for us */
368                                 break;
369                         case FLAC__STREAM_DECODER_READ_FRAME:
370                                 if(!stream_decoder_read_frame_(decoder, &dummy))
371                                         return false; /* above function sets the status for us */
372                                 break;
373                         case FLAC__STREAM_DECODER_END_OF_STREAM:
374                                 return true;
375                         default:
376                                 FLAC__ASSERT(0);
377                 }
378         }
379 }
380
381 unsigned FLAC__stream_decoder_input_bytes_unconsumed(FLAC__StreamDecoder *decoder)
382 {
383         FLAC__ASSERT(decoder != 0);
384         return decoder->guts->input.bytes - decoder->guts->input.consumed_bytes;
385 }
386
387 bool stream_decoder_allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
388 {
389         unsigned i;
390         int32 *tmp;
391
392         if(size <= decoder->guts->output_capacity && channels <= decoder->guts->output_channels)
393                 return true;
394
395         /* @@@ should change to use realloc() */
396
397         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
398                 if(decoder->guts->output[i] != 0) {
399                         free(decoder->guts->output[i]);
400                         decoder->guts->output[i] = 0;
401                 }
402                 if(decoder->guts->residual[i] != 0) {
403                         free(decoder->guts->residual[i]);
404                         decoder->guts->residual[i] = 0;
405                 }
406         }
407
408         for(i = 0; i < channels; i++) {
409                 tmp = (int32*)malloc(sizeof(int32)*size);
410                 if(tmp == 0) {
411                         decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
412                         return false;
413                 }
414                 decoder->guts->output[i] = tmp;
415
416                 tmp = (int32*)malloc(sizeof(int32)*size);
417                 if(tmp == 0) {
418                         decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
419                         return false;
420                 }
421                 decoder->guts->residual[i] = tmp;
422         }
423
424         decoder->guts->output_capacity = size;
425         decoder->guts->output_channels = channels;
426
427         return true;
428 }
429
430 bool stream_decoder_find_metadata_(FLAC__StreamDecoder *decoder)
431 {
432         uint32 x;
433         unsigned i, id;
434         bool first = true;
435
436         FLAC__ASSERT(decoder->guts->input.consumed_bits == 0); /* make sure we're byte aligned */
437
438         for(i = id = 0; i < 4; ) {
439                 if(decoder->guts->cached) {
440                         x = (uint32)decoder->guts->lookahead;
441                         decoder->guts->cached = false;
442                 }
443                 else {
444                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
445                                 return false; /* the read_callback_ sets the state for us */
446                 }
447                 if(x == FLAC__STREAM_SYNC_STRING[i]) {
448                         first = true;
449                         i++;
450                         id = 0;
451                         continue;
452                 }
453                 if(x == ID3V2_TAG_[id]) {
454                         id++;
455                         i = 0;
456                         if(id == 3) {
457                                 if(!stream_decoder_skip_id3v2_tag_(decoder))
458                                         return false; /* the read_callback_ sets the state for us */
459                         }
460                         continue;
461                 }
462                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
463                         decoder->guts->header_warmup[0] = (byte)x;
464                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
465                                 return false; /* the read_callback_ sets the state for us */
466
467                         /* 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 */
468                         /* else we have to check if the second byte is the end of a sync code */
469                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
470                                 decoder->guts->lookahead = (byte)x;
471                                 decoder->guts->cached = true;
472                         }
473                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
474                                 decoder->guts->header_warmup[1] = (byte)x;
475                                 decoder->state = FLAC__STREAM_DECODER_READ_FRAME;
476                                 return true;
477                         }
478                 }
479                 i = 0;
480                 if(first) {
481                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_LOST_SYNC, decoder->guts->client_data);
482                         first = false;
483                 }
484         }
485
486         decoder->state = FLAC__STREAM_DECODER_READ_METADATA;
487         return true;
488 }
489
490 bool stream_decoder_read_metadata_(FLAC__StreamDecoder *decoder)
491 {
492         uint32 i, x, last_block, type, length;
493         uint64 xx;
494
495         FLAC__ASSERT(decoder->guts->input.consumed_bits == 0); /* make sure we're byte aligned */
496
497         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &last_block, FLAC__STREAM_METADATA_IS_LAST_LEN, read_callback_, decoder))
498                 return false; /* the read_callback_ sets the state for us */
499         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &type, FLAC__STREAM_METADATA_TYPE_LEN, read_callback_, decoder))
500                 return false; /* the read_callback_ sets the state for us */
501         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN, read_callback_, decoder))
502                 return false; /* the read_callback_ sets the state for us */
503         if(type == FLAC__METADATA_TYPE_STREAMINFO) {
504                 unsigned used_bits = 0;
505                 decoder->guts->stream_info.type = type;
506                 decoder->guts->stream_info.is_last = last_block;
507                 decoder->guts->stream_info.length = length;
508
509                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN, read_callback_, decoder))
510                         return false; /* the read_callback_ sets the state for us */
511                 decoder->guts->stream_info.data.stream_info.min_blocksize = x;
512                 used_bits += FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
513
514                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN, read_callback_, decoder))
515                         return false; /* the read_callback_ sets the state for us */
516                 decoder->guts->stream_info.data.stream_info.max_blocksize = x;
517                 used_bits += FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
518
519                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN, read_callback_, decoder))
520                         return false; /* the read_callback_ sets the state for us */
521                 decoder->guts->stream_info.data.stream_info.min_framesize = x;
522                 used_bits += FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
523
524                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN, read_callback_, decoder))
525                         return false; /* the read_callback_ sets the state for us */
526                 decoder->guts->stream_info.data.stream_info.max_framesize = x;
527                 used_bits += FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
528
529                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN, read_callback_, decoder))
530                         return false; /* the read_callback_ sets the state for us */
531                 decoder->guts->stream_info.data.stream_info.sample_rate = x;
532                 used_bits += FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
533
534                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN, read_callback_, decoder))
535                         return false; /* the read_callback_ sets the state for us */
536                 decoder->guts->stream_info.data.stream_info.channels = x+1;
537                 used_bits += FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
538
539                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN, read_callback_, decoder))
540                         return false; /* the read_callback_ sets the state for us */
541                 decoder->guts->stream_info.data.stream_info.bits_per_sample = x+1;
542                 used_bits += FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
543
544                 if(!FLAC__bitbuffer_read_raw_uint64(&decoder->guts->input, &decoder->guts->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN, read_callback_, decoder))
545                         return false; /* the read_callback_ sets the state for us */
546                 used_bits += FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
547
548                 for(i = 0; i < 16; i++) {
549                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
550                                 return false; /* the read_callback_ sets the state for us */
551                         decoder->guts->stream_info.data.stream_info.md5sum[i] = (byte)x;
552                 }
553                 used_bits += i*8;
554
555                 /* skip the rest of the block */
556                 FLAC__ASSERT(used_bits % 8 == 0);
557                 length -= (used_bits / 8);
558                 for(i = 0; i < length; i++) {
559                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
560                                 return false; /* the read_callback_ sets the state for us */
561                 }
562
563                 decoder->guts->has_stream_info = true;
564                 decoder->guts->metadata_callback(decoder, &decoder->guts->stream_info, decoder->guts->client_data);
565         }
566         else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
567                 unsigned real_points;
568
569                 decoder->guts->seek_table.type = type;
570                 decoder->guts->seek_table.is_last = last_block;
571                 decoder->guts->seek_table.length = length;
572
573                 decoder->guts->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LEN;
574
575                 if(0 == (decoder->guts->seek_table.data.seek_table.points = (FLAC__StreamMetaData_SeekPoint*)malloc(decoder->guts->seek_table.data.seek_table.num_points * sizeof(FLAC__StreamMetaData_SeekPoint)))) {
576                         decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
577                         return false;
578                 }
579                 for(i = real_points = 0; i < decoder->guts->seek_table.data.seek_table.num_points; i++) {
580                         if(!FLAC__bitbuffer_read_raw_uint64(&decoder->guts->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN, read_callback_, decoder))
581                                 return false; /* the read_callback_ sets the state for us */
582                         decoder->guts->seek_table.data.seek_table.points[real_points].sample_number = xx;
583
584                         if(!FLAC__bitbuffer_read_raw_uint64(&decoder->guts->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN, read_callback_, decoder))
585                                 return false; /* the read_callback_ sets the state for us */
586                         decoder->guts->seek_table.data.seek_table.points[real_points].stream_offset = xx;
587
588                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN, read_callback_, decoder))
589                                 return false; /* the read_callback_ sets the state for us */
590                         decoder->guts->seek_table.data.seek_table.points[real_points].frame_samples = x;
591
592                         if(decoder->guts->seek_table.data.seek_table.points[real_points].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
593                                 real_points++;
594                 }
595                 decoder->guts->seek_table.data.seek_table.num_points = real_points;
596
597                 decoder->guts->has_seek_table = true;
598                 decoder->guts->metadata_callback(decoder, &decoder->guts->seek_table, decoder->guts->client_data);
599         }
600         else {
601                 /* skip other metadata blocks */
602                 for(i = 0; i < length; i++) {
603                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
604                                 return false; /* the read_callback_ sets the state for us */
605                 }
606         }
607
608         if(last_block)
609                 decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
610
611         return true;
612 }
613
614 bool stream_decoder_skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
615 {
616         uint32 x;
617         unsigned i, skip;
618
619         /* skip the version and flags bytes */
620         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 24, read_callback_, decoder))
621                 return false; /* the read_callback_ sets the state for us */
622         /* get the size (in bytes) to skip */
623         skip = 0;
624         for(i = 0; i < 4; i++) {
625                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
626                         return false; /* the read_callback_ sets the state for us */
627                 skip <<= 7;
628                 skip |= (x & 0x7f);
629         }
630         /* skip the rest of the tag */
631         for(i = 0; i < skip; i++) {
632                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
633                         return false; /* the read_callback_ sets the state for us */
634         }
635         return true;
636 }
637
638 bool stream_decoder_frame_sync_(FLAC__StreamDecoder *decoder)
639 {
640         uint32 x;
641         bool first = true;
642
643         /* If we know the total number of samples in the stream, stop if we've read that many. */
644         /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
645         if(decoder->guts->has_stream_info && decoder->guts->stream_info.data.stream_info.total_samples) {
646                 if(decoder->guts->samples_decoded >= decoder->guts->stream_info.data.stream_info.total_samples) {
647                         decoder->state = FLAC__STREAM_DECODER_END_OF_STREAM;
648                         return true;
649                 }
650         }
651
652         /* make sure we're byte aligned */
653         if(decoder->guts->input.consumed_bits != 0) {
654                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8-decoder->guts->input.consumed_bits, read_callback_, decoder))
655                         return false; /* the read_callback_ sets the state for us */
656         }
657
658         while(1) {
659                 if(decoder->guts->cached) {
660                         x = (uint32)decoder->guts->lookahead;
661                         decoder->guts->cached = false;
662                 }
663                 else {
664                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
665                                 return false; /* the read_callback_ sets the state for us */
666                 }
667                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
668                         decoder->guts->header_warmup[0] = (byte)x;
669                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
670                                 return false; /* the read_callback_ sets the state for us */
671
672                         /* 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 */
673                         /* else we have to check if the second byte is the end of a sync code */
674                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
675                                 decoder->guts->lookahead = (byte)x;
676                                 decoder->guts->cached = true;
677                         }
678                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
679                                 decoder->guts->header_warmup[1] = (byte)x;
680                                 decoder->state = FLAC__STREAM_DECODER_READ_FRAME;
681                                 return true;
682                         }
683                 }
684                 if(first) {
685                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_LOST_SYNC, decoder->guts->client_data);
686                         first = 0;
687                 }
688         }
689
690         return true;
691 }
692
693 bool stream_decoder_read_frame_(FLAC__StreamDecoder *decoder, bool *got_a_frame)
694 {
695         unsigned channel;
696         unsigned i;
697         int32 mid, side, left, right;
698         uint16 frame_crc; /* the one we calculate from the input stream */
699         uint32 x;
700
701         *got_a_frame = false;
702
703         /* init the CRC */
704         frame_crc = 0;
705         FLAC__CRC16_UPDATE(decoder->guts->header_warmup[0], frame_crc);
706         FLAC__CRC16_UPDATE(decoder->guts->header_warmup[1], frame_crc);
707         FLAC__bitbuffer_init_read_crc16(&decoder->guts->input, frame_crc);
708
709         if(!stream_decoder_read_frame_header_(decoder))
710                 return false;
711         if(decoder->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC)
712                 return true;
713         if(!stream_decoder_allocate_output_(decoder, decoder->guts->frame.header.blocksize, decoder->guts->frame.header.channels))
714                 return false;
715         for(channel = 0; channel < decoder->guts->frame.header.channels; channel++) {
716                 /*
717                  * first figure the correct bits-per-sample of the subframe
718                  */
719                 unsigned bps = decoder->guts->frame.header.bits_per_sample;
720                 switch(decoder->guts->frame.header.channel_assignment) {
721                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
722                                 /* no adjustment needed */
723                                 break;
724                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
725                                 FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
726                                 if(channel == 1)
727                                         bps++;
728                                 break;
729                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
730                                 FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
731                                 if(channel == 0)
732                                         bps++;
733                                 break;
734                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
735                                 FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
736                                 if(channel == 1)
737                                         bps++;
738                                 break;
739                         default:
740                                 FLAC__ASSERT(0);
741                 }
742                 /*
743                  * now read it
744                  */
745                 if(!stream_decoder_read_subframe_(decoder, channel, bps))
746                         return false;
747                 if(decoder->state != FLAC__STREAM_DECODER_READ_FRAME) {
748                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
749                         return true;
750                 }
751         }
752         if(!stream_decoder_read_zero_padding_(decoder))
753                 return false;
754
755         /*
756          * Read the frame CRC-16 from the footer and check
757          */
758         frame_crc = decoder->guts->input.read_crc16;
759         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__FRAME_FOOTER_CRC_LEN, read_callback_, decoder))
760                 return false; /* the read_callback_ sets the state for us */
761         if(frame_crc == (uint16)x) {
762                 /* Undo any special channel coding */
763                 switch(decoder->guts->frame.header.channel_assignment) {
764                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
765                                 /* do nothing */
766                                 break;
767                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
768                                 FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
769                                 for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
770                                         decoder->guts->output[1][i] = decoder->guts->output[0][i] - decoder->guts->output[1][i];
771                                 break;
772                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
773                                 FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
774                                 for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
775                                         decoder->guts->output[0][i] += decoder->guts->output[1][i];
776                                 break;
777                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
778                                 FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
779                                 for(i = 0; i < decoder->guts->frame.header.blocksize; i++) {
780                                         mid = decoder->guts->output[0][i];
781                                         side = decoder->guts->output[1][i];
782                                         mid <<= 1;
783                                         if(side & 1) /* i.e. if 'side' is odd... */
784                                                 mid++;
785                                         left = mid + side;
786                                         right = mid - side;
787                                         decoder->guts->output[0][i] = left >> 1;
788                                         decoder->guts->output[1][i] = right >> 1;
789                                 }
790                                 break;
791                         default:
792                                 FLAC__ASSERT(0);
793                                 break;
794                 }
795         }
796         else {
797                 /* Bad frame, emit error and zero the output signal */
798                 decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_FRAME_CRC_MISMATCH, decoder->guts->client_data);
799                 for(channel = 0; channel < decoder->guts->frame.header.channels; channel++) {
800                         memset(decoder->guts->output[channel], 0, sizeof(int32) * decoder->guts->frame.header.blocksize);
801                 }
802         }
803
804         *got_a_frame = true;
805
806         /* put the latest values into the public section of the decoder instance */
807         decoder->channels = decoder->guts->frame.header.channels;
808         decoder->channel_assignment = decoder->guts->frame.header.channel_assignment;
809         decoder->bits_per_sample = decoder->guts->frame.header.bits_per_sample;
810         decoder->sample_rate = decoder->guts->frame.header.sample_rate;
811         decoder->blocksize = decoder->guts->frame.header.blocksize;
812
813         decoder->guts->samples_decoded = decoder->guts->frame.header.number.sample_number + decoder->guts->frame.header.blocksize;
814
815         /* write it */
816         /* 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: */
817         if(decoder->guts->write_callback(decoder, &decoder->guts->frame, decoder->guts->output, decoder->guts->client_data) != FLAC__STREAM_DECODER_WRITE_CONTINUE)
818                 return false;
819
820         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
821         return true;
822 }
823
824 bool stream_decoder_read_frame_header_(FLAC__StreamDecoder *decoder)
825 {
826         uint32 x;
827         uint64 xx;
828         unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
829         byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
830         unsigned raw_header_len;
831         bool is_unparseable = false;
832         const bool is_known_variable_blocksize_stream = (decoder->guts->has_stream_info && decoder->guts->stream_info.data.stream_info.min_blocksize != decoder->guts->stream_info.data.stream_info.max_blocksize);
833         const bool is_known_fixed_blocksize_stream = (decoder->guts->has_stream_info && decoder->guts->stream_info.data.stream_info.min_blocksize == decoder->guts->stream_info.data.stream_info.max_blocksize);
834
835         FLAC__ASSERT(decoder->guts->input.consumed_bits == 0); /* make sure we're byte aligned */
836
837         /* init the raw header with the saved bits from synchronization */
838         raw_header[0] = decoder->guts->header_warmup[0];
839         raw_header[1] = decoder->guts->header_warmup[1];
840         raw_header_len = 2;
841
842         /*
843          * check to make sure that the reserved bits are 0
844          */
845         if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
846                 is_unparseable = true;
847         }
848
849         /*
850          * Note that along the way as we read the header, we look for a sync
851          * code inside.  If we find one it would indicate that our original
852          * sync was bad since there cannot be a sync code in a valid header.
853          */
854
855         /*
856          * read in the raw header as bytes so we can CRC it, and parse it on the way
857          */
858         for(i = 0; i < 2; i++) {
859                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
860                         return false; /* the read_callback_ sets the state for us */
861                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
862                         /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
863                         decoder->guts->lookahead = (byte)x;
864                         decoder->guts->cached = true;
865                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
866                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
867                         return true;
868                 }
869                 raw_header[raw_header_len++] = (byte)x;
870         }
871
872         switch(x = raw_header[2] >> 4) {
873                 case 0:
874                         if(is_known_fixed_blocksize_stream)
875                                 decoder->guts->frame.header.blocksize = decoder->guts->stream_info.data.stream_info.min_blocksize;
876                         else
877                                 is_unparseable = true;
878                         break;
879                 case 1:
880                         decoder->guts->frame.header.blocksize = 192;
881                         break;
882                 case 2:
883                 case 3:
884                 case 4:
885                 case 5:
886                         decoder->guts->frame.header.blocksize = 576 << (x-2);
887                         break;
888                 case 6:
889                 case 7:
890                         blocksize_hint = x;
891                         break;
892                 case 8:
893                 case 9:
894                 case 10:
895                 case 11:
896                 case 12:
897                 case 13:
898                 case 14:
899                 case 15:
900                         decoder->guts->frame.header.blocksize = 256 << (x-8);
901                         break;
902                 default:
903                         FLAC__ASSERT(0);
904                         break;
905         }
906
907         switch(x = raw_header[2] & 0x0f) {
908                 case 0:
909                         if(decoder->guts->has_stream_info)
910                                 decoder->guts->frame.header.sample_rate = decoder->guts->stream_info.data.stream_info.sample_rate;
911                         else
912                                 is_unparseable = true;
913                         break;
914                 case 1:
915                 case 2:
916                 case 3:
917                         is_unparseable = true;
918                         break;
919                 case 4:
920                         decoder->guts->frame.header.sample_rate = 8000;
921                         break;
922                 case 5:
923                         decoder->guts->frame.header.sample_rate = 16000;
924                         break;
925                 case 6:
926                         decoder->guts->frame.header.sample_rate = 22050;
927                         break;
928                 case 7:
929                         decoder->guts->frame.header.sample_rate = 24000;
930                         break;
931                 case 8:
932                         decoder->guts->frame.header.sample_rate = 32000;
933                         break;
934                 case 9:
935                         decoder->guts->frame.header.sample_rate = 44100;
936                         break;
937                 case 10:
938                         decoder->guts->frame.header.sample_rate = 48000;
939                         break;
940                 case 11:
941                         decoder->guts->frame.header.sample_rate = 96000;
942                         break;
943                 case 12:
944                 case 13:
945                 case 14:
946                         sample_rate_hint = x;
947                         break;
948                 case 15:
949                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
950                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
951                         return true;
952                 default:
953                         FLAC__ASSERT(0);
954         }
955
956         x = (unsigned)(raw_header[3] >> 4);
957         if(x & 8) {
958                 decoder->guts->frame.header.channels = 2;
959                 switch(x & 7) {
960                         case 0:
961                                 decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
962                                 break;
963                         case 1:
964                                 decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
965                                 break;
966                         case 2:
967                                 decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
968                                 break;
969                         default:
970                                 is_unparseable = true;
971                                 break;
972                 }
973         }
974         else {
975                 decoder->guts->frame.header.channels = (unsigned)x + 1;
976                 decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
977         }
978
979         switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
980                 case 0:
981                         if(decoder->guts->has_stream_info)
982                                 decoder->guts->frame.header.bits_per_sample = decoder->guts->stream_info.data.stream_info.bits_per_sample;
983                         else
984                                 is_unparseable = true;
985                         break;
986                 case 1:
987                         decoder->guts->frame.header.bits_per_sample = 8;
988                         break;
989                 case 2:
990                         decoder->guts->frame.header.bits_per_sample = 12;
991                         break;
992                 case 4:
993                         decoder->guts->frame.header.bits_per_sample = 16;
994                         break;
995                 case 5:
996                         decoder->guts->frame.header.bits_per_sample = 20;
997                         break;
998                 case 6:
999                         decoder->guts->frame.header.bits_per_sample = 24;
1000                         break;
1001                 case 3:
1002                 case 7:
1003                         is_unparseable = true;
1004                         break;
1005                 default:
1006                         FLAC__ASSERT(0);
1007                         break;
1008         }
1009
1010         if(raw_header[3] & 0x01) { /* this should be a zero padding bit */
1011                 decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
1012                 decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1013                 return true;
1014         }
1015
1016         if(blocksize_hint && is_known_variable_blocksize_stream) {
1017                 if(!FLAC__bitbuffer_read_utf8_uint64(&decoder->guts->input, &xx, read_callback_, decoder, raw_header, &raw_header_len))
1018                         return false; /* the read_callback_ sets the state for us */
1019                 if(xx == 0xffffffffffffffff) { /* i.e. non-UTF8 code... */
1020                         decoder->guts->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
1021                         decoder->guts->cached = true;
1022                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
1023                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1024                         return true;
1025                 }
1026                 decoder->guts->frame.header.number.sample_number = xx;
1027         }
1028         else {
1029                 if(!FLAC__bitbuffer_read_utf8_uint32(&decoder->guts->input, &x, read_callback_, decoder, raw_header, &raw_header_len))
1030                         return false; /* the read_callback_ sets the state for us */
1031                 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
1032                         decoder->guts->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
1033                         decoder->guts->cached = true;
1034                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
1035                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1036                         return true;
1037                 }
1038                 decoder->guts->last_frame_number = x;
1039                 if(decoder->guts->has_stream_info) {
1040                         decoder->guts->frame.header.number.sample_number = (int64)decoder->guts->stream_info.data.stream_info.min_blocksize * (int64)x;
1041                 }
1042                 else {
1043                         is_unparseable = true;
1044                 }
1045         }
1046
1047         if(blocksize_hint) {
1048                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
1049                         return false; /* the read_callback_ sets the state for us */
1050                 raw_header[raw_header_len++] = (byte)x;
1051                 if(blocksize_hint == 7) {
1052                         uint32 _x;
1053                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &_x, 8, read_callback_, decoder))
1054                                 return false; /* the read_callback_ sets the state for us */
1055                         raw_header[raw_header_len++] = (byte)_x;
1056                         x = (x << 8) | _x;
1057                 }
1058                 decoder->guts->frame.header.blocksize = x+1;
1059         }
1060
1061         if(sample_rate_hint) {
1062                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
1063                         return false; /* the read_callback_ sets the state for us */
1064                 raw_header[raw_header_len++] = (byte)x;
1065                 if(sample_rate_hint != 12) {
1066                         uint32 _x;
1067                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &_x, 8, read_callback_, decoder))
1068                                 return false; /* the read_callback_ sets the state for us */
1069                         raw_header[raw_header_len++] = (byte)_x;
1070                         x = (x << 8) | _x;
1071                 }
1072                 if(sample_rate_hint == 12)
1073                         decoder->guts->frame.header.sample_rate = x*1000;
1074                 else if(sample_rate_hint == 13)
1075                         decoder->guts->frame.header.sample_rate = x;
1076                 else
1077                         decoder->guts->frame.header.sample_rate = x*10;
1078         }
1079
1080         /* read the CRC-8 byte */
1081         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
1082                 return false; /* the read_callback_ sets the state for us */
1083         crc8 = (byte)x;
1084
1085         if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
1086                 decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
1087                 decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1088                 return true;
1089         }
1090
1091         if(is_unparseable) {
1092                 decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1093                 return false;
1094         }
1095
1096         return true;
1097 }
1098
1099 bool stream_decoder_read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps)
1100 {
1101         uint32 x;
1102         bool wasted_bits;
1103
1104         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder)) /* MAGIC NUMBER */
1105                 return false; /* the read_callback_ sets the state for us */
1106
1107         wasted_bits = (x & 1);
1108         x &= 0xfe;
1109
1110         if(wasted_bits) {
1111                 unsigned u;
1112                 if(!FLAC__bitbuffer_read_unary_unsigned(&decoder->guts->input, &u, read_callback_, decoder))
1113                         return false; /* the read_callback_ sets the state for us */
1114                 decoder->guts->frame.subframes[channel].wasted_bits = u+1;
1115                 bps -= decoder->guts->frame.subframes[channel].wasted_bits;
1116         }
1117         else
1118                 decoder->guts->frame.subframes[channel].wasted_bits = 0;
1119
1120         /*
1121          * Lots of magic numbers here
1122          */
1123         if(x & 0x80) {
1124                 decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_LOST_SYNC, decoder->guts->client_data);
1125                 decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1126                 return true;
1127         }
1128         else if(x == 0) {
1129                 if(!stream_decoder_read_subframe_constant_(decoder, channel, bps))
1130                         return false;
1131         }
1132         else if(x == 2) {
1133                 if(!stream_decoder_read_subframe_verbatim_(decoder, channel, bps))
1134                         return false;
1135         }
1136         else if(x < 16) {
1137                 decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1138                 return false;
1139         }
1140         else if(x <= 24) {
1141                 if(!stream_decoder_read_subframe_fixed_(decoder, channel, bps, (x>>1)&7))
1142                         return false;
1143         }
1144         else if(x < 64) {
1145                 decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1146                 return false;
1147         }
1148         else {
1149                 if(!stream_decoder_read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1))
1150                         return false;
1151         }
1152
1153         if(wasted_bits) {
1154                 unsigned i;
1155                 x = decoder->guts->frame.subframes[channel].wasted_bits;
1156                 for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
1157                         decoder->guts->output[channel][i] <<= x;
1158         }
1159
1160         return true;
1161 }
1162
1163 bool stream_decoder_read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps)
1164 {
1165         FLAC__Subframe_Constant *subframe = &decoder->guts->frame.subframes[channel].data.constant;
1166         int32 x;
1167         unsigned i;
1168         int32 *output = decoder->guts->output[channel];
1169
1170         decoder->guts->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
1171
1172         if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &x, bps, read_callback_, decoder))
1173                 return false; /* the read_callback_ sets the state for us */
1174
1175         subframe->value = x;
1176
1177         /* decode the subframe */
1178         for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
1179                 output[i] = x;
1180
1181         return true;
1182 }
1183
1184 bool stream_decoder_read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order)
1185 {
1186         FLAC__Subframe_Fixed *subframe = &decoder->guts->frame.subframes[channel].data.fixed;
1187         int32 i32;
1188         uint32 u32;
1189         unsigned u;
1190
1191         decoder->guts->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
1192
1193         subframe->residual = decoder->guts->residual[channel];
1194         subframe->order = order;
1195
1196         /* read warm-up samples */
1197         for(u = 0; u < order; u++) {
1198                 if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &i32, bps, read_callback_, decoder))
1199                         return false; /* the read_callback_ sets the state for us */
1200                 subframe->warmup[u] = i32;
1201         }
1202
1203         /* read entropy coding method info */
1204         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
1205                 return false; /* the read_callback_ sets the state for us */
1206         subframe->entropy_coding_method.type = u32;
1207         switch(subframe->entropy_coding_method.type) {
1208                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1209                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
1210                                 return false; /* the read_callback_ sets the state for us */
1211                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
1212                         break;
1213                 default:
1214                         decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1215                         return false;
1216         }
1217
1218         /* read residual */
1219         switch(subframe->entropy_coding_method.type) {
1220                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1221                         if(!stream_decoder_read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, decoder->guts->residual[channel]))
1222                                 return false;
1223                         break;
1224                 default:
1225                         FLAC__ASSERT(0);
1226         }
1227
1228         /* decode the subframe */
1229         memcpy(decoder->guts->output[channel], subframe->warmup, sizeof(int32) * order);
1230         FLAC__fixed_restore_signal(decoder->guts->residual[channel], decoder->guts->frame.header.blocksize-order, order, decoder->guts->output[channel]+order);
1231
1232         return true;
1233 }
1234
1235 bool stream_decoder_read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order)
1236 {
1237         FLAC__Subframe_LPC *subframe = &decoder->guts->frame.subframes[channel].data.lpc;
1238         int32 i32;
1239         uint32 u32;
1240         unsigned u;
1241
1242         decoder->guts->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
1243
1244         subframe->residual = decoder->guts->residual[channel];
1245         subframe->order = order;
1246
1247         /* read warm-up samples */
1248         for(u = 0; u < order; u++) {
1249                 if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &i32, bps, read_callback_, decoder))
1250                         return false; /* the read_callback_ sets the state for us */
1251                 subframe->warmup[u] = i32;
1252         }
1253
1254         /* read qlp coeff precision */
1255         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN, read_callback_, decoder))
1256                 return false; /* the read_callback_ sets the state for us */
1257         if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
1258                 decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_LOST_SYNC, decoder->guts->client_data);
1259                 decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1260                 return true;
1261         }
1262         subframe->qlp_coeff_precision = u32+1;
1263
1264         /* read qlp shift */
1265         if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN, read_callback_, decoder))
1266                 return false; /* the read_callback_ sets the state for us */
1267         subframe->quantization_level = i32;
1268
1269         /* read quantized lp coefficiencts */
1270         for(u = 0; u < order; u++) {
1271                 if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &i32, subframe->qlp_coeff_precision, read_callback_, decoder))
1272                         return false; /* the read_callback_ sets the state for us */
1273                 subframe->qlp_coeff[u] = i32;
1274         }
1275
1276         /* read entropy coding method info */
1277         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
1278                 return false; /* the read_callback_ sets the state for us */
1279         subframe->entropy_coding_method.type = u32;
1280         switch(subframe->entropy_coding_method.type) {
1281                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1282                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
1283                                 return false; /* the read_callback_ sets the state for us */
1284                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
1285                         break;
1286                 default:
1287                         decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1288                         return false;
1289         }
1290
1291         /* read residual */
1292         switch(subframe->entropy_coding_method.type) {
1293                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1294                         if(!stream_decoder_read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, decoder->guts->residual[channel]))
1295                                 return false;
1296                         break;
1297                 default:
1298                         FLAC__ASSERT(0);
1299         }
1300
1301         /* decode the subframe */
1302         memcpy(decoder->guts->output[channel], subframe->warmup, sizeof(int32) * order);
1303         if(bps <= 16 && subframe->qlp_coeff_precision <= 16)
1304                 decoder->guts->local_lpc_restore_signal_16bit(decoder->guts->residual[channel], decoder->guts->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->guts->output[channel]+order);
1305         else
1306                 decoder->guts->local_lpc_restore_signal(decoder->guts->residual[channel], decoder->guts->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->guts->output[channel]+order);
1307
1308         return true;
1309 }
1310
1311 bool stream_decoder_read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps)
1312 {
1313         FLAC__Subframe_Verbatim *subframe = &decoder->guts->frame.subframes[channel].data.verbatim;
1314         int32 x, *residual = decoder->guts->residual[channel];
1315         unsigned i;
1316
1317         decoder->guts->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
1318
1319         subframe->data = residual;
1320
1321         for(i = 0; i < decoder->guts->frame.header.blocksize; i++) {
1322                 if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &x, bps, read_callback_, decoder))
1323                         return false; /* the read_callback_ sets the state for us */
1324                 residual[i] = x;
1325         }
1326
1327         /* decode the subframe */
1328         memcpy(decoder->guts->output[channel], subframe->data, sizeof(int32) * decoder->guts->frame.header.blocksize);
1329
1330         return true;
1331 }
1332
1333 bool stream_decoder_read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, int32 *residual)
1334 {
1335         uint32 rice_parameter;
1336         int i;
1337         unsigned partition, sample, u;
1338         const unsigned partitions = 1u << partition_order;
1339         const unsigned partition_samples = partition_order > 0? decoder->guts->frame.header.blocksize >> partition_order : decoder->guts->frame.header.blocksize - predictor_order;
1340
1341         sample = 0;
1342         for(partition = 0; partition < partitions; partition++) {
1343                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN, read_callback_, decoder))
1344                         return false; /* the read_callback_ sets the state for us */
1345                 if(rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
1346                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
1347 #ifdef FLAC__SYMMETRIC_RICE
1348                                 if(!FLAC__bitbuffer_read_symmetric_rice_signed(&decoder->guts->input, &i, rice_parameter, read_callback_, decoder))
1349                                         return false; /* the read_callback_ sets the state for us */
1350 #else
1351                                 if(!FLAC__bitbuffer_read_rice_signed(&decoder->guts->input, &i, rice_parameter, read_callback_, decoder))
1352                                         return false; /* the read_callback_ sets the state for us */
1353 #endif
1354                                 residual[sample] = i;
1355                         }
1356                 }
1357                 else {
1358                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN, read_callback_, decoder))
1359                                 return false; /* the read_callback_ sets the state for us */
1360                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
1361                                 if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &i, rice_parameter, read_callback_, decoder))
1362                                         return false; /* the read_callback_ sets the state for us */
1363                                 residual[sample] = i;
1364                         }
1365                 }
1366         }
1367
1368         return true;
1369 }
1370
1371 bool stream_decoder_read_zero_padding_(FLAC__StreamDecoder *decoder)
1372 {
1373         if(decoder->guts->input.consumed_bits != 0) {
1374                 uint32 zero = 0;
1375                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &zero, 8-decoder->guts->input.consumed_bits, read_callback_, decoder))
1376                         return false; /* the read_callback_ sets the state for us */
1377                 if(zero != 0) {
1378                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_LOST_SYNC, decoder->guts->client_data);
1379                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1380                 }
1381         }
1382         return true;
1383 }
1384
1385 bool read_callback_(byte buffer[], unsigned *bytes, void *client_data)
1386 {
1387         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
1388         FLAC__StreamDecoderReadStatus status;
1389         status = decoder->guts->read_callback(decoder, buffer, bytes, decoder->guts->client_data);
1390         if(status == FLAC__STREAM_DECODER_READ_END_OF_STREAM)
1391                 decoder->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1392         else if(status == FLAC__STREAM_DECODER_READ_ABORT)
1393                 decoder->state = FLAC__STREAM_DECODER_ABORTED;
1394         return status == FLAC__STREAM_DECODER_READ_CONTINUE;
1395 }