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