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