add support for new "wasted bits" field
[platform/upstream/flac.git] / src / libFLAC / stream_decoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001  Josh Coalson
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA  02111-1307, USA.
18  */
19
20 #include <assert.h>
21 #include <stdio.h>
22 #include <stdlib.h> /* for malloc() */
23 #include "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                                 if(channel == 1)
653                                         bps++;
654                                 break;
655                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
656                                 if(channel == 0)
657                                         bps++;
658                                 break;
659                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
660                                 if(channel == 1)
661                                         bps++;
662                                 break;
663                         default:
664                                 assert(0);
665                 }
666                 /*
667                  * now read it
668                  */
669                 if(!stream_decoder_read_subframe_(decoder, channel, bps))
670                         return false;
671                 if(decoder->state != FLAC__STREAM_DECODER_READ_FRAME) {
672                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
673                         return true;
674                 }
675         }
676         if(!stream_decoder_read_zero_padding_(decoder))
677                 return false;
678
679         /*
680          * Read the frame CRC-16 from the footer and check
681          */
682         frame_crc = decoder->guts->input.read_crc16;
683         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__FRAME_FOOTER_CRC_LEN, read_callback_, decoder))
684                 return false; /* the read_callback_ sets the state for us */
685         if(frame_crc == (uint16)x) {
686                 /* Undo any special channel coding */
687                 switch(decoder->guts->frame.header.channel_assignment) {
688                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
689                                 /* do nothing */
690                                 break;
691                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
692                                 assert(decoder->guts->frame.header.channels == 2);
693                                 for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
694                                         decoder->guts->output[1][i] = decoder->guts->output[0][i] - decoder->guts->output[1][i];
695                                 break;
696                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
697                                 assert(decoder->guts->frame.header.channels == 2);
698                                 for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
699                                         decoder->guts->output[0][i] += decoder->guts->output[1][i];
700                                 break;
701                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
702                                 assert(decoder->guts->frame.header.channels == 2);
703                                 for(i = 0; i < decoder->guts->frame.header.blocksize; i++) {
704                                         mid = decoder->guts->output[0][i];
705                                         side = decoder->guts->output[1][i];
706                                         mid <<= 1;
707                                         if(side & 1) /* i.e. if 'side' is odd... */
708                                                 mid++;
709                                         left = mid + side;
710                                         right = mid - side;
711                                         decoder->guts->output[0][i] = left >> 1;
712                                         decoder->guts->output[1][i] = right >> 1;
713                                 }
714                                 break;
715                         default:
716                                 assert(0);
717                                 break;
718                 }
719         }
720         else {
721                 /* Bad frame, emit error and zero the output signal */
722                 decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_FRAME_CRC_MISMATCH, decoder->guts->client_data);
723                 for(channel = 0; channel < decoder->guts->frame.header.channels; channel++) {
724                         memset(decoder->guts->output[channel], 0, sizeof(int32) * decoder->guts->frame.header.blocksize);
725                 }
726         }
727
728         *got_a_frame = true;
729
730         /* put the latest values into the public section of the decoder instance */
731         decoder->channels = decoder->guts->frame.header.channels;
732         decoder->channel_assignment = decoder->guts->frame.header.channel_assignment;
733         decoder->bits_per_sample = decoder->guts->frame.header.bits_per_sample;
734         decoder->sample_rate = decoder->guts->frame.header.sample_rate;
735         decoder->blocksize = decoder->guts->frame.header.blocksize;
736
737         decoder->guts->samples_decoded += decoder->guts->frame.header.blocksize;
738
739         /* write it */
740         if(decoder->guts->write_callback(decoder, &decoder->guts->frame, decoder->guts->output, decoder->guts->client_data) != FLAC__STREAM_DECODER_WRITE_CONTINUE)
741                 return false;
742
743         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
744         return true;
745 }
746
747 bool stream_decoder_read_frame_header_(FLAC__StreamDecoder *decoder)
748 {
749         uint32 x;
750         uint64 xx;
751         unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
752         byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
753         unsigned raw_header_len;
754         bool is_unparseable = false;
755
756         assert(decoder->guts->input.consumed_bits == 0); /* make sure we're byte aligned */
757
758         /* init the raw header with the saved bits from synchronization */
759         raw_header[0] = decoder->guts->header_warmup[0];
760         raw_header[1] = decoder->guts->header_warmup[1];
761         raw_header_len = 2;
762
763         /*
764          * check to make sure that the reserved bits are 0
765          */
766         if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
767                 is_unparseable = true;
768         }
769
770         /*
771          * Note that along the way as we read the header, we look for a sync
772          * code inside.  If we find one it would indicate that our original
773          * sync was bad since there cannot be a sync code in a valid header.
774          */
775
776         /*
777          * read in the raw header as bytes so we can CRC it, and parse it on the way
778          */
779         for(i = 0; i < 2; i++) {
780                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
781                         return false; /* the read_callback_ sets the state for us */
782                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
783                         /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
784                         decoder->guts->lookahead = (byte)x;
785                         decoder->guts->cached = true;
786                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
787                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
788                         return true;
789                 }
790                 raw_header[raw_header_len++] = (byte)x;
791         }
792
793         switch(x = raw_header[2] >> 4) {
794                 case 0:
795                         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 */
796                                 decoder->guts->frame.header.blocksize = decoder->guts->stream_header.data.stream_info.min_blocksize;
797                         else
798                                 is_unparseable = true;
799                         break;
800                 case 1:
801                         decoder->guts->frame.header.blocksize = 192;
802                         break;
803                 case 2:
804                 case 3:
805                 case 4:
806                 case 5:
807                         decoder->guts->frame.header.blocksize = 576 << (x-2);
808                         break;
809                 case 6:
810                 case 7:
811                         blocksize_hint = x;
812                         break;
813                 case 8:
814                 case 9:
815                 case 10:
816                 case 11:
817                 case 12:
818                 case 13:
819                 case 14:
820                 case 15:
821                         decoder->guts->frame.header.blocksize = 256 << (x-8);
822                         break;
823                 default:
824                         assert(0);
825                         break;
826         }
827
828         switch(x = raw_header[2] & 0x0f) {
829                 case 0:
830                         if(decoder->guts->has_stream_header)
831                                 decoder->guts->frame.header.sample_rate = decoder->guts->stream_header.data.stream_info.sample_rate;
832                         else
833                                 is_unparseable = true;
834                         break;
835                 case 1:
836                 case 2:
837                 case 3:
838                         is_unparseable = true;
839                         break;
840                 case 4:
841                         decoder->guts->frame.header.sample_rate = 8000;
842                         break;
843                 case 5:
844                         decoder->guts->frame.header.sample_rate = 16000;
845                         break;
846                 case 6:
847                         decoder->guts->frame.header.sample_rate = 22050;
848                         break;
849                 case 7:
850                         decoder->guts->frame.header.sample_rate = 24000;
851                         break;
852                 case 8:
853                         decoder->guts->frame.header.sample_rate = 32000;
854                         break;
855                 case 9:
856                         decoder->guts->frame.header.sample_rate = 44100;
857                         break;
858                 case 10:
859                         decoder->guts->frame.header.sample_rate = 48000;
860                         break;
861                 case 11:
862                         decoder->guts->frame.header.sample_rate = 96000;
863                         break;
864                 case 12:
865                 case 13:
866                 case 14:
867                         sample_rate_hint = x;
868                         break;
869                 case 15:
870                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
871                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
872                         return true;
873                 default:
874                         assert(0);
875         }
876
877         x = (unsigned)(raw_header[3] >> 4);
878         if(x & 8) {
879                 decoder->guts->frame.header.channels = 2;
880                 switch(x & 7) {
881                         case 0:
882                                 decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
883                                 break;
884                         case 1:
885                                 decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
886                                 break;
887                         case 2:
888                                 decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
889                                 break;
890                         default:
891                                 is_unparseable = true;
892                                 break;
893                 }
894         }
895         else {
896                 decoder->guts->frame.header.channels = (unsigned)x + 1;
897                 decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
898         }
899
900         switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
901                 case 0:
902                         if(decoder->guts->has_stream_header)
903                                 decoder->guts->frame.header.bits_per_sample = decoder->guts->stream_header.data.stream_info.bits_per_sample;
904                         else
905                                 is_unparseable = true;
906                         break;
907                 case 1:
908                         decoder->guts->frame.header.bits_per_sample = 8;
909                         break;
910                 case 2:
911                         decoder->guts->frame.header.bits_per_sample = 12;
912                         break;
913                 case 4:
914                         decoder->guts->frame.header.bits_per_sample = 16;
915                         break;
916                 case 5:
917                         decoder->guts->frame.header.bits_per_sample = 20;
918                         break;
919                 case 6:
920                         decoder->guts->frame.header.bits_per_sample = 24;
921                         break;
922                 case 3:
923                 case 7:
924                         is_unparseable = true;
925                         break;
926                 default:
927                         assert(0);
928                         break;
929         }
930
931         if(raw_header[3] & 0x01) { /* this should be a zero padding bit */
932                 decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
933                 decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
934                 return true;
935         }
936
937         if(blocksize_hint) {
938                 if(!FLAC__bitbuffer_read_utf8_uint64(&decoder->guts->input, &xx, read_callback_, decoder, raw_header, &raw_header_len))
939                         return false; /* the read_callback_ sets the state for us */
940                 if(xx == 0xffffffffffffffff) { /* i.e. non-UTF8 code... */
941                         decoder->guts->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
942                         decoder->guts->cached = true;
943                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
944                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
945                         return true;
946                 }
947                 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 */
948                         decoder->guts->frame.header.number.sample_number = (uint64)decoder->guts->last_frame_number * (int64)decoder->guts->stream_header.data.stream_info.min_blocksize + xx;
949                 else
950                         decoder->guts->frame.header.number.sample_number = xx;
951         }
952         else {
953                 if(!FLAC__bitbuffer_read_utf8_uint32(&decoder->guts->input, &x, read_callback_, decoder, raw_header, &raw_header_len))
954                         return false; /* the read_callback_ sets the state for us */
955                 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
956                         decoder->guts->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
957                         decoder->guts->cached = true;
958                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
959                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
960                         return true;
961                 }
962                 decoder->guts->last_frame_number = x;
963                 if(decoder->guts->has_stream_header) {
964                         decoder->guts->frame.header.number.sample_number = (int64)decoder->guts->stream_header.data.stream_info.min_blocksize * (int64)x;
965                 }
966                 else {
967                         is_unparseable = true;
968                 }
969         }
970
971         if(blocksize_hint) {
972                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
973                         return false; /* the read_callback_ sets the state for us */
974                 raw_header[raw_header_len++] = (byte)x;
975                 if(blocksize_hint == 7) {
976                         uint32 _x;
977                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &_x, 8, read_callback_, decoder))
978                                 return false; /* the read_callback_ sets the state for us */
979                         raw_header[raw_header_len++] = (byte)_x;
980                         x = (x << 8) | _x;
981                 }
982                 decoder->guts->frame.header.blocksize = x+1;
983         }
984
985         if(sample_rate_hint) {
986                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
987                         return false; /* the read_callback_ sets the state for us */
988                 raw_header[raw_header_len++] = (byte)x;
989                 if(sample_rate_hint != 12) {
990                         uint32 _x;
991                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &_x, 8, read_callback_, decoder))
992                                 return false; /* the read_callback_ sets the state for us */
993                         raw_header[raw_header_len++] = (byte)_x;
994                         x = (x << 8) | _x;
995                 }
996                 if(sample_rate_hint == 12)
997                         decoder->guts->frame.header.sample_rate = x*1000;
998                 else if(sample_rate_hint == 13)
999                         decoder->guts->frame.header.sample_rate = x;
1000                 else
1001                         decoder->guts->frame.header.sample_rate = x*10;
1002         }
1003
1004         /* read the CRC-8 byte */
1005         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
1006                 return false; /* the read_callback_ sets the state for us */
1007         crc8 = (byte)x;
1008
1009         if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
1010                 decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
1011                 decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1012                 return true;
1013         }
1014
1015         if(is_unparseable) {
1016                 decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1017                 return false;
1018         }
1019
1020         return true;
1021 }
1022
1023 bool stream_decoder_read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps)
1024 {
1025         uint32 x;
1026         bool wasted_bits;
1027
1028         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder)) /* MAGIC NUMBER */
1029                 return false; /* the read_callback_ sets the state for us */
1030
1031         wasted_bits = (x & 1);
1032         x &= 0xfe;
1033
1034         if(wasted_bits) {
1035                 unsigned u;
1036                 if(!FLAC__bitbuffer_read_unary_unsigned(&decoder->guts->input, &u, read_callback_, decoder))
1037                         return false; /* the read_callback_ sets the state for us */
1038                 decoder->guts->frame.subframes[channel].wasted_bits = u+1;
1039         }
1040         else
1041                 decoder->guts->frame.subframes[channel].wasted_bits = 0;
1042
1043         /*
1044          * Lots of magic numbers here
1045          */
1046         if(x & 0x80) {
1047                 decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_LOST_SYNC, decoder->guts->client_data);
1048                 decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1049                 return true;
1050         }
1051         else if(x == 0) {
1052                 if(!stream_decoder_read_subframe_constant_(decoder, channel, bps))
1053                         return false;
1054         }
1055         else if(x == 2) {
1056                 if(!stream_decoder_read_subframe_verbatim_(decoder, channel, bps))
1057                         return false;
1058         }
1059         else if(x < 16) {
1060                 decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1061                 return false;
1062         }
1063         else if(x <= 24) {
1064                 if(!stream_decoder_read_subframe_fixed_(decoder, channel, bps, (x>>1)&7))
1065                         return false;
1066         }
1067         else if(x < 64) {
1068                 decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1069                 return false;
1070         }
1071         else {
1072                 if(!stream_decoder_read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1))
1073                         return false;
1074         }
1075
1076         if(wasted_bits) {
1077                 unsigned i;
1078                 x = decoder->guts->frame.subframes[channel].wasted_bits;
1079                 for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
1080                         decoder->guts->output[channel][i] <<= x;
1081         }
1082
1083         return true;
1084 }
1085
1086 bool stream_decoder_read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps)
1087 {
1088         FLAC__Subframe_Constant *subframe = &decoder->guts->frame.subframes[channel].data.constant;
1089         int32 x;
1090         unsigned i;
1091         int32 *output = decoder->guts->output[channel];
1092
1093         decoder->guts->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
1094
1095         if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &x, bps, read_callback_, decoder))
1096                 return false; /* the read_callback_ sets the state for us */
1097
1098         subframe->value = x;
1099
1100         /* decode the subframe */
1101         for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
1102                 output[i] = x;
1103
1104         return true;
1105 }
1106
1107 bool stream_decoder_read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order)
1108 {
1109         FLAC__Subframe_Fixed *subframe = &decoder->guts->frame.subframes[channel].data.fixed;
1110         int32 i32;
1111         uint32 u32;
1112         unsigned u;
1113
1114         decoder->guts->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
1115
1116         subframe->residual = decoder->guts->residual[channel];
1117         subframe->order = order;
1118
1119         /* read warm-up samples */
1120         for(u = 0; u < order; u++) {
1121                 if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &i32, bps - decoder->guts->frame.subframes[channel].wasted_bits, read_callback_, decoder))
1122                         return false; /* the read_callback_ sets the state for us */
1123                 subframe->warmup[u] = i32;
1124         }
1125
1126         /* read entropy coding method info */
1127         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
1128                 return false; /* the read_callback_ sets the state for us */
1129         subframe->entropy_coding_method.type = u32;
1130         switch(subframe->entropy_coding_method.type) {
1131                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1132                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
1133                                 return false; /* the read_callback_ sets the state for us */
1134                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
1135                         break;
1136                 default:
1137                         decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1138                         return false;
1139         }
1140
1141         /* read residual */
1142         switch(subframe->entropy_coding_method.type) {
1143                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1144                         if(!stream_decoder_read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, decoder->guts->residual[channel]))
1145                                 return false;
1146                         break;
1147                 default:
1148                         assert(0);
1149         }
1150
1151         /* decode the subframe */
1152         memcpy(decoder->guts->output[channel], subframe->warmup, sizeof(int32) * order);
1153         FLAC__fixed_restore_signal(decoder->guts->residual[channel], decoder->guts->frame.header.blocksize-order, order, decoder->guts->output[channel]+order);
1154
1155         return true;
1156 }
1157
1158 bool stream_decoder_read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order)
1159 {
1160         FLAC__Subframe_LPC *subframe = &decoder->guts->frame.subframes[channel].data.lpc;
1161         int32 i32;
1162         uint32 u32;
1163         unsigned u;
1164
1165         decoder->guts->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
1166
1167         subframe->residual = decoder->guts->residual[channel];
1168         subframe->order = order;
1169
1170         /* read warm-up samples */
1171         for(u = 0; u < order; u++) {
1172                 if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &i32, bps - decoder->guts->frame.subframes[channel].wasted_bits, read_callback_, decoder))
1173                         return false; /* the read_callback_ sets the state for us */
1174                 subframe->warmup[u] = i32;
1175         }
1176
1177         /* read qlp coeff precision */
1178         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN, read_callback_, decoder))
1179                 return false; /* the read_callback_ sets the state for us */
1180         if(u32 == 15) {
1181                 decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_LOST_SYNC, decoder->guts->client_data);
1182                 decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1183                 return true;
1184         }
1185         subframe->qlp_coeff_precision = u32+1;
1186
1187         /* read qlp shift */
1188         if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN, read_callback_, decoder))
1189                 return false; /* the read_callback_ sets the state for us */
1190         subframe->quantization_level = i32;
1191
1192         /* read quantized lp coefficiencts */
1193         for(u = 0; u < order; u++) {
1194                 if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &i32, subframe->qlp_coeff_precision, read_callback_, decoder))
1195                         return false; /* the read_callback_ sets the state for us */
1196                 subframe->qlp_coeff[u] = i32;
1197         }
1198
1199         /* read entropy coding method info */
1200         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
1201                 return false; /* the read_callback_ sets the state for us */
1202         subframe->entropy_coding_method.type = u32;
1203         switch(subframe->entropy_coding_method.type) {
1204                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1205                         if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
1206                                 return false; /* the read_callback_ sets the state for us */
1207                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
1208                         break;
1209                 default:
1210                         decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
1211                         return false;
1212         }
1213
1214         /* read residual */
1215         switch(subframe->entropy_coding_method.type) {
1216                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
1217                         if(!stream_decoder_read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, decoder->guts->residual[channel]))
1218                                 return false;
1219                         break;
1220                 default:
1221                         assert(0);
1222         }
1223
1224         /* decode the subframe */
1225         memcpy(decoder->guts->output[channel], subframe->warmup, sizeof(int32) * order);
1226         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);
1227
1228         return true;
1229 }
1230
1231 bool stream_decoder_read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps)
1232 {
1233         FLAC__Subframe_Verbatim *subframe = &decoder->guts->frame.subframes[channel].data.verbatim;
1234         int32 x, *residual = decoder->guts->residual[channel];
1235         unsigned i;
1236
1237         decoder->guts->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
1238
1239         subframe->data = residual;
1240
1241         for(i = 0; i < decoder->guts->frame.header.blocksize; i++) {
1242                 if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &x, bps, read_callback_, decoder))
1243                         return false; /* the read_callback_ sets the state for us */
1244                 residual[i] = x;
1245         }
1246
1247         /* decode the subframe */
1248         memcpy(decoder->guts->output[channel], subframe->data, sizeof(int32) * decoder->guts->frame.header.blocksize);
1249
1250         return true;
1251 }
1252
1253 bool stream_decoder_read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, int32 *residual)
1254 {
1255         uint32 rice_parameter;
1256         int i;
1257         unsigned partition, sample, u;
1258         const unsigned partitions = 1u << partition_order;
1259         const unsigned partition_samples = partition_order > 0? decoder->guts->frame.header.blocksize >> partition_order : decoder->guts->frame.header.blocksize - predictor_order;
1260
1261         sample = 0;
1262         for(partition = 0; partition < partitions; partition++) {
1263                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN, read_callback_, decoder))
1264                         return false; /* the read_callback_ sets the state for us */
1265                 for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
1266 #ifdef SYMMETRIC_RICE
1267                         if(!FLAC__bitbuffer_read_symmetric_rice_signed(&decoder->guts->input, &i, rice_parameter, read_callback_, decoder))
1268                                 return false; /* the read_callback_ sets the state for us */
1269 #else
1270                         if(!FLAC__bitbuffer_read_rice_signed(&decoder->guts->input, &i, rice_parameter, read_callback_, decoder))
1271                                 return false; /* the read_callback_ sets the state for us */
1272 #endif
1273                         residual[sample] = i;
1274                 }
1275         }
1276
1277         return true;
1278 }
1279
1280 bool stream_decoder_read_zero_padding_(FLAC__StreamDecoder *decoder)
1281 {
1282         if(decoder->guts->input.consumed_bits != 0) {
1283                 uint32 zero = 0;
1284                 if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &zero, 8-decoder->guts->input.consumed_bits, read_callback_, decoder))
1285                         return false; /* the read_callback_ sets the state for us */
1286                 if(zero != 0) {
1287                         decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_LOST_SYNC, decoder->guts->client_data);
1288                         decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1289                 }
1290         }
1291         return true;
1292 }
1293
1294 bool read_callback_(byte buffer[], unsigned *bytes, void *client_data)
1295 {
1296         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
1297         FLAC__StreamDecoderReadStatus status;
1298         status = decoder->guts->read_callback(decoder, buffer, bytes, decoder->guts->client_data);
1299         if(status == FLAC__STREAM_DECODER_READ_END_OF_STREAM)
1300                 decoder->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1301         else if(status == FLAC__STREAM_DECODER_READ_ABORT)
1302                 decoder->state = FLAC__STREAM_DECODER_ABORTED;
1303         return status == FLAC__STREAM_DECODER_READ_CONTINUE;
1304 }