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