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