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