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