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