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