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