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