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