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