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