merge decoder part from RICE_EXT_BRANCH: blocking strategy bit, new rice2 ecm, frame...
[flac.git] / src / libFLAC / stream_decoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * - Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
11  * - Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * - Neither the name of the Xiph.org Foundation nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #if HAVE_CONFIG_H
33 #  include <config.h>
34 #endif
35
36 #if defined _MSC_VER || defined __MINGW32__
37 #include <io.h> /* for _setmode() */
38 #include <fcntl.h> /* for _O_BINARY */
39 #endif
40 #if defined __CYGWIN__ || defined __EMX__
41 #include <io.h> /* for setmode(), O_BINARY */
42 #include <fcntl.h> /* for _O_BINARY */
43 #endif
44 #include <stdio.h>
45 #include <stdlib.h> /* for malloc() */
46 #include <string.h> /* for memset/memcpy() */
47 #include <sys/stat.h> /* for stat() */
48 #include <sys/types.h> /* for off_t */
49 #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
50 #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
51 #define fseeko fseek
52 #define ftello ftell
53 #endif
54 #endif
55 #include "FLAC/assert.h"
56 #include "protected/stream_decoder.h"
57 #include "private/bitreader.h"
58 #include "private/bitmath.h"
59 #include "private/cpu.h"
60 #include "private/crc.h"
61 #include "private/fixed.h"
62 #include "private/format.h"
63 #include "private/lpc.h"
64 #include "private/md5.h"
65 #include "private/memory.h"
66
67 #ifdef max
68 #undef max
69 #endif
70 #define max(a,b) ((a)>(b)?(a):(b))
71
72 /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
73 #ifdef _MSC_VER
74 #define FLAC__U64L(x) x
75 #else
76 #define FLAC__U64L(x) x##LLU
77 #endif
78
79
80 /* technically this should be in an "export.c" but this is convenient enough */
81 FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
82 #if FLAC__HAS_OGG
83         1
84 #else
85         0
86 #endif
87 ;
88
89
90 /***********************************************************************
91  *
92  * Private static data
93  *
94  ***********************************************************************/
95
96 static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
97
98 /***********************************************************************
99  *
100  * Private class method prototypes
101  *
102  ***********************************************************************/
103
104 static void set_defaults_(FLAC__StreamDecoder *decoder);
105 static FILE *get_binary_stdin_(void);
106 static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
107 static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
108 static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
109 static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
110 static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
111 static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
112 static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
113 static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
114 static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
115 static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
116 static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
117 static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
118 static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
119 static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
120 static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
121 static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
122 static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
123 static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
124 static FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended);
125 static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
126 static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
127 #if FLAC__HAS_OGG
128 static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
129 static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
130 #endif
131 static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
132 static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
133 static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
134 #if FLAC__HAS_OGG
135 static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
136 #endif
137 static FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
138 static FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
139 static FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
140 static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
141 static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
142
143 /***********************************************************************
144  *
145  * Private class data
146  *
147  ***********************************************************************/
148
149 typedef struct FLAC__StreamDecoderPrivate {
150 #if FLAC__HAS_OGG
151         FLAC__bool is_ogg;
152 #endif
153         FLAC__StreamDecoderReadCallback read_callback;
154         FLAC__StreamDecoderSeekCallback seek_callback;
155         FLAC__StreamDecoderTellCallback tell_callback;
156         FLAC__StreamDecoderLengthCallback length_callback;
157         FLAC__StreamDecoderEofCallback eof_callback;
158         FLAC__StreamDecoderWriteCallback write_callback;
159         FLAC__StreamDecoderMetadataCallback metadata_callback;
160         FLAC__StreamDecoderErrorCallback error_callback;
161         /* generic 32-bit datapath: */
162         void (*local_lpc_restore_signal)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
163         /* generic 64-bit datapath: */
164         void (*local_lpc_restore_signal_64bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
165         /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
166         void (*local_lpc_restore_signal_16bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
167         /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit), AND order <= 8: */
168         void (*local_lpc_restore_signal_16bit_order8)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
169         FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
170         void *client_data;
171         FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
172         FLAC__BitReader *input;
173         FLAC__int32 *output[FLAC__MAX_CHANNELS];
174         FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
175         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
176         unsigned output_capacity, output_channels;
177         FLAC__uint32 fixed_block_size, next_fixed_block_size;
178         FLAC__uint64 samples_decoded;
179         FLAC__bool has_stream_info, has_seek_table;
180         FLAC__StreamMetadata stream_info;
181         FLAC__StreamMetadata seek_table;
182         FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
183         FLAC__byte *metadata_filter_ids;
184         unsigned metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
185         FLAC__Frame frame;
186         FLAC__bool cached; /* true if there is a byte in lookahead */
187         FLAC__CPUInfo cpuinfo;
188         FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
189         FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
190         /* unaligned (original) pointers to allocated data */
191         FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
192         FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */
193         FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
194         FLAC__bool is_seeking;
195         FLAC__MD5Context md5context;
196         FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
197         /* (the rest of these are only used for seeking) */
198         FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
199         FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
200         FLAC__uint64 target_sample;
201         unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
202 #if FLAC__HAS_OGG
203         FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
204 #endif
205 } FLAC__StreamDecoderPrivate;
206
207 /***********************************************************************
208  *
209  * Public static class data
210  *
211  ***********************************************************************/
212
213 FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
214         "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
215         "FLAC__STREAM_DECODER_READ_METADATA",
216         "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
217         "FLAC__STREAM_DECODER_READ_FRAME",
218         "FLAC__STREAM_DECODER_END_OF_STREAM",
219         "FLAC__STREAM_DECODER_OGG_ERROR",
220         "FLAC__STREAM_DECODER_SEEK_ERROR",
221         "FLAC__STREAM_DECODER_ABORTED",
222         "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
223         "FLAC__STREAM_DECODER_UNINITIALIZED"
224 };
225
226 FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
227         "FLAC__STREAM_DECODER_INIT_STATUS_OK",
228         "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
229         "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
230         "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
231         "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
232         "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
233 };
234
235 FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
236         "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
237         "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
238         "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
239 };
240
241 FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
242         "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
243         "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
244         "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
245 };
246
247 FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
248         "FLAC__STREAM_DECODER_TELL_STATUS_OK",
249         "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
250         "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
251 };
252
253 FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
254         "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
255         "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
256         "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
257 };
258
259 FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
260         "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
261         "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
262 };
263
264 FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
265         "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
266         "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
267         "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
268         "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
269 };
270
271 /***********************************************************************
272  *
273  * Class constructor/destructor
274  *
275  ***********************************************************************/
276 FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
277 {
278         FLAC__StreamDecoder *decoder;
279         unsigned i;
280
281         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
282
283         decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
284         if(decoder == 0) {
285                 return 0;
286         }
287
288         decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
289         if(decoder->protected_ == 0) {
290                 free(decoder);
291                 return 0;
292         }
293
294         decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
295         if(decoder->private_ == 0) {
296                 free(decoder->protected_);
297                 free(decoder);
298                 return 0;
299         }
300
301         decoder->private_->input = FLAC__bitreader_new();
302         if(decoder->private_->input == 0) {
303                 free(decoder->private_);
304                 free(decoder->protected_);
305                 free(decoder);
306                 return 0;
307         }
308
309         decoder->private_->metadata_filter_ids_capacity = 16;
310         if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
311                 FLAC__bitreader_delete(decoder->private_->input);
312                 free(decoder->private_);
313                 free(decoder->protected_);
314                 free(decoder);
315                 return 0;
316         }
317
318         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
319                 decoder->private_->output[i] = 0;
320                 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
321         }
322
323         decoder->private_->output_capacity = 0;
324         decoder->private_->output_channels = 0;
325         decoder->private_->has_seek_table = false;
326
327         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
328                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
329
330         decoder->private_->file = 0;
331
332         set_defaults_(decoder);
333
334         decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
335
336         return decoder;
337 }
338
339 FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
340 {
341         unsigned i;
342
343         FLAC__ASSERT(0 != decoder);
344         FLAC__ASSERT(0 != decoder->protected_);
345         FLAC__ASSERT(0 != decoder->private_);
346         FLAC__ASSERT(0 != decoder->private_->input);
347
348         (void)FLAC__stream_decoder_finish(decoder);
349
350         if(0 != decoder->private_->metadata_filter_ids)
351                 free(decoder->private_->metadata_filter_ids);
352
353         FLAC__bitreader_delete(decoder->private_->input);
354
355         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
356                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
357
358         free(decoder->private_);
359         free(decoder->protected_);
360         free(decoder);
361 }
362
363 /***********************************************************************
364  *
365  * Public class methods
366  *
367  ***********************************************************************/
368
369 static FLAC__StreamDecoderInitStatus init_stream_internal_(
370         FLAC__StreamDecoder *decoder,
371         FLAC__StreamDecoderReadCallback read_callback,
372         FLAC__StreamDecoderSeekCallback seek_callback,
373         FLAC__StreamDecoderTellCallback tell_callback,
374         FLAC__StreamDecoderLengthCallback length_callback,
375         FLAC__StreamDecoderEofCallback eof_callback,
376         FLAC__StreamDecoderWriteCallback write_callback,
377         FLAC__StreamDecoderMetadataCallback metadata_callback,
378         FLAC__StreamDecoderErrorCallback error_callback,
379         void *client_data,
380         FLAC__bool is_ogg
381 )
382 {
383         FLAC__ASSERT(0 != decoder);
384
385         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
386                 return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
387
388 #if !FLAC__HAS_OGG
389         if(is_ogg)
390                 return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
391 #endif
392
393         if(
394                 0 == read_callback ||
395                 0 == write_callback ||
396                 0 == error_callback ||
397                 (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
398         )
399                 return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
400
401 #if FLAC__HAS_OGG
402         decoder->private_->is_ogg = is_ogg;
403         if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
404                 return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
405 #endif
406
407         /*
408          * get the CPU info and set the function pointers
409          */
410         FLAC__cpu_info(&decoder->private_->cpuinfo);
411         /* first default to the non-asm routines */
412         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
413         decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
414         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
415         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
416         decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
417         /* now override with asm where appropriate */
418 #ifndef FLAC__NO_ASM
419         if(decoder->private_->cpuinfo.use_asm) {
420 #ifdef FLAC__CPU_IA32
421                 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
422 #ifdef FLAC__HAS_NASM
423                 if(decoder->private_->cpuinfo.data.ia32.bswap)
424                         decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
425                 if(decoder->private_->cpuinfo.data.ia32.mmx) {
426                         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
427                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
428                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
429                 }
430                 else {
431                         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
432                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
433                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
434                 }
435 #endif
436 #elif defined FLAC__CPU_PPC
437                 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
438                 if(decoder->private_->cpuinfo.data.ppc.altivec) {
439                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
440                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
441                 }
442 #endif
443         }
444 #endif
445
446         /* from here on, errors are fatal */
447
448         if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
449                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
450                 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
451         }
452
453         decoder->private_->read_callback = read_callback;
454         decoder->private_->seek_callback = seek_callback;
455         decoder->private_->tell_callback = tell_callback;
456         decoder->private_->length_callback = length_callback;
457         decoder->private_->eof_callback = eof_callback;
458         decoder->private_->write_callback = write_callback;
459         decoder->private_->metadata_callback = metadata_callback;
460         decoder->private_->error_callback = error_callback;
461         decoder->private_->client_data = client_data;
462         decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
463         decoder->private_->samples_decoded = 0;
464         decoder->private_->has_stream_info = false;
465         decoder->private_->cached = false;
466
467         decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
468         decoder->private_->is_seeking = false;
469
470         decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
471         if(!FLAC__stream_decoder_reset(decoder)) {
472                 /* above call sets the state for us */
473                 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
474         }
475
476         return FLAC__STREAM_DECODER_INIT_STATUS_OK;
477 }
478
479 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
480         FLAC__StreamDecoder *decoder,
481         FLAC__StreamDecoderReadCallback read_callback,
482         FLAC__StreamDecoderSeekCallback seek_callback,
483         FLAC__StreamDecoderTellCallback tell_callback,
484         FLAC__StreamDecoderLengthCallback length_callback,
485         FLAC__StreamDecoderEofCallback eof_callback,
486         FLAC__StreamDecoderWriteCallback write_callback,
487         FLAC__StreamDecoderMetadataCallback metadata_callback,
488         FLAC__StreamDecoderErrorCallback error_callback,
489         void *client_data
490 )
491 {
492         return init_stream_internal_(
493                 decoder,
494                 read_callback,
495                 seek_callback,
496                 tell_callback,
497                 length_callback,
498                 eof_callback,
499                 write_callback,
500                 metadata_callback,
501                 error_callback,
502                 client_data,
503                 /*is_ogg=*/false
504         );
505 }
506
507 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
508         FLAC__StreamDecoder *decoder,
509         FLAC__StreamDecoderReadCallback read_callback,
510         FLAC__StreamDecoderSeekCallback seek_callback,
511         FLAC__StreamDecoderTellCallback tell_callback,
512         FLAC__StreamDecoderLengthCallback length_callback,
513         FLAC__StreamDecoderEofCallback eof_callback,
514         FLAC__StreamDecoderWriteCallback write_callback,
515         FLAC__StreamDecoderMetadataCallback metadata_callback,
516         FLAC__StreamDecoderErrorCallback error_callback,
517         void *client_data
518 )
519 {
520         return init_stream_internal_(
521                 decoder,
522                 read_callback,
523                 seek_callback,
524                 tell_callback,
525                 length_callback,
526                 eof_callback,
527                 write_callback,
528                 metadata_callback,
529                 error_callback,
530                 client_data,
531                 /*is_ogg=*/true
532         );
533 }
534
535 static FLAC__StreamDecoderInitStatus init_FILE_internal_(
536         FLAC__StreamDecoder *decoder,
537         FILE *file,
538         FLAC__StreamDecoderWriteCallback write_callback,
539         FLAC__StreamDecoderMetadataCallback metadata_callback,
540         FLAC__StreamDecoderErrorCallback error_callback,
541         void *client_data,
542         FLAC__bool is_ogg
543 )
544 {
545         FLAC__ASSERT(0 != decoder);
546         FLAC__ASSERT(0 != file);
547
548         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
549                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
550
551         if(0 == write_callback || 0 == error_callback)
552                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
553
554         /*
555          * To make sure that our file does not go unclosed after an error, we
556          * must assign the FILE pointer before any further error can occur in
557          * this routine.
558          */
559         if(file == stdin)
560                 file = get_binary_stdin_(); /* just to be safe */
561
562         decoder->private_->file = file;
563
564         return init_stream_internal_(
565                 decoder,
566                 file_read_callback_,
567                 decoder->private_->file == stdin? 0: file_seek_callback_,
568                 decoder->private_->file == stdin? 0: file_tell_callback_,
569                 decoder->private_->file == stdin? 0: file_length_callback_,
570                 file_eof_callback_,
571                 write_callback,
572                 metadata_callback,
573                 error_callback,
574                 client_data,
575                 is_ogg
576         );
577 }
578
579 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
580         FLAC__StreamDecoder *decoder,
581         FILE *file,
582         FLAC__StreamDecoderWriteCallback write_callback,
583         FLAC__StreamDecoderMetadataCallback metadata_callback,
584         FLAC__StreamDecoderErrorCallback error_callback,
585         void *client_data
586 )
587 {
588         return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
589 }
590
591 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
592         FLAC__StreamDecoder *decoder,
593         FILE *file,
594         FLAC__StreamDecoderWriteCallback write_callback,
595         FLAC__StreamDecoderMetadataCallback metadata_callback,
596         FLAC__StreamDecoderErrorCallback error_callback,
597         void *client_data
598 )
599 {
600         return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
601 }
602
603 static FLAC__StreamDecoderInitStatus init_file_internal_(
604         FLAC__StreamDecoder *decoder,
605         const char *filename,
606         FLAC__StreamDecoderWriteCallback write_callback,
607         FLAC__StreamDecoderMetadataCallback metadata_callback,
608         FLAC__StreamDecoderErrorCallback error_callback,
609         void *client_data,
610         FLAC__bool is_ogg
611 )
612 {
613         FILE *file;
614
615         FLAC__ASSERT(0 != decoder);
616
617         /*
618          * To make sure that our file does not go unclosed after an error, we
619          * have to do the same entrance checks here that are later performed
620          * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
621          */
622         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
623                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
624
625         if(0 == write_callback || 0 == error_callback)
626                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
627
628         file = filename? fopen(filename, "rb") : stdin;
629
630         if(0 == file)
631                 return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
632
633         return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
634 }
635
636 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
637         FLAC__StreamDecoder *decoder,
638         const char *filename,
639         FLAC__StreamDecoderWriteCallback write_callback,
640         FLAC__StreamDecoderMetadataCallback metadata_callback,
641         FLAC__StreamDecoderErrorCallback error_callback,
642         void *client_data
643 )
644 {
645         return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
646 }
647
648 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
649         FLAC__StreamDecoder *decoder,
650         const char *filename,
651         FLAC__StreamDecoderWriteCallback write_callback,
652         FLAC__StreamDecoderMetadataCallback metadata_callback,
653         FLAC__StreamDecoderErrorCallback error_callback,
654         void *client_data
655 )
656 {
657         return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
658 }
659
660 FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
661 {
662         FLAC__bool md5_failed = false;
663         unsigned i;
664
665         FLAC__ASSERT(0 != decoder);
666         FLAC__ASSERT(0 != decoder->private_);
667         FLAC__ASSERT(0 != decoder->protected_);
668
669         if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
670                 return true;
671
672         /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
673          * always call FLAC__MD5Final()
674          */
675         FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
676
677         if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
678                 free(decoder->private_->seek_table.data.seek_table.points);
679                 decoder->private_->seek_table.data.seek_table.points = 0;
680                 decoder->private_->has_seek_table = false;
681         }
682         FLAC__bitreader_free(decoder->private_->input);
683         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
684                 /* WATCHOUT:
685                  * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
686                  * output arrays have a buffer of up to 3 zeroes in front
687                  * (at negative indices) for alignment purposes; we use 4
688                  * to keep the data well-aligned.
689                  */
690                 if(0 != decoder->private_->output[i]) {
691                         free(decoder->private_->output[i]-4);
692                         decoder->private_->output[i] = 0;
693                 }
694                 if(0 != decoder->private_->residual_unaligned[i]) {
695                         free(decoder->private_->residual_unaligned[i]);
696                         decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
697                 }
698         }
699         decoder->private_->output_capacity = 0;
700         decoder->private_->output_channels = 0;
701
702 #if FLAC__HAS_OGG
703         if(decoder->private_->is_ogg)
704                 FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
705 #endif
706
707         if(0 != decoder->private_->file) {
708                 if(decoder->private_->file != stdin)
709                         fclose(decoder->private_->file);
710                 decoder->private_->file = 0;
711         }
712
713         if(decoder->private_->do_md5_checking) {
714                 if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
715                         md5_failed = true;
716         }
717         decoder->private_->is_seeking = false;
718
719         set_defaults_(decoder);
720
721         decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
722
723         return !md5_failed;
724 }
725
726 FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
727 {
728         FLAC__ASSERT(0 != decoder);
729         FLAC__ASSERT(0 != decoder->private_);
730         FLAC__ASSERT(0 != decoder->protected_);
731         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
732                 return false;
733 #if FLAC__HAS_OGG
734         /* can't check decoder->private_->is_ogg since that's not set until init time */
735         FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
736         return true;
737 #else
738         (void)value;
739         return false;
740 #endif
741 }
742
743 FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
744 {
745         FLAC__ASSERT(0 != decoder);
746         FLAC__ASSERT(0 != decoder->protected_);
747         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
748                 return false;
749         decoder->protected_->md5_checking = value;
750         return true;
751 }
752
753 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
754 {
755         FLAC__ASSERT(0 != decoder);
756         FLAC__ASSERT(0 != decoder->private_);
757         FLAC__ASSERT(0 != decoder->protected_);
758         FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
759         /* double protection */
760         if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
761                 return false;
762         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
763                 return false;
764         decoder->private_->metadata_filter[type] = true;
765         if(type == FLAC__METADATA_TYPE_APPLICATION)
766                 decoder->private_->metadata_filter_ids_count = 0;
767         return true;
768 }
769
770 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
771 {
772         FLAC__ASSERT(0 != decoder);
773         FLAC__ASSERT(0 != decoder->private_);
774         FLAC__ASSERT(0 != decoder->protected_);
775         FLAC__ASSERT(0 != id);
776         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
777                 return false;
778
779         if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
780                 return true;
781
782         FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
783
784         if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
785                 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2))) {
786                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
787                         return false;
788                 }
789                 decoder->private_->metadata_filter_ids_capacity *= 2;
790         }
791
792         memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
793         decoder->private_->metadata_filter_ids_count++;
794
795         return true;
796 }
797
798 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
799 {
800         unsigned i;
801         FLAC__ASSERT(0 != decoder);
802         FLAC__ASSERT(0 != decoder->private_);
803         FLAC__ASSERT(0 != decoder->protected_);
804         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
805                 return false;
806         for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
807                 decoder->private_->metadata_filter[i] = true;
808         decoder->private_->metadata_filter_ids_count = 0;
809         return true;
810 }
811
812 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
813 {
814         FLAC__ASSERT(0 != decoder);
815         FLAC__ASSERT(0 != decoder->private_);
816         FLAC__ASSERT(0 != decoder->protected_);
817         FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
818         /* double protection */
819         if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
820                 return false;
821         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
822                 return false;
823         decoder->private_->metadata_filter[type] = false;
824         if(type == FLAC__METADATA_TYPE_APPLICATION)
825                 decoder->private_->metadata_filter_ids_count = 0;
826         return true;
827 }
828
829 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
830 {
831         FLAC__ASSERT(0 != decoder);
832         FLAC__ASSERT(0 != decoder->private_);
833         FLAC__ASSERT(0 != decoder->protected_);
834         FLAC__ASSERT(0 != id);
835         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
836                 return false;
837
838         if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
839                 return true;
840
841         FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
842
843         if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
844                 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2))) {
845                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
846                         return false;
847                 }
848                 decoder->private_->metadata_filter_ids_capacity *= 2;
849         }
850
851         memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
852         decoder->private_->metadata_filter_ids_count++;
853
854         return true;
855 }
856
857 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
858 {
859         FLAC__ASSERT(0 != decoder);
860         FLAC__ASSERT(0 != decoder->private_);
861         FLAC__ASSERT(0 != decoder->protected_);
862         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
863                 return false;
864         memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
865         decoder->private_->metadata_filter_ids_count = 0;
866         return true;
867 }
868
869 FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
870 {
871         FLAC__ASSERT(0 != decoder);
872         FLAC__ASSERT(0 != decoder->protected_);
873         return decoder->protected_->state;
874 }
875
876 FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
877 {
878         return FLAC__StreamDecoderStateString[decoder->protected_->state];
879 }
880
881 FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
882 {
883         FLAC__ASSERT(0 != decoder);
884         FLAC__ASSERT(0 != decoder->protected_);
885         return decoder->protected_->md5_checking;
886 }
887
888 FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
889 {
890         FLAC__ASSERT(0 != decoder);
891         FLAC__ASSERT(0 != decoder->protected_);
892         return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
893 }
894
895 FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
896 {
897         FLAC__ASSERT(0 != decoder);
898         FLAC__ASSERT(0 != decoder->protected_);
899         return decoder->protected_->channels;
900 }
901
902 FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
903 {
904         FLAC__ASSERT(0 != decoder);
905         FLAC__ASSERT(0 != decoder->protected_);
906         return decoder->protected_->channel_assignment;
907 }
908
909 FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
910 {
911         FLAC__ASSERT(0 != decoder);
912         FLAC__ASSERT(0 != decoder->protected_);
913         return decoder->protected_->bits_per_sample;
914 }
915
916 FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
917 {
918         FLAC__ASSERT(0 != decoder);
919         FLAC__ASSERT(0 != decoder->protected_);
920         return decoder->protected_->sample_rate;
921 }
922
923 FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
924 {
925         FLAC__ASSERT(0 != decoder);
926         FLAC__ASSERT(0 != decoder->protected_);
927         return decoder->protected_->blocksize;
928 }
929
930 FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
931 {
932         FLAC__ASSERT(0 != decoder);
933         FLAC__ASSERT(0 != decoder->private_);
934         FLAC__ASSERT(0 != position);
935
936 #if FLAC__HAS_OGG
937         if(decoder->private_->is_ogg)
938                 return false;
939 #endif
940         if(0 == decoder->private_->tell_callback)
941                 return false;
942         if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
943                 return false;
944         /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
945         if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
946                 return false;
947         FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
948         *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
949         return true;
950 }
951
952 FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
953 {
954         FLAC__ASSERT(0 != decoder);
955         FLAC__ASSERT(0 != decoder->private_);
956         FLAC__ASSERT(0 != decoder->protected_);
957
958         decoder->private_->samples_decoded = 0;
959         decoder->private_->do_md5_checking = false;
960
961 #if FLAC__HAS_OGG
962         if(decoder->private_->is_ogg)
963                 FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
964 #endif
965
966         if(!FLAC__bitreader_clear(decoder->private_->input)) {
967                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
968                 return false;
969         }
970         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
971
972         return true;
973 }
974
975 FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
976 {
977         FLAC__ASSERT(0 != decoder);
978         FLAC__ASSERT(0 != decoder->private_);
979         FLAC__ASSERT(0 != decoder->protected_);
980
981         if(!FLAC__stream_decoder_flush(decoder)) {
982                 /* above call sets the state for us */
983                 return false;
984         }
985
986 #if FLAC__HAS_OGG
987         /*@@@ could go in !internal_reset_hack block below */
988         if(decoder->private_->is_ogg)
989                 FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
990 #endif
991
992         /* Rewind if necessary.  If FLAC__stream_decoder_init() is calling us,
993          * (internal_reset_hack) don't try to rewind since we are already at
994          * the beginning of the stream and don't want to fail if the input is
995          * not seekable.
996          */
997         if(!decoder->private_->internal_reset_hack) {
998                 if(decoder->private_->file == stdin)
999                         return false; /* can't rewind stdin, reset fails */
1000                 if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
1001                         return false; /* seekable and seek fails, reset fails */
1002         }
1003         else
1004                 decoder->private_->internal_reset_hack = false;
1005
1006         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
1007
1008         decoder->private_->has_stream_info = false;
1009         if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
1010                 free(decoder->private_->seek_table.data.seek_table.points);
1011                 decoder->private_->seek_table.data.seek_table.points = 0;
1012                 decoder->private_->has_seek_table = false;
1013         }
1014         decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
1015         /*
1016          * This goes in reset() and not flush() because according to the spec, a
1017          * fixed-blocksize stream must stay that way through the whole stream.
1018          */
1019         decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
1020
1021         /* We initialize the FLAC__MD5Context even though we may never use it.  This
1022          * is because md5 checking may be turned on to start and then turned off if
1023          * a seek occurs.  So we init the context here and finalize it in
1024          * FLAC__stream_decoder_finish() to make sure things are always cleaned up
1025          * properly.
1026          */
1027         FLAC__MD5Init(&decoder->private_->md5context);
1028
1029         decoder->private_->first_frame_offset = 0;
1030         decoder->private_->unparseable_frame_count = 0;
1031
1032         return true;
1033 }
1034
1035 FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
1036 {
1037         FLAC__bool got_a_frame;
1038         FLAC__ASSERT(0 != decoder);
1039         FLAC__ASSERT(0 != decoder->protected_);
1040
1041         while(1) {
1042                 switch(decoder->protected_->state) {
1043                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1044                                 if(!find_metadata_(decoder))
1045                                         return false; /* above function sets the status for us */
1046                                 break;
1047                         case FLAC__STREAM_DECODER_READ_METADATA:
1048                                 if(!read_metadata_(decoder))
1049                                         return false; /* above function sets the status for us */
1050                                 else
1051                                         return true;
1052                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1053                                 if(!frame_sync_(decoder))
1054                                         return true; /* above function sets the status for us */
1055                                 break;
1056                         case FLAC__STREAM_DECODER_READ_FRAME:
1057                                 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
1058                                         return false; /* above function sets the status for us */
1059                                 if(got_a_frame)
1060                                         return true; /* above function sets the status for us */
1061                                 break;
1062                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1063                         case FLAC__STREAM_DECODER_ABORTED:
1064                                 return true;
1065                         default:
1066                                 FLAC__ASSERT(0);
1067                                 return false;
1068                 }
1069         }
1070 }
1071
1072 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
1073 {
1074         FLAC__ASSERT(0 != decoder);
1075         FLAC__ASSERT(0 != decoder->protected_);
1076
1077         while(1) {
1078                 switch(decoder->protected_->state) {
1079                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1080                                 if(!find_metadata_(decoder))
1081                                         return false; /* above function sets the status for us */
1082                                 break;
1083                         case FLAC__STREAM_DECODER_READ_METADATA:
1084                                 if(!read_metadata_(decoder))
1085                                         return false; /* above function sets the status for us */
1086                                 break;
1087                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1088                         case FLAC__STREAM_DECODER_READ_FRAME:
1089                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1090                         case FLAC__STREAM_DECODER_ABORTED:
1091                                 return true;
1092                         default:
1093                                 FLAC__ASSERT(0);
1094                                 return false;
1095                 }
1096         }
1097 }
1098
1099 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
1100 {
1101         FLAC__bool dummy;
1102         FLAC__ASSERT(0 != decoder);
1103         FLAC__ASSERT(0 != decoder->protected_);
1104
1105         while(1) {
1106                 switch(decoder->protected_->state) {
1107                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1108                                 if(!find_metadata_(decoder))
1109                                         return false; /* above function sets the status for us */
1110                                 break;
1111                         case FLAC__STREAM_DECODER_READ_METADATA:
1112                                 if(!read_metadata_(decoder))
1113                                         return false; /* above function sets the status for us */
1114                                 break;
1115                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1116                                 if(!frame_sync_(decoder))
1117                                         return true; /* above function sets the status for us */
1118                                 break;
1119                         case FLAC__STREAM_DECODER_READ_FRAME:
1120                                 if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
1121                                         return false; /* above function sets the status for us */
1122                                 break;
1123                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1124                         case FLAC__STREAM_DECODER_ABORTED:
1125                                 return true;
1126                         default:
1127                                 FLAC__ASSERT(0);
1128                                 return false;
1129                 }
1130         }
1131 }
1132
1133 FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
1134 {
1135         FLAC__bool got_a_frame;
1136         FLAC__ASSERT(0 != decoder);
1137         FLAC__ASSERT(0 != decoder->protected_);
1138
1139         while(1) {
1140                 switch(decoder->protected_->state) {
1141                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1142                         case FLAC__STREAM_DECODER_READ_METADATA:
1143                                 return false; /* above function sets the status for us */
1144                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1145                                 if(!frame_sync_(decoder))
1146                                         return true; /* above function sets the status for us */
1147                                 break;
1148                         case FLAC__STREAM_DECODER_READ_FRAME:
1149                                 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
1150                                         return false; /* above function sets the status for us */
1151                                 if(got_a_frame)
1152                                         return true; /* above function sets the status for us */
1153                                 break;
1154                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1155                         case FLAC__STREAM_DECODER_ABORTED:
1156                                 return true;
1157                         default:
1158                                 FLAC__ASSERT(0);
1159                                 return false;
1160                 }
1161         }
1162 }
1163
1164 FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
1165 {
1166         FLAC__uint64 length;
1167
1168         FLAC__ASSERT(0 != decoder);
1169
1170         if(
1171                 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
1172                 decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
1173                 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
1174                 decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
1175                 decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
1176         )
1177                 return false;
1178
1179         if(0 == decoder->private_->seek_callback)
1180                 return false;
1181
1182         FLAC__ASSERT(decoder->private_->seek_callback);
1183         FLAC__ASSERT(decoder->private_->tell_callback);
1184         FLAC__ASSERT(decoder->private_->length_callback);
1185         FLAC__ASSERT(decoder->private_->eof_callback);
1186
1187         if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
1188                 return false;
1189
1190         decoder->private_->is_seeking = true;
1191
1192         /* turn off md5 checking if a seek is attempted */
1193         decoder->private_->do_md5_checking = false;
1194
1195         /* get the file length (currently our algorithm needs to know the length so it's also an error to get FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED) */
1196         if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
1197                 decoder->private_->is_seeking = false;
1198                 return false;
1199         }
1200
1201         /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
1202         if(
1203                 decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
1204                 decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
1205         ) {
1206                 if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
1207                         /* above call sets the state for us */
1208                         decoder->private_->is_seeking = false;
1209                         return false;
1210                 }
1211                 /* check this again in case we didn't know total_samples the first time */
1212                 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
1213                         decoder->private_->is_seeking = false;
1214                         return false;
1215                 }
1216         }
1217
1218         {
1219                 const FLAC__bool ok =
1220 #if FLAC__HAS_OGG
1221                         decoder->private_->is_ogg?
1222                         seek_to_absolute_sample_ogg_(decoder, length, sample) :
1223 #endif
1224                         seek_to_absolute_sample_(decoder, length, sample)
1225                 ;
1226                 decoder->private_->is_seeking = false;
1227                 return ok;
1228         }
1229 }
1230
1231 /***********************************************************************
1232  *
1233  * Protected class methods
1234  *
1235  ***********************************************************************/
1236
1237 unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
1238 {
1239         FLAC__ASSERT(0 != decoder);
1240         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1241         FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
1242         return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
1243 }
1244
1245 /***********************************************************************
1246  *
1247  * Private class methods
1248  *
1249  ***********************************************************************/
1250
1251 void set_defaults_(FLAC__StreamDecoder *decoder)
1252 {
1253 #if FLAC__HAS_OGG
1254         decoder->private_->is_ogg = false;
1255 #endif
1256         decoder->private_->read_callback = 0;
1257         decoder->private_->seek_callback = 0;
1258         decoder->private_->tell_callback = 0;
1259         decoder->private_->length_callback = 0;
1260         decoder->private_->eof_callback = 0;
1261         decoder->private_->write_callback = 0;
1262         decoder->private_->metadata_callback = 0;
1263         decoder->private_->error_callback = 0;
1264         decoder->private_->client_data = 0;
1265
1266         memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
1267         decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
1268         decoder->private_->metadata_filter_ids_count = 0;
1269
1270         decoder->protected_->md5_checking = false;
1271
1272 #if FLAC__HAS_OGG
1273         FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
1274 #endif
1275 }
1276
1277 /*
1278  * This will forcibly set stdin to binary mode (for OSes that require it)
1279  */
1280 FILE *get_binary_stdin_(void)
1281 {
1282         /* if something breaks here it is probably due to the presence or
1283          * absence of an underscore before the identifiers 'setmode',
1284          * 'fileno', and/or 'O_BINARY'; check your system header files.
1285          */
1286 #if defined _MSC_VER || defined __MINGW32__
1287         _setmode(_fileno(stdin), _O_BINARY);
1288 #elif defined __CYGWIN__ || defined __EMX__
1289         /* almost certainly not needed for any modern Cygwin, but let's be safe... */
1290         setmode(_fileno(stdin), _O_BINARY);
1291 #endif
1292
1293         return stdin;
1294 }
1295
1296 FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
1297 {
1298         unsigned i;
1299         FLAC__int32 *tmp;
1300
1301         if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
1302                 return true;
1303
1304         /* simply using realloc() is not practical because the number of channels may change mid-stream */
1305
1306         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
1307                 if(0 != decoder->private_->output[i]) {
1308                         free(decoder->private_->output[i]-4);
1309                         decoder->private_->output[i] = 0;
1310                 }
1311                 if(0 != decoder->private_->residual_unaligned[i]) {
1312                         free(decoder->private_->residual_unaligned[i]);
1313                         decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
1314                 }
1315         }
1316
1317         for(i = 0; i < channels; i++) {
1318                 /* WATCHOUT:
1319                  * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
1320                  * output arrays have a buffer of up to 3 zeroes in front
1321                  * (at negative indices) for alignment purposes; we use 4
1322                  * to keep the data well-aligned.
1323                  */
1324                 tmp = (FLAC__int32*)malloc(sizeof(FLAC__int32)*(size+4));
1325                 if(tmp == 0) {
1326                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1327                         return false;
1328                 }
1329                 memset(tmp, 0, sizeof(FLAC__int32)*4);
1330                 decoder->private_->output[i] = tmp + 4;
1331
1332                 /* WATCHOUT:
1333                  * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
1334                  */
1335                 if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
1336                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1337                         return false;
1338                 }
1339         }
1340
1341         decoder->private_->output_capacity = size;
1342         decoder->private_->output_channels = channels;
1343
1344         return true;
1345 }
1346
1347 FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
1348 {
1349         unsigned i;
1350
1351         FLAC__ASSERT(0 != decoder);
1352         FLAC__ASSERT(0 != decoder->private_);
1353
1354         for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
1355                 if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
1356                         return true;
1357
1358         return false;
1359 }
1360
1361 FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
1362 {
1363         FLAC__uint32 x;
1364         unsigned i, id;
1365         FLAC__bool first = true;
1366
1367         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1368
1369         for(i = id = 0; i < 4; ) {
1370                 if(decoder->private_->cached) {
1371                         x = (FLAC__uint32)decoder->private_->lookahead;
1372                         decoder->private_->cached = false;
1373                 }
1374                 else {
1375                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1376                                 return false; /* read_callback_ sets the state for us */
1377                 }
1378                 if(x == FLAC__STREAM_SYNC_STRING[i]) {
1379                         first = true;
1380                         i++;
1381                         id = 0;
1382                         continue;
1383                 }
1384                 if(x == ID3V2_TAG_[id]) {
1385                         id++;
1386                         i = 0;
1387                         if(id == 3) {
1388                                 if(!skip_id3v2_tag_(decoder))
1389                                         return false; /* skip_id3v2_tag_ sets the state for us */
1390                         }
1391                         continue;
1392                 }
1393                 id = 0;
1394                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1395                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1396                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1397                                 return false; /* read_callback_ sets the state for us */
1398
1399                         /* 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 */
1400                         /* else we have to check if the second byte is the end of a sync code */
1401                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1402                                 decoder->private_->lookahead = (FLAC__byte)x;
1403                                 decoder->private_->cached = true;
1404                         }
1405                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1406                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1407                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1408                                 return true;
1409                         }
1410                 }
1411                 i = 0;
1412                 if(first) {
1413                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1414                         first = false;
1415                 }
1416         }
1417
1418         decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
1419         return true;
1420 }
1421
1422 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
1423 {
1424         FLAC__bool is_last;
1425         FLAC__uint32 i, x, type, length;
1426
1427         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1428
1429         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
1430                 return false; /* read_callback_ sets the state for us */
1431         is_last = x? true : false;
1432
1433         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
1434                 return false; /* read_callback_ sets the state for us */
1435
1436         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
1437                 return false; /* read_callback_ sets the state for us */
1438
1439         if(type == FLAC__METADATA_TYPE_STREAMINFO) {
1440                 if(!read_metadata_streaminfo_(decoder, is_last, length))
1441                         return false;
1442
1443                 decoder->private_->has_stream_info = true;
1444                 if(0 == memcmp(decoder->private_->stream_info.data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
1445                         decoder->private_->do_md5_checking = false;
1446                 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
1447                         decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
1448         }
1449         else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
1450                 if(!read_metadata_seektable_(decoder, is_last, length))
1451                         return false;
1452
1453                 decoder->private_->has_seek_table = true;
1454                 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
1455                         decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
1456         }
1457         else {
1458                 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
1459                 unsigned real_length = length;
1460                 FLAC__StreamMetadata block;
1461
1462                 block.is_last = is_last;
1463                 block.type = (FLAC__MetadataType)type;
1464                 block.length = length;
1465
1466                 if(type == FLAC__METADATA_TYPE_APPLICATION) {
1467                         if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
1468                                 return false; /* read_callback_ sets the state for us */
1469
1470                         real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
1471
1472                         if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
1473                                 skip_it = !skip_it;
1474                 }
1475
1476                 if(skip_it) {
1477                         if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
1478                                 return false; /* read_callback_ sets the state for us */
1479                 }
1480                 else {
1481                         switch(type) {
1482                                 case FLAC__METADATA_TYPE_PADDING:
1483                                         /* skip the padding bytes */
1484                                         if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
1485                                                 return false; /* read_callback_ sets the state for us */
1486                                         break;
1487                                 case FLAC__METADATA_TYPE_APPLICATION:
1488                                         /* remember, we read the ID already */
1489                                         if(real_length > 0) {
1490                                                 if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
1491                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1492                                                         return false;
1493                                                 }
1494                                                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
1495                                                         return false; /* read_callback_ sets the state for us */
1496                                         }
1497                                         else
1498                                                 block.data.application.data = 0;
1499                                         break;
1500                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1501                                         if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
1502                                                 return false;
1503                                         break;
1504                                 case FLAC__METADATA_TYPE_CUESHEET:
1505                                         if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
1506                                                 return false;
1507                                         break;
1508                                 case FLAC__METADATA_TYPE_PICTURE:
1509                                         if(!read_metadata_picture_(decoder, &block.data.picture))
1510                                                 return false;
1511                                         break;
1512                                 case FLAC__METADATA_TYPE_STREAMINFO:
1513                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1514                                         FLAC__ASSERT(0);
1515                                         break;
1516                                 default:
1517                                         if(real_length > 0) {
1518                                                 if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
1519                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1520                                                         return false;
1521                                                 }
1522                                                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
1523                                                         return false; /* read_callback_ sets the state for us */
1524                                         }
1525                                         else
1526                                                 block.data.unknown.data = 0;
1527                                         break;
1528                         }
1529                         if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
1530                                 decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1531
1532                         /* now we have to free any malloc'ed data in the block */
1533                         switch(type) {
1534                                 case FLAC__METADATA_TYPE_PADDING:
1535                                         break;
1536                                 case FLAC__METADATA_TYPE_APPLICATION:
1537                                         if(0 != block.data.application.data)
1538                                                 free(block.data.application.data);
1539                                         break;
1540                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1541                                         if(0 != block.data.vorbis_comment.vendor_string.entry)
1542                                                 free(block.data.vorbis_comment.vendor_string.entry);
1543                                         if(block.data.vorbis_comment.num_comments > 0)
1544                                                 for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
1545                                                         if(0 != block.data.vorbis_comment.comments[i].entry)
1546                                                                 free(block.data.vorbis_comment.comments[i].entry);
1547                                         if(0 != block.data.vorbis_comment.comments)
1548                                                 free(block.data.vorbis_comment.comments);
1549                                         break;
1550                                 case FLAC__METADATA_TYPE_CUESHEET:
1551                                         if(block.data.cue_sheet.num_tracks > 0)
1552                                                 for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
1553                                                         if(0 != block.data.cue_sheet.tracks[i].indices)
1554                                                                 free(block.data.cue_sheet.tracks[i].indices);
1555                                         if(0 != block.data.cue_sheet.tracks)
1556                                                 free(block.data.cue_sheet.tracks);
1557                                         break;
1558                                 case FLAC__METADATA_TYPE_PICTURE:
1559                                         if(0 != block.data.picture.mime_type)
1560                                                 free(block.data.picture.mime_type);
1561                                         if(0 != block.data.picture.description)
1562                                                 free(block.data.picture.description);
1563                                         if(0 != block.data.picture.data)
1564                                                 free(block.data.picture.data);
1565                                         break;
1566                                 case FLAC__METADATA_TYPE_STREAMINFO:
1567                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1568                                         FLAC__ASSERT(0);
1569                                 default:
1570                                         if(0 != block.data.unknown.data)
1571                                                 free(block.data.unknown.data);
1572                                         break;
1573                         }
1574                 }
1575         }
1576
1577         if(is_last) {
1578                 /* if this fails, it's OK, it's just a hint for the seek routine */
1579                 if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
1580                         decoder->private_->first_frame_offset = 0;
1581                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1582         }
1583
1584         return true;
1585 }
1586
1587 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1588 {
1589         FLAC__uint32 x;
1590         unsigned bits, used_bits = 0;
1591
1592         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1593
1594         decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
1595         decoder->private_->stream_info.is_last = is_last;
1596         decoder->private_->stream_info.length = length;
1597
1598         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1599         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
1600                 return false; /* read_callback_ sets the state for us */
1601         decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1602         used_bits += bits;
1603
1604         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1605         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
1606                 return false; /* read_callback_ sets the state for us */
1607         decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1608         used_bits += bits;
1609
1610         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1611         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
1612                 return false; /* read_callback_ sets the state for us */
1613         decoder->private_->stream_info.data.stream_info.min_framesize = x;
1614         used_bits += bits;
1615
1616         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1617         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
1618                 return false; /* read_callback_ sets the state for us */
1619         decoder->private_->stream_info.data.stream_info.max_framesize = x;
1620         used_bits += bits;
1621
1622         bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1623         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
1624                 return false; /* read_callback_ sets the state for us */
1625         decoder->private_->stream_info.data.stream_info.sample_rate = x;
1626         used_bits += bits;
1627
1628         bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1629         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
1630                 return false; /* read_callback_ sets the state for us */
1631         decoder->private_->stream_info.data.stream_info.channels = x+1;
1632         used_bits += bits;
1633
1634         bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1635         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
1636                 return false; /* read_callback_ sets the state for us */
1637         decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1638         used_bits += bits;
1639
1640         bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1641         if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
1642                 return false; /* read_callback_ sets the state for us */
1643         used_bits += bits;
1644
1645         if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
1646                 return false; /* read_callback_ sets the state for us */
1647         used_bits += 16*8;
1648
1649         /* skip the rest of the block */
1650         FLAC__ASSERT(used_bits % 8 == 0);
1651         length -= (used_bits / 8);
1652         if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
1653                 return false; /* read_callback_ sets the state for us */
1654
1655         return true;
1656 }
1657
1658 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1659 {
1660         FLAC__uint32 i, x;
1661         FLAC__uint64 xx;
1662
1663         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1664
1665         decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1666         decoder->private_->seek_table.is_last = is_last;
1667         decoder->private_->seek_table.length = length;
1668
1669         decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1670
1671         /* use realloc since we may pass through here several times (e.g. after seeking) */
1672         if(0 == (decoder->private_->seek_table.data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)realloc(decoder->private_->seek_table.data.seek_table.points, decoder->private_->seek_table.data.seek_table.num_points * sizeof(FLAC__StreamMetadata_SeekPoint)))) {
1673                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1674                 return false;
1675         }
1676         for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1677                 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
1678                         return false; /* read_callback_ sets the state for us */
1679                 decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1680
1681                 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
1682                         return false; /* read_callback_ sets the state for us */
1683                 decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1684
1685                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
1686                         return false; /* read_callback_ sets the state for us */
1687                 decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1688         }
1689         length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1690         /* if there is a partial point left, skip over it */
1691         if(length > 0) {
1692                 /*@@@ do a send_error_to_client_() here?  there's an argument for either way */
1693                 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
1694                         return false; /* read_callback_ sets the state for us */
1695         }
1696
1697         return true;
1698 }
1699
1700 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1701 {
1702         FLAC__uint32 i;
1703
1704         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1705
1706         /* read vendor string */
1707         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1708         if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
1709                 return false; /* read_callback_ sets the state for us */
1710         if(obj->vendor_string.length > 0) {
1711                 if(0 == (obj->vendor_string.entry = (FLAC__byte*)malloc(obj->vendor_string.length+1))) {
1712                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1713                         return false;
1714                 }
1715                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
1716                         return false; /* read_callback_ sets the state for us */
1717                 obj->vendor_string.entry[obj->vendor_string.length] = '\0';
1718         }
1719         else
1720                 obj->vendor_string.entry = 0;
1721
1722         /* read num comments */
1723         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1724         if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
1725                 return false; /* read_callback_ sets the state for us */
1726
1727         /* read comments */
1728         if(obj->num_comments > 0) {
1729                 if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)malloc(obj->num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1730                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1731                         return false;
1732                 }
1733                 for(i = 0; i < obj->num_comments; i++) {
1734                         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1735                         if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
1736                                 return false; /* read_callback_ sets the state for us */
1737                         if(obj->comments[i].length > 0) {
1738                                 if(0 == (obj->comments[i].entry = (FLAC__byte*)malloc(obj->comments[i].length+1))) {
1739                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1740                                         return false;
1741                                 }
1742                                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
1743                                         return false; /* read_callback_ sets the state for us */
1744                                 obj->comments[i].entry[obj->comments[i].length] = '\0';
1745                         }
1746                         else
1747                                 obj->comments[i].entry = 0;
1748                 }
1749         }
1750         else {
1751                 obj->comments = 0;
1752         }
1753
1754         return true;
1755 }
1756
1757 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1758 {
1759         FLAC__uint32 i, j, x;
1760
1761         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1762
1763         memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1764
1765         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1766         if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
1767                 return false; /* read_callback_ sets the state for us */
1768
1769         if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
1770                 return false; /* read_callback_ sets the state for us */
1771
1772         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
1773                 return false; /* read_callback_ sets the state for us */
1774         obj->is_cd = x? true : false;
1775
1776         if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
1777                 return false; /* read_callback_ sets the state for us */
1778
1779         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
1780                 return false; /* read_callback_ sets the state for us */
1781         obj->num_tracks = x;
1782
1783         if(obj->num_tracks > 0) {
1784                 if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1785                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1786                         return false;
1787                 }
1788                 for(i = 0; i < obj->num_tracks; i++) {
1789                         FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1790                         if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
1791                                 return false; /* read_callback_ sets the state for us */
1792
1793                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
1794                                 return false; /* read_callback_ sets the state for us */
1795                         track->number = (FLAC__byte)x;
1796
1797                         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1798                         if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
1799                                 return false; /* read_callback_ sets the state for us */
1800
1801                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
1802                                 return false; /* read_callback_ sets the state for us */
1803                         track->type = x;
1804
1805                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
1806                                 return false; /* read_callback_ sets the state for us */
1807                         track->pre_emphasis = x;
1808
1809                         if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
1810                                 return false; /* read_callback_ sets the state for us */
1811
1812                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
1813                                 return false; /* read_callback_ sets the state for us */
1814                         track->num_indices = (FLAC__byte)x;
1815
1816                         if(track->num_indices > 0) {
1817                                 if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1818                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1819                                         return false;
1820                                 }
1821                                 for(j = 0; j < track->num_indices; j++) {
1822                                         FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1823                                         if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
1824                                                 return false; /* read_callback_ sets the state for us */
1825
1826                                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
1827                                                 return false; /* read_callback_ sets the state for us */
1828                                         index->number = (FLAC__byte)x;
1829
1830                                         if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
1831                                                 return false; /* read_callback_ sets the state for us */
1832                                 }
1833                         }
1834                 }
1835         }
1836
1837         return true;
1838 }
1839
1840 FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
1841 {
1842         FLAC__uint32 x;
1843
1844         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1845
1846         /* read type */
1847         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
1848                 return false; /* read_callback_ sets the state for us */
1849         obj->type = x;
1850
1851         /* read MIME type */
1852         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
1853                 return false; /* read_callback_ sets the state for us */
1854         if(0 == (obj->mime_type = (char*)malloc(x+1))) {
1855                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1856                 return false;
1857         }
1858         if(x > 0) {
1859                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
1860                         return false; /* read_callback_ sets the state for us */
1861         }
1862         obj->mime_type[x] = '\0';
1863
1864         /* read description */
1865         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
1866                 return false; /* read_callback_ sets the state for us */
1867         if(0 == (obj->description = (FLAC__byte*)malloc(x+1))) {
1868                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1869                 return false;
1870         }
1871         if(x > 0) {
1872                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
1873                         return false; /* read_callback_ sets the state for us */
1874         }
1875         obj->description[x] = '\0';
1876
1877         /* read width */
1878         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
1879                 return false; /* read_callback_ sets the state for us */
1880
1881         /* read height */
1882         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
1883                 return false; /* read_callback_ sets the state for us */
1884
1885         /* read depth */
1886         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
1887                 return false; /* read_callback_ sets the state for us */
1888
1889         /* read colors */
1890         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
1891                 return false; /* read_callback_ sets the state for us */
1892
1893         /* read data */
1894         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
1895                 return false; /* read_callback_ sets the state for us */
1896         if(0 == (obj->data = (FLAC__byte*)malloc(obj->data_length))) {
1897                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1898                 return false;
1899         }
1900         if(obj->data_length > 0) {
1901                 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
1902                         return false; /* read_callback_ sets the state for us */
1903         }
1904
1905         return true;
1906 }
1907
1908 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1909 {
1910         FLAC__uint32 x;
1911         unsigned i, skip;
1912
1913         /* skip the version and flags bytes */
1914         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
1915                 return false; /* read_callback_ sets the state for us */
1916         /* get the size (in bytes) to skip */
1917         skip = 0;
1918         for(i = 0; i < 4; i++) {
1919                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1920                         return false; /* read_callback_ sets the state for us */
1921                 skip <<= 7;
1922                 skip |= (x & 0x7f);
1923         }
1924         /* skip the rest of the tag */
1925         if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
1926                 return false; /* read_callback_ sets the state for us */
1927         return true;
1928 }
1929
1930 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1931 {
1932         FLAC__uint32 x;
1933         FLAC__bool first = true;
1934
1935         /* If we know the total number of samples in the stream, stop if we've read that many. */
1936         /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1937         if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
1938                 if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
1939                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1940                         return true;
1941                 }
1942         }
1943
1944         /* make sure we're byte aligned */
1945         if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
1946                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
1947                         return false; /* read_callback_ sets the state for us */
1948         }
1949
1950         while(1) {
1951                 if(decoder->private_->cached) {
1952                         x = (FLAC__uint32)decoder->private_->lookahead;
1953                         decoder->private_->cached = false;
1954                 }
1955                 else {
1956                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1957                                 return false; /* read_callback_ sets the state for us */
1958                 }
1959                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1960                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1961                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1962                                 return false; /* read_callback_ sets the state for us */
1963
1964                         /* 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 */
1965                         /* else we have to check if the second byte is the end of a sync code */
1966                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1967                                 decoder->private_->lookahead = (FLAC__byte)x;
1968                                 decoder->private_->cached = true;
1969                         }
1970                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1971                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1972                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1973                                 return true;
1974                         }
1975                 }
1976                 if(first) {
1977                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1978                         first = false;
1979                 }
1980         }
1981
1982         return true;
1983 }
1984
1985 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
1986 {
1987         unsigned channel;
1988         unsigned i;
1989         FLAC__int32 mid, side;
1990         unsigned frame_crc; /* the one we calculate from the input stream */
1991         FLAC__uint32 x;
1992
1993         *got_a_frame = false;
1994
1995         /* init the CRC */
1996         frame_crc = 0;
1997         frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
1998         frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
1999         FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
2000
2001         if(!read_frame_header_(decoder))
2002                 return false;
2003         if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
2004                 return true;
2005         if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
2006                 return false;
2007         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2008                 /*
2009                  * first figure the correct bits-per-sample of the subframe
2010                  */
2011                 unsigned bps = decoder->private_->frame.header.bits_per_sample;
2012                 switch(decoder->private_->frame.header.channel_assignment) {
2013                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2014                                 /* no adjustment needed */
2015                                 break;
2016                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2017                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2018                                 if(channel == 1)
2019                                         bps++;
2020                                 break;
2021                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2022                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2023                                 if(channel == 0)
2024                                         bps++;
2025                                 break;
2026                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2027                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2028                                 if(channel == 1)
2029                                         bps++;
2030                                 break;
2031                         default:
2032                                 FLAC__ASSERT(0);
2033                 }
2034                 /*
2035                  * now read it
2036                  */
2037                 if(!read_subframe_(decoder, channel, bps, do_full_decode))
2038                         return false;
2039                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2040                         return true;
2041         }
2042         if(!read_zero_padding_(decoder))
2043                 return false;
2044
2045         /*
2046          * Read the frame CRC-16 from the footer and check
2047          */
2048         frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
2049         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
2050                 return false; /* read_callback_ sets the state for us */
2051         if(frame_crc == x) {
2052                 if(do_full_decode) {
2053                         /* Undo any special channel coding */
2054                         switch(decoder->private_->frame.header.channel_assignment) {
2055                                 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2056                                         /* do nothing */
2057                                         break;
2058                                 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2059                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2060                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2061                                                 decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
2062                                         break;
2063                                 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2064                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2065                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2066                                                 decoder->private_->output[0][i] += decoder->private_->output[1][i];
2067                                         break;
2068                                 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2069                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2070                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2071 #if 1
2072                                                 mid = decoder->private_->output[0][i];
2073                                                 side = decoder->private_->output[1][i];
2074                                                 mid <<= 1;
2075                                                 mid |= (side & 1); /* i.e. if 'side' is odd... */
2076                                                 decoder->private_->output[0][i] = (mid + side) >> 1;
2077                                                 decoder->private_->output[1][i] = (mid - side) >> 1;
2078 #else
2079                                                 //@@@@@@ OPT: try without 'side' temp variable
2080                                                 mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
2081                                                 decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
2082                                                 decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
2083 #endif
2084                                         }
2085                                         break;
2086                                 default:
2087                                         FLAC__ASSERT(0);
2088                                         break;
2089                         }
2090                 }
2091         }
2092         else {
2093                 /* Bad frame, emit error and zero the output signal */
2094                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
2095                 if(do_full_decode) {
2096                         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2097                                 memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2098                         }
2099                 }
2100         }
2101
2102         *got_a_frame = true;
2103
2104         /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
2105         if(decoder->private_->next_fixed_block_size)
2106                 decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
2107
2108         /* put the latest values into the public section of the decoder instance */
2109         decoder->protected_->channels = decoder->private_->frame.header.channels;
2110         decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
2111         decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
2112         decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
2113         decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
2114
2115         FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2116         decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
2117
2118         /* write it */
2119         if(do_full_decode) {
2120                 if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
2121                         return false;
2122         }
2123
2124         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2125         return true;
2126 }
2127
2128 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
2129 {
2130         FLAC__uint32 x;
2131         FLAC__uint64 xx;
2132         unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
2133         FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
2134         unsigned raw_header_len;
2135         FLAC__bool is_unparseable = false;
2136
2137         FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
2138
2139         /* init the raw header with the saved bits from synchronization */
2140         raw_header[0] = decoder->private_->header_warmup[0];
2141         raw_header[1] = decoder->private_->header_warmup[1];
2142         raw_header_len = 2;
2143
2144         /* check to make sure that reserved bit is 0 */
2145         if(raw_header[1] & 0x02) /* MAGIC NUMBER */
2146                 is_unparseable = true;
2147
2148         /*
2149          * Note that along the way as we read the header, we look for a sync
2150          * code inside.  If we find one it would indicate that our original
2151          * sync was bad since there cannot be a sync code in a valid header.
2152          *
2153          * Three kinds of things can go wrong when reading the frame header:
2154          *  1) We may have sync'ed incorrectly and not landed on a frame header.
2155          *     If we don't find a sync code, it can end up looking like we read
2156          *     a valid but unparseable header, until getting to the frame header
2157          *     CRC.  Even then we could get a false positive on the CRC.
2158          *  2) We may have sync'ed correctly but on an unparseable frame (from a
2159          *     future encoder).
2160          *  3) We may be on a damaged frame which appears valid but unparseable.
2161          *
2162          * For all these reasons, we try and read a complete frame header as
2163          * long as it seems valid, even if unparseable, up until the frame
2164          * header CRC.
2165          */
2166
2167         /*
2168          * read in the raw header as bytes so we can CRC it, and parse it on the way
2169          */
2170         for(i = 0; i < 2; i++) {
2171                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2172                         return false; /* read_callback_ sets the state for us */
2173                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
2174                         /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
2175                         decoder->private_->lookahead = (FLAC__byte)x;
2176                         decoder->private_->cached = true;
2177                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2178                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2179                         return true;
2180                 }
2181                 raw_header[raw_header_len++] = (FLAC__byte)x;
2182         }
2183
2184         switch(x = raw_header[2] >> 4) {
2185                 case 0:
2186                         is_unparseable = true;
2187                         break;
2188                 case 1:
2189                         decoder->private_->frame.header.blocksize = 192;
2190                         break;
2191                 case 2:
2192                 case 3:
2193                 case 4:
2194                 case 5:
2195                         decoder->private_->frame.header.blocksize = 576 << (x-2);
2196                         break;
2197                 case 6:
2198                 case 7:
2199                         blocksize_hint = x;
2200                         break;
2201                 case 8:
2202                 case 9:
2203                 case 10:
2204                 case 11:
2205                 case 12:
2206                 case 13:
2207                 case 14:
2208                 case 15:
2209                         decoder->private_->frame.header.blocksize = 256 << (x-8);
2210                         break;
2211                 default:
2212                         FLAC__ASSERT(0);
2213                         break;
2214         }
2215
2216         switch(x = raw_header[2] & 0x0f) {
2217                 case 0:
2218                         if(decoder->private_->has_stream_info)
2219                                 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
2220                         else
2221                                 is_unparseable = true;
2222                         break;
2223                 case 1:
2224                         decoder->private_->frame.header.sample_rate = 88200;
2225                         break;
2226                 case 2:
2227                         decoder->private_->frame.header.sample_rate = 176400;
2228                         break;
2229                 case 3:
2230                         decoder->private_->frame.header.sample_rate = 192000;
2231                         break;
2232                 case 4:
2233                         decoder->private_->frame.header.sample_rate = 8000;
2234                         break;
2235                 case 5:
2236                         decoder->private_->frame.header.sample_rate = 16000;
2237                         break;
2238                 case 6:
2239                         decoder->private_->frame.header.sample_rate = 22050;
2240                         break;
2241                 case 7:
2242                         decoder->private_->frame.header.sample_rate = 24000;
2243                         break;
2244                 case 8:
2245                         decoder->private_->frame.header.sample_rate = 32000;
2246                         break;
2247                 case 9:
2248                         decoder->private_->frame.header.sample_rate = 44100;
2249                         break;
2250                 case 10:
2251                         decoder->private_->frame.header.sample_rate = 48000;
2252                         break;
2253                 case 11:
2254                         decoder->private_->frame.header.sample_rate = 96000;
2255                         break;
2256                 case 12:
2257                 case 13:
2258                 case 14:
2259                         sample_rate_hint = x;
2260                         break;
2261                 case 15:
2262                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2263                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2264                         return true;
2265                 default:
2266                         FLAC__ASSERT(0);
2267         }
2268
2269         x = (unsigned)(raw_header[3] >> 4);
2270         if(x & 8) {
2271                 decoder->private_->frame.header.channels = 2;
2272                 switch(x & 7) {
2273                         case 0:
2274                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2275                                 break;
2276                         case 1:
2277                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2278                                 break;
2279                         case 2:
2280                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2281                                 break;
2282                         default:
2283                                 is_unparseable = true;
2284                                 break;
2285                 }
2286         }
2287         else {
2288                 decoder->private_->frame.header.channels = (unsigned)x + 1;
2289                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2290         }
2291
2292         switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2293                 case 0:
2294                         if(decoder->private_->has_stream_info)
2295                                 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2296                         else
2297                                 is_unparseable = true;
2298                         break;
2299                 case 1:
2300                         decoder->private_->frame.header.bits_per_sample = 8;
2301                         break;
2302                 case 2:
2303                         decoder->private_->frame.header.bits_per_sample = 12;
2304                         break;
2305                 case 4:
2306                         decoder->private_->frame.header.bits_per_sample = 16;
2307                         break;
2308                 case 5:
2309                         decoder->private_->frame.header.bits_per_sample = 20;
2310                         break;
2311                 case 6:
2312                         decoder->private_->frame.header.bits_per_sample = 24;
2313                         break;
2314                 case 3:
2315                 case 7:
2316                         is_unparseable = true;
2317                         break;
2318                 default:
2319                         FLAC__ASSERT(0);
2320                         break;
2321         }
2322
2323         /* check to make sure that reserved bit is 0 */
2324         if(raw_header[3] & 0x01) /* MAGIC NUMBER */
2325                 is_unparseable = true;
2326
2327         /* read the frame's starting sample number (or frame number as the case may be) */
2328         if(
2329                 raw_header[1] & 0x01 ||
2330                 /*@@@ this clause is a concession to the old way of doing variable blocksize; the only known implementation is flake and can probably be removed without inconveniencing anyone */
2331                 (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
2332         ) { /* variable blocksize */
2333                 if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
2334                         return false; /* read_callback_ sets the state for us */
2335                 if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
2336                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2337                         decoder->private_->cached = true;
2338                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2339                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2340                         return true;
2341                 }
2342                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2343                 decoder->private_->frame.header.number.sample_number = xx;
2344         }
2345         else { /* fixed blocksize */
2346                 if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
2347                         return false; /* read_callback_ sets the state for us */
2348                 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
2349                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2350                         decoder->private_->cached = true;
2351                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2352                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2353                         return true;
2354                 }
2355                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2356                 decoder->private_->frame.header.number.frame_number = x;
2357         }
2358
2359         if(blocksize_hint) {
2360                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2361                         return false; /* read_callback_ sets the state for us */
2362                 raw_header[raw_header_len++] = (FLAC__byte)x;
2363                 if(blocksize_hint == 7) {
2364                         FLAC__uint32 _x;
2365                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2366                                 return false; /* read_callback_ sets the state for us */
2367                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2368                         x = (x << 8) | _x;
2369                 }
2370                 decoder->private_->frame.header.blocksize = x+1;
2371         }
2372
2373         if(sample_rate_hint) {
2374                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2375                         return false; /* read_callback_ sets the state for us */
2376                 raw_header[raw_header_len++] = (FLAC__byte)x;
2377                 if(sample_rate_hint != 12) {
2378                         FLAC__uint32 _x;
2379                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2380                                 return false; /* read_callback_ sets the state for us */
2381                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2382                         x = (x << 8) | _x;
2383                 }
2384                 if(sample_rate_hint == 12)
2385                         decoder->private_->frame.header.sample_rate = x*1000;
2386                 else if(sample_rate_hint == 13)
2387                         decoder->private_->frame.header.sample_rate = x;
2388                 else
2389                         decoder->private_->frame.header.sample_rate = x*10;
2390         }
2391
2392         /* read the CRC-8 byte */
2393         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2394                 return false; /* read_callback_ sets the state for us */
2395         crc8 = (FLAC__byte)x;
2396
2397         if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
2398                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2399                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2400                 return true;
2401         }
2402
2403         /* calculate the sample number from the frame number if needed */
2404         decoder->private_->next_fixed_block_size = 0;
2405         if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
2406                 x = decoder->private_->frame.header.number.frame_number;
2407                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2408                 if(decoder->private_->fixed_block_size)
2409                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
2410                 else if(decoder->private_->has_stream_info) {
2411                         if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
2412                                 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
2413                                 decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
2414                         }
2415                         else
2416                                 is_unparseable = true;
2417                 }
2418                 else if(x == 0) {
2419                         decoder->private_->frame.header.number.sample_number = 0;
2420                         decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
2421                 }
2422                 else {
2423                         /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
2424                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
2425                 }
2426         }
2427
2428         if(is_unparseable) {
2429                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2430                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2431                 return true;
2432         }
2433
2434         return true;
2435 }
2436
2437 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2438 {
2439         FLAC__uint32 x;
2440         FLAC__bool wasted_bits;
2441         unsigned i;
2442
2443         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
2444                 return false; /* read_callback_ sets the state for us */
2445
2446         wasted_bits = (x & 1);
2447         x &= 0xfe;
2448
2449         if(wasted_bits) {
2450                 unsigned u;
2451                 if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
2452                         return false; /* read_callback_ sets the state for us */
2453                 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
2454                 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
2455         }
2456         else
2457                 decoder->private_->frame.subframes[channel].wasted_bits = 0;
2458
2459         /*
2460          * Lots of magic numbers here
2461          */
2462         if(x & 0x80) {
2463                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2464                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2465                 return true;
2466         }
2467         else if(x == 0) {
2468                 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2469                         return false;
2470         }
2471         else if(x == 2) {
2472                 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2473                         return false;
2474         }
2475         else if(x < 16) {
2476                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2477                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2478                 return true;
2479         }
2480         else if(x <= 24) {
2481                 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2482                         return false;
2483                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2484                         return true;
2485         }
2486         else if(x < 64) {
2487                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2488                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2489                 return true;
2490         }
2491         else {
2492                 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2493                         return false;
2494                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2495                         return true;
2496         }
2497
2498         if(wasted_bits && do_full_decode) {
2499                 x = decoder->private_->frame.subframes[channel].wasted_bits;
2500                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2501                         decoder->private_->output[channel][i] <<= x;
2502         }
2503
2504         return true;
2505 }
2506
2507 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2508 {
2509         FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2510         FLAC__int32 x;
2511         unsigned i;
2512         FLAC__int32 *output = decoder->private_->output[channel];
2513
2514         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2515
2516         if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2517                 return false; /* read_callback_ sets the state for us */
2518
2519         subframe->value = x;
2520
2521         /* decode the subframe */
2522         if(do_full_decode) {
2523                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2524                         output[i] = x;
2525         }
2526
2527         return true;
2528 }
2529
2530 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2531 {
2532         FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2533         FLAC__int32 i32;
2534         FLAC__uint32 u32;
2535         unsigned u;
2536
2537         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2538
2539         subframe->residual = decoder->private_->residual[channel];
2540         subframe->order = order;
2541
2542         /* read warm-up samples */
2543         for(u = 0; u < order; u++) {
2544                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2545                         return false; /* read_callback_ sets the state for us */
2546                 subframe->warmup[u] = i32;
2547         }
2548
2549         /* read entropy coding method info */
2550         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2551                 return false; /* read_callback_ sets the state for us */
2552         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2553         switch(subframe->entropy_coding_method.type) {
2554                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2555                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2556                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2557                                 return false; /* read_callback_ sets the state for us */
2558                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2559                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2560                         break;
2561                 default:
2562                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2563                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2564                         return true;
2565         }
2566
2567         /* read residual */
2568         switch(subframe->entropy_coding_method.type) {
2569                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2570                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2571                         if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
2572                                 return false;
2573                         break;
2574                 default:
2575                         FLAC__ASSERT(0);
2576         }
2577
2578         /* decode the subframe */
2579         if(do_full_decode) {
2580                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2581                 FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
2582         }
2583
2584         return true;
2585 }
2586
2587 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2588 {
2589         FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2590         FLAC__int32 i32;
2591         FLAC__uint32 u32;
2592         unsigned u;
2593
2594         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2595
2596         subframe->residual = decoder->private_->residual[channel];
2597         subframe->order = order;
2598
2599         /* read warm-up samples */
2600         for(u = 0; u < order; u++) {
2601                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2602                         return false; /* read_callback_ sets the state for us */
2603                 subframe->warmup[u] = i32;
2604         }
2605
2606         /* read qlp coeff precision */
2607         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
2608                 return false; /* read_callback_ sets the state for us */
2609         if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
2610                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2611                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2612                 return true;
2613         }
2614         subframe->qlp_coeff_precision = u32+1;
2615
2616         /* read qlp shift */
2617         if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
2618                 return false; /* read_callback_ sets the state for us */
2619         subframe->quantization_level = i32;
2620
2621         /* read quantized lp coefficiencts */
2622         for(u = 0; u < order; u++) {
2623                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
2624                         return false; /* read_callback_ sets the state for us */
2625                 subframe->qlp_coeff[u] = i32;
2626         }
2627
2628         /* read entropy coding method info */
2629         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2630                 return false; /* read_callback_ sets the state for us */
2631         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2632         switch(subframe->entropy_coding_method.type) {
2633                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2634                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2635                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2636                                 return false; /* read_callback_ sets the state for us */
2637                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2638                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2639                         break;
2640                 default:
2641                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2642                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2643                         return true;
2644         }
2645
2646         /* read residual */
2647         switch(subframe->entropy_coding_method.type) {
2648                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2649                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2650                         if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
2651                                 return false;
2652                         break;
2653                 default:
2654                         FLAC__ASSERT(0);
2655         }
2656
2657         /* decode the subframe */
2658         if(do_full_decode) {
2659                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2660                 /*@@@@@@ technically not pessimistic enough, should be more like
2661                 if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
2662                 */
2663                 if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2664                         if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2665                                 if(order <= 8)
2666                                         decoder->private_->local_lpc_restore_signal_16bit_order8(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
2667                                 else
2668                                         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);
2669                         }
2670                         else
2671                                 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);
2672                 else
2673                         decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
2674         }
2675
2676         return true;
2677 }
2678
2679 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2680 {
2681         FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2682         FLAC__int32 x, *residual = decoder->private_->residual[channel];
2683         unsigned i;
2684
2685         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2686
2687         subframe->data = residual;
2688
2689         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2690                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2691                         return false; /* read_callback_ sets the state for us */
2692                 residual[i] = x;
2693         }
2694
2695         /* decode the subframe */
2696         if(do_full_decode)
2697                 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2698
2699         return true;
2700 }
2701
2702 FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended)
2703 {
2704         FLAC__uint32 rice_parameter;
2705         int i;
2706         unsigned partition, sample, u;
2707         const unsigned partitions = 1u << partition_order;
2708         const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2709         const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
2710         const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
2711
2712         /* sanity checks */
2713         if(partition_order == 0) {
2714                 if(decoder->private_->frame.header.blocksize < predictor_order) {
2715                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2716                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2717                         return true;
2718                 }
2719         }
2720         else {
2721                 if(partition_samples < predictor_order) {
2722                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2723                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2724                         return true;
2725                 }
2726         }
2727
2728         if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2729                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2730                 return false;
2731         }
2732
2733         sample = 0;
2734         for(partition = 0; partition < partitions; partition++) {
2735                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
2736                         return false; /* read_callback_ sets the state for us */
2737                 partitioned_rice_contents->parameters[partition] = rice_parameter;
2738                 if(rice_parameter < pesc) {
2739                         partitioned_rice_contents->raw_bits[partition] = 0;
2740                         u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2741                         if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter))
2742                                 return false; /* read_callback_ sets the state for us */
2743                         sample += u;
2744                 }
2745                 else {
2746                         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
2747                                 return false; /* read_callback_ sets the state for us */
2748                         partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2749                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2750                                 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i, rice_parameter))
2751                                         return false; /* read_callback_ sets the state for us */
2752                                 residual[sample] = i;
2753                         }
2754                 }
2755         }
2756
2757         return true;
2758 }
2759
2760 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2761 {
2762         if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
2763                 FLAC__uint32 zero = 0;
2764                 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
2765                         return false; /* read_callback_ sets the state for us */
2766                 if(zero != 0) {
2767                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2768                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2769                 }
2770         }
2771         return true;
2772 }
2773
2774 FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
2775 {
2776         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2777
2778         if(
2779 #if FLAC__HAS_OGG
2780                 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2781                 !decoder->private_->is_ogg &&
2782 #endif
2783                 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2784         ) {
2785                 *bytes = 0;
2786                 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2787                 return false;
2788         }
2789         else if(*bytes > 0) {
2790                 /* While seeking, it is possible for our seek to land in the
2791                  * middle of audio data that looks exactly like a frame header
2792                  * from a future version of an encoder.  When that happens, our
2793                  * error callback will get an
2794                  * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
2795                  * unparseable_frame_count.  But there is a remote possibility
2796                  * that it is properly synced at such a "future-codec frame",
2797                  * so to make sure, we wait to see many "unparseable" errors in
2798                  * a row before bailing out.
2799                  */
2800                 if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2801                         decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2802                         return false;
2803                 }
2804                 else {
2805                         const FLAC__StreamDecoderReadStatus status =
2806 #if FLAC__HAS_OGG
2807                                 decoder->private_->is_ogg?
2808                                 read_callback_ogg_aspect_(decoder, buffer, bytes) :
2809 #endif
2810                                 decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
2811                         ;
2812                         if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
2813                                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2814                                 return false;
2815                         }
2816                         else if(*bytes == 0) {
2817                                 if(
2818                                         status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
2819                                         (
2820 #if FLAC__HAS_OGG
2821                                                 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2822                                                 !decoder->private_->is_ogg &&
2823 #endif
2824                                                 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2825                                         )
2826                                 ) {
2827                                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2828                                         return false;
2829                                 }
2830                                 else
2831                                         return true;
2832                         }
2833                         else
2834                                 return true;
2835                 }
2836         }
2837         else {
2838                 /* abort to avoid a deadlock */
2839                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2840                 return false;
2841         }
2842         /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
2843          * for Ogg FLAC.  This is because the ogg decoder aspect can lose sync
2844          * and at the same time hit the end of the stream (for example, seeking
2845          * to a point that is after the beginning of the last Ogg page).  There
2846          * is no way to report an Ogg sync loss through the callbacks (see note
2847          * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
2848          * So to keep the decoder from stopping at this point we gate the call
2849          * to the eof_callback and let the Ogg decoder aspect set the
2850          * end-of-stream state when it is needed.
2851          */
2852 }
2853
2854 #if FLAC__HAS_OGG
2855 FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
2856 {
2857         switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
2858                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
2859                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2860                 /* we don't really have a way to handle lost sync via read
2861                  * callback so we'll let it pass and let the underlying
2862                  * FLAC decoder catch the error
2863                  */
2864                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
2865                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2866                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
2867                         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2868                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
2869                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
2870                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
2871                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
2872                 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
2873                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2874                 default:
2875                         FLAC__ASSERT(0);
2876                         /* double protection */
2877                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2878         }
2879 }
2880
2881 FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
2882 {
2883         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
2884
2885         switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
2886                 case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
2887                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
2888                 case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
2889                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
2890                 case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
2891                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2892                 default:
2893                         /* double protection: */
2894                         FLAC__ASSERT(0);
2895                         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2896         }
2897 }
2898 #endif
2899
2900 FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2901 {
2902         if(decoder->private_->is_seeking) {
2903                 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
2904                 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
2905                 FLAC__uint64 target_sample = decoder->private_->target_sample;
2906
2907                 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2908
2909 #if FLAC__HAS_OGG
2910                 decoder->private_->got_a_frame = true;
2911 #endif
2912                 decoder->private_->last_frame = *frame; /* save the frame */
2913                 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
2914                         unsigned delta = (unsigned)(target_sample - this_frame_sample);
2915                         /* kick out of seek mode */
2916                         decoder->private_->is_seeking = false;
2917                         /* shift out the samples before target_sample */
2918                         if(delta > 0) {
2919                                 unsigned channel;
2920                                 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
2921                                 for(channel = 0; channel < frame->header.channels; channel++)
2922                                         newbuffer[channel] = buffer[channel] + delta;
2923                                 decoder->private_->last_frame.header.blocksize -= delta;
2924                                 decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
2925                                 /* write the relevant samples */
2926                                 return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
2927                         }
2928                         else {
2929                                 /* write the relevant samples */
2930                                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2931                         }
2932                 }
2933                 else {
2934                         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2935                 }
2936         }
2937         else {
2938                 /*
2939                  * If we never got STREAMINFO, turn off MD5 checking to save
2940                  * cycles since we don't have a sum to compare to anyway
2941                  */
2942                 if(!decoder->private_->has_stream_info)
2943                         decoder->private_->do_md5_checking = false;
2944                 if(decoder->private_->do_md5_checking) {
2945                         if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
2946                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2947                 }
2948                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2949         }
2950 }
2951
2952 void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2953 {
2954         if(!decoder->private_->is_seeking)
2955                 decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
2956         else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
2957                 decoder->private_->unparseable_frame_count++;
2958 }
2959
2960 FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2961 {
2962         FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
2963         FLAC__int64 pos = -1;
2964         int i;
2965         unsigned approx_bytes_per_frame;
2966         FLAC__bool first_seek = true;
2967         const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
2968         const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2969         const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
2970         const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
2971         const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
2972         /* take these from the current frame in case they've changed mid-stream */
2973         unsigned channels = FLAC__stream_decoder_get_channels(decoder);
2974         unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
2975         const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
2976
2977         /* use values from stream info if we didn't decode a frame */
2978         if(channels == 0)
2979                 channels = decoder->private_->stream_info.data.stream_info.channels;
2980         if(bps == 0)
2981                 bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2982
2983         /* we are just guessing here */
2984         if(max_framesize > 0)
2985                 approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
2986         /*
2987          * Check if it's a known fixed-blocksize stream.  Note that though
2988          * the spec doesn't allow zeroes in the STREAMINFO block, we may
2989          * never get a STREAMINFO block when decoding so the value of
2990          * min_blocksize might be zero.
2991          */
2992         else if(min_blocksize == max_blocksize && min_blocksize > 0) {
2993                 /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
2994                 approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
2995         }
2996         else
2997                 approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
2998
2999         /*
3000          * First, we set an upper and lower bound on where in the
3001          * stream we will search.  For now we assume the worst case
3002          * scenario, which is our best guess at the beginning of
3003          * the first frame and end of the stream.
3004          */
3005         lower_bound = first_frame_offset;
3006         lower_bound_sample = 0;
3007         upper_bound = stream_length;
3008         upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
3009
3010         /*@@@@@@ add step to validate seek table before using?  encoding to pipe leaves some flac files with incomplete seektables which screw us up */
3011
3012         /*
3013          * Now we refine the bounds if we have a seektable with
3014          * suitable points.  Note that according to the spec they
3015          * must be ordered by ascending sample number.
3016          */
3017         if(seek_table) {
3018                 /* find the closest seek point <= target_sample, if it exists */
3019                 for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
3020                         if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number <= target_sample)
3021                                 break;
3022                 }
3023                 if(i >= 0) { /* i.e. we found a suitable seek point... */
3024                         lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
3025                         lower_bound_sample = seek_table->points[i].sample_number;
3026                 }
3027
3028                 /* find the closest seek point > target_sample, if it exists */
3029                 for(i = 0; i < (int)seek_table->num_points; i++) {
3030                         if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number > target_sample)
3031                                 break;
3032                 }
3033                 if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
3034                         upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
3035                         upper_bound_sample = seek_table->points[i].sample_number;
3036                 }
3037         }
3038
3039         FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
3040         /* there are 2 insidious ways that the following equality occurs, which
3041          * we need to fix:
3042          *  1) total_samples is 0 (unknown) and target_sample is 0
3043          *  2) total_samples is 0 (unknown) and target_sample happens to be
3044          *     exactly equal to the last seek point in the seek table; this
3045          *     means there is no seek point above it, and upper_bound_samples
3046          *     remains equal to the estimate (of target_samples) we made above
3047          * in either case it does not hurt to move upper_bound_sample up by 1
3048          */
3049         if(upper_bound_sample == lower_bound_sample)
3050                 upper_bound_sample++;
3051
3052         decoder->private_->target_sample = target_sample;
3053         while(1) {
3054                 /* check if the bounds are still ok */
3055                 if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
3056                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3057                         return false;
3058                 }
3059 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3060 #if defined _MSC_VER || defined __MINGW32__
3061                 /* with VC++ you have to spoon feed it the casting */
3062                 pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(FLAC__int64)(target_sample - lower_bound_sample) / (FLAC__double)(FLAC__int64)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(FLAC__int64)(upper_bound - lower_bound)) - approx_bytes_per_frame;
3063 #else
3064                 pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(target_sample - lower_bound_sample) / (FLAC__double)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(upper_bound - lower_bound)) - approx_bytes_per_frame;
3065 #endif
3066 #else
3067                 /* a little less accurate: */
3068                 if(upper_bound - lower_bound < 0xffffffff)
3069                         pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_sample - lower_bound_sample) * (upper_bound - lower_bound)) / (upper_bound_sample - lower_bound_sample)) - approx_bytes_per_frame;
3070                 else /* @@@ WATCHOUT, ~2TB limit */
3071                         pos = (FLAC__int64)lower_bound + (FLAC__int64)((((target_sample - lower_bound_sample)>>8) * ((upper_bound - lower_bound)>>8)) / ((upper_bound_sample - lower_bound_sample)>>16)) - approx_bytes_per_frame;
3072 #endif
3073                 if(pos >= (FLAC__int64)upper_bound)
3074                         pos = (FLAC__int64)upper_bound - 1;
3075                 if(pos < (FLAC__int64)lower_bound)
3076                         pos = (FLAC__int64)lower_bound;
3077                 if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3078                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3079                         return false;
3080                 }
3081                 if(!FLAC__stream_decoder_flush(decoder)) {
3082                         /* above call sets the state for us */
3083                         return false;
3084                 }
3085                 /* Now we need to get a frame.  First we need to reset our
3086                  * unparseable_frame_count; if we get too many unparseable
3087                  * frames in a row, the read callback will return