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