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