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