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