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