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