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