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