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