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