1 /* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007 Josh Coalson
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #if defined _MSC_VER || defined __MINGW32__
37 #include <io.h> /* for _setmode() */
38 #include <fcntl.h> /* for _O_BINARY */
40 #if defined __CYGWIN__ || defined __EMX__
41 #include <io.h> /* for setmode(), O_BINARY */
42 #include <fcntl.h> /* for _O_BINARY */
45 #include <stdlib.h> /* for malloc() */
46 #include <string.h> /* for memset/memcpy() */
47 #include <sys/stat.h> /* for stat() */
48 #include <sys/types.h> /* for off_t */
49 #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
50 #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
55 #include "flac/assert.h"
56 #include "share/alloc.h"
57 #include "protected/stream_decoder.h"
58 #include "private/bitreader.h"
59 #include "private/bitmath.h"
60 #include "private/cpu.h"
61 #include "private/crc.h"
62 #include "private/fixed.h"
63 #include "private/format.h"
64 #include "private/lpc.h"
65 #include "private/md5.h"
66 #include "private/memory.h"
68 #ifdef TARGET_MSDOS /* @@@ [2G limit] */
76 #define max(a,b) ((a)>(b)?(a):(b))
78 /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
80 #define FLAC__U64L(x) x
82 #define FLAC__U64L(x) x##LLU
86 /* technically this should be in an "export.c" but this is convenient enough */
87 FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
96 /***********************************************************************
100 ***********************************************************************/
102 static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
104 /***********************************************************************
106 * Private class method prototypes
108 ***********************************************************************/
110 static void set_defaults_(FLAC__StreamDecoder *decoder);
111 static FILE *get_binary_stdin_(void);
112 static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
113 static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
114 static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
115 static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
116 static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
117 static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
118 static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
119 static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
120 static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
121 static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
122 static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
123 static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
124 static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
125 static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
126 static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
127 static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
128 static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
129 static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
130 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);
131 static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
132 static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
134 static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
135 static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
137 static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
138 static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
139 static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
141 static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
143 static FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
144 static FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
145 static FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
146 static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
147 static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
149 /***********************************************************************
153 ***********************************************************************/
155 typedef struct FLAC__StreamDecoderPrivate {
159 FLAC__StreamDecoderReadCallback read_callback;
160 FLAC__StreamDecoderSeekCallback seek_callback;
161 FLAC__StreamDecoderTellCallback tell_callback;
162 FLAC__StreamDecoderLengthCallback length_callback;
163 FLAC__StreamDecoderEofCallback eof_callback;
164 FLAC__StreamDecoderWriteCallback write_callback;
165 FLAC__StreamDecoderMetadataCallback metadata_callback;
166 FLAC__StreamDecoderErrorCallback error_callback;
167 /* generic 32-bit datapath: */
168 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[]);
169 /* generic 64-bit datapath: */
170 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[]);
171 /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
172 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[]);
173 /* 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: */
174 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[]);
175 FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
177 FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
178 FLAC__BitReader *input;
179 FLAC__int32 *output[FLAC__MAX_CHANNELS];
180 FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
181 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
182 unsigned output_capacity, output_channels;
183 FLAC__uint32 fixed_block_size, next_fixed_block_size;
184 FLAC__uint64 samples_decoded;
185 FLAC__bool has_stream_info, has_seek_table;
186 FLAC__StreamMetadata stream_info;
187 FLAC__StreamMetadata seek_table;
188 FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
189 FLAC__byte *metadata_filter_ids;
190 size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
192 FLAC__bool cached; /* true if there is a byte in lookahead */
193 FLAC__CPUInfo cpuinfo;
194 FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
195 FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
196 /* unaligned (original) pointers to allocated data */
197 FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
198 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 */
199 FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
200 FLAC__bool is_seeking;
201 FLAC__MD5Context md5context;
202 FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
203 /* (the rest of these are only used for seeking) */
204 FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
205 FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
206 FLAC__uint64 target_sample;
207 unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
209 FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
211 } FLAC__StreamDecoderPrivate;
213 /***********************************************************************
215 * Public static class data
217 ***********************************************************************/
219 FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
220 "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
221 "FLAC__STREAM_DECODER_READ_METADATA",
222 "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
223 "FLAC__STREAM_DECODER_READ_FRAME",
224 "FLAC__STREAM_DECODER_END_OF_STREAM",
225 "FLAC__STREAM_DECODER_OGG_ERROR",
226 "FLAC__STREAM_DECODER_SEEK_ERROR",
227 "FLAC__STREAM_DECODER_ABORTED",
228 "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
229 "FLAC__STREAM_DECODER_UNINITIALIZED"
232 FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
233 "FLAC__STREAM_DECODER_INIT_STATUS_OK",
234 "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
235 "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
236 "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
237 "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
238 "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
241 FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
242 "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
243 "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
244 "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
247 FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
248 "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
249 "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
250 "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
253 FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
254 "FLAC__STREAM_DECODER_TELL_STATUS_OK",
255 "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
256 "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
259 FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
260 "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
261 "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
262 "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
265 FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
266 "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
267 "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
270 FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
271 "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
272 "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
273 "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
274 "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
277 /***********************************************************************
279 * Class constructor/destructor
281 ***********************************************************************/
282 FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
284 FLAC__StreamDecoder *decoder;
287 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
289 decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
294 decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
295 if(decoder->protected_ == 0) {
300 decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
301 if(decoder->private_ == 0) {
302 free(decoder->protected_);
307 decoder->private_->input = FLAC__bitreader_new();
308 if(decoder->private_->input == 0) {
309 free(decoder->private_);
310 free(decoder->protected_);
315 decoder->private_->metadata_filter_ids_capacity = 16;
316 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
317 FLAC__bitreader_delete(decoder->private_->input);
318 free(decoder->private_);
319 free(decoder->protected_);
324 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
325 decoder->private_->output[i] = 0;
326 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
329 decoder->private_->output_capacity = 0;
330 decoder->private_->output_channels = 0;
331 decoder->private_->has_seek_table = false;
333 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
334 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
336 decoder->private_->file = 0;
338 set_defaults_(decoder);
340 decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
345 FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
349 FLAC__ASSERT(0 != decoder);
350 FLAC__ASSERT(0 != decoder->protected_);
351 FLAC__ASSERT(0 != decoder->private_);
352 FLAC__ASSERT(0 != decoder->private_->input);
354 (void)FLAC__stream_decoder_finish(decoder);
356 if(0 != decoder->private_->metadata_filter_ids)
357 free(decoder->private_->metadata_filter_ids);
359 FLAC__bitreader_delete(decoder->private_->input);
361 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
362 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
364 free(decoder->private_);
365 free(decoder->protected_);
369 /***********************************************************************
371 * Public class methods
373 ***********************************************************************/
375 static FLAC__StreamDecoderInitStatus init_stream_internal_(
376 FLAC__StreamDecoder *decoder,
377 FLAC__StreamDecoderReadCallback read_callback,
378 FLAC__StreamDecoderSeekCallback seek_callback,
379 FLAC__StreamDecoderTellCallback tell_callback,
380 FLAC__StreamDecoderLengthCallback length_callback,
381 FLAC__StreamDecoderEofCallback eof_callback,
382 FLAC__StreamDecoderWriteCallback write_callback,
383 FLAC__StreamDecoderMetadataCallback metadata_callback,
384 FLAC__StreamDecoderErrorCallback error_callback,
389 FLAC__ASSERT(0 != decoder);
391 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
392 return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
396 return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
400 0 == read_callback ||
401 0 == write_callback ||
402 0 == error_callback ||
403 (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
405 return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
408 decoder->private_->is_ogg = is_ogg;
409 if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
410 return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
414 * get the CPU info and set the function pointers
416 FLAC__cpu_info(&decoder->private_->cpuinfo);
417 /* first default to the non-asm routines */
418 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
419 decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
420 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
421 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
422 decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
423 /* now override with asm where appropriate */
425 if(decoder->private_->cpuinfo.use_asm) {
426 #ifdef FLAC__CPU_IA32
427 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
428 #ifdef FLAC__HAS_NASM
429 #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
430 if(decoder->private_->cpuinfo.data.ia32.bswap)
431 decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
433 if(decoder->private_->cpuinfo.data.ia32.mmx) {
434 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
435 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
436 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
439 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
440 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
441 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
444 #elif defined FLAC__CPU_PPC
445 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
446 if(decoder->private_->cpuinfo.data.ppc.altivec) {
447 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
448 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
454 /* from here on, errors are fatal */
456 if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
457 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
458 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
461 decoder->private_->read_callback = read_callback;
462 decoder->private_->seek_callback = seek_callback;
463 decoder->private_->tell_callback = tell_callback;
464 decoder->private_->length_callback = length_callback;
465 decoder->private_->eof_callback = eof_callback;
466 decoder->private_->write_callback = write_callback;
467 decoder->private_->metadata_callback = metadata_callback;
468 decoder->private_->error_callback = error_callback;
469 decoder->private_->client_data = client_data;
470 decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
471 decoder->private_->samples_decoded = 0;
472 decoder->private_->has_stream_info = false;
473 decoder->private_->cached = false;
475 decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
476 decoder->private_->is_seeking = false;
478 decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
479 if(!FLAC__stream_decoder_reset(decoder)) {
480 /* above call sets the state for us */
481 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
484 return FLAC__STREAM_DECODER_INIT_STATUS_OK;
487 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
488 FLAC__StreamDecoder *decoder,
489 FLAC__StreamDecoderReadCallback read_callback,
490 FLAC__StreamDecoderSeekCallback seek_callback,
491 FLAC__StreamDecoderTellCallback tell_callback,
492 FLAC__StreamDecoderLengthCallback length_callback,
493 FLAC__StreamDecoderEofCallback eof_callback,
494 FLAC__StreamDecoderWriteCallback write_callback,
495 FLAC__StreamDecoderMetadataCallback metadata_callback,
496 FLAC__StreamDecoderErrorCallback error_callback,
500 return init_stream_internal_(
515 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
516 FLAC__StreamDecoder *decoder,
517 FLAC__StreamDecoderReadCallback read_callback,
518 FLAC__StreamDecoderSeekCallback seek_callback,
519 FLAC__StreamDecoderTellCallback tell_callback,
520 FLAC__StreamDecoderLengthCallback length_callback,
521 FLAC__StreamDecoderEofCallback eof_callback,
522 FLAC__StreamDecoderWriteCallback write_callback,
523 FLAC__StreamDecoderMetadataCallback metadata_callback,
524 FLAC__StreamDecoderErrorCallback error_callback,
528 return init_stream_internal_(
543 static FLAC__StreamDecoderInitStatus init_FILE_internal_(
544 FLAC__StreamDecoder *decoder,
546 FLAC__StreamDecoderWriteCallback write_callback,
547 FLAC__StreamDecoderMetadataCallback metadata_callback,
548 FLAC__StreamDecoderErrorCallback error_callback,
553 FLAC__ASSERT(0 != decoder);
554 FLAC__ASSERT(0 != file);
556 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
557 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
559 if(0 == write_callback || 0 == error_callback)
560 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
563 * To make sure that our file does not go unclosed after an error, we
564 * must assign the FILE pointer before any further error can occur in
568 file = get_binary_stdin_(); /* just to be safe */
570 decoder->private_->file = file;
572 return init_stream_internal_(
575 decoder->private_->file == stdin? 0: file_seek_callback_,
576 decoder->private_->file == stdin? 0: file_tell_callback_,
577 decoder->private_->file == stdin? 0: file_length_callback_,
587 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
588 FLAC__StreamDecoder *decoder,
590 FLAC__StreamDecoderWriteCallback write_callback,
591 FLAC__StreamDecoderMetadataCallback metadata_callback,
592 FLAC__StreamDecoderErrorCallback error_callback,
596 return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
599 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
600 FLAC__StreamDecoder *decoder,
602 FLAC__StreamDecoderWriteCallback write_callback,
603 FLAC__StreamDecoderMetadataCallback metadata_callback,
604 FLAC__StreamDecoderErrorCallback error_callback,
608 return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
611 static FLAC__StreamDecoderInitStatus init_file_internal_(
612 FLAC__StreamDecoder *decoder,
613 const char *filename,
614 FLAC__StreamDecoderWriteCallback write_callback,
615 FLAC__StreamDecoderMetadataCallback metadata_callback,
616 FLAC__StreamDecoderErrorCallback error_callback,
623 FLAC__ASSERT(0 != decoder);
626 * To make sure that our file does not go unclosed after an error, we
627 * have to do the same entrance checks here that are later performed
628 * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
630 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
631 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
633 if(0 == write_callback || 0 == error_callback)
634 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
636 file = filename? fopen(filename, "rb") : stdin;
639 return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
641 return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
644 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
645 FLAC__StreamDecoder *decoder,
646 const char *filename,
647 FLAC__StreamDecoderWriteCallback write_callback,
648 FLAC__StreamDecoderMetadataCallback metadata_callback,
649 FLAC__StreamDecoderErrorCallback error_callback,
653 return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
656 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
657 FLAC__StreamDecoder *decoder,
658 const char *filename,
659 FLAC__StreamDecoderWriteCallback write_callback,
660 FLAC__StreamDecoderMetadataCallback metadata_callback,
661 FLAC__StreamDecoderErrorCallback error_callback,
665 return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
668 FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
670 FLAC__bool md5_failed = false;
673 FLAC__ASSERT(0 != decoder);
674 FLAC__ASSERT(0 != decoder->private_);
675 FLAC__ASSERT(0 != decoder->protected_);
677 if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
680 /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
681 * always call FLAC__MD5Final()
683 FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
685 if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
686 free(decoder->private_->seek_table.data.seek_table.points);
687 decoder->private_->seek_table.data.seek_table.points = 0;
688 decoder->private_->has_seek_table = false;
690 FLAC__bitreader_free(decoder->private_->input);
691 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
693 * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
694 * output arrays have a buffer of up to 3 zeroes in front
695 * (at negative indices) for alignment purposes; we use 4
696 * to keep the data well-aligned.
698 if(0 != decoder->private_->output[i]) {
699 free(decoder->private_->output[i]-4);
700 decoder->private_->output[i] = 0;
702 if(0 != decoder->private_->residual_unaligned[i]) {
703 free(decoder->private_->residual_unaligned[i]);
704 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
707 decoder->private_->output_capacity = 0;
708 decoder->private_->output_channels = 0;
711 if(decoder->private_->is_ogg)
712 FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
715 if(0 != decoder->private_->file) {
716 if(decoder->private_->file != stdin)
717 fclose(decoder->private_->file);
718 decoder->private_->file = 0;
721 if(decoder->private_->do_md5_checking) {
722 if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
725 decoder->private_->is_seeking = false;
727 set_defaults_(decoder);
729 decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
734 FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
736 FLAC__ASSERT(0 != decoder);
737 FLAC__ASSERT(0 != decoder->private_);
738 FLAC__ASSERT(0 != decoder->protected_);
739 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
742 /* can't check decoder->private_->is_ogg since that's not set until init time */
743 FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
751 FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
753 FLAC__ASSERT(0 != decoder);
754 FLAC__ASSERT(0 != decoder->protected_);
755 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
757 decoder->protected_->md5_checking = value;
761 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
763 FLAC__ASSERT(0 != decoder);
764 FLAC__ASSERT(0 != decoder->private_);
765 FLAC__ASSERT(0 != decoder->protected_);
766 FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
767 /* double protection */
768 if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
770 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
772 decoder->private_->metadata_filter[type] = true;
773 if(type == FLAC__METADATA_TYPE_APPLICATION)
774 decoder->private_->metadata_filter_ids_count = 0;
778 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
780 FLAC__ASSERT(0 != decoder);
781 FLAC__ASSERT(0 != decoder->private_);
782 FLAC__ASSERT(0 != decoder->protected_);
783 FLAC__ASSERT(0 != id);
784 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
787 if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
790 FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
792 if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
793 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))) {
794 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
797 decoder->private_->metadata_filter_ids_capacity *= 2;
800 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));
801 decoder->private_->metadata_filter_ids_count++;
806 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
809 FLAC__ASSERT(0 != decoder);
810 FLAC__ASSERT(0 != decoder->private_);
811 FLAC__ASSERT(0 != decoder->protected_);
812 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
814 for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
815 decoder->private_->metadata_filter[i] = true;
816 decoder->private_->metadata_filter_ids_count = 0;
820 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
822 FLAC__ASSERT(0 != decoder);
823 FLAC__ASSERT(0 != decoder->private_);
824 FLAC__ASSERT(0 != decoder->protected_);
825 FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
826 /* double protection */
827 if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
829 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
831 decoder->private_->metadata_filter[type] = false;
832 if(type == FLAC__METADATA_TYPE_APPLICATION)
833 decoder->private_->metadata_filter_ids_count = 0;
837 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
839 FLAC__ASSERT(0 != decoder);
840 FLAC__ASSERT(0 != decoder->private_);
841 FLAC__ASSERT(0 != decoder->protected_);
842 FLAC__ASSERT(0 != id);
843 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
846 if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
849 FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
851 if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
852 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))) {
853 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
856 decoder->private_->metadata_filter_ids_capacity *= 2;
859 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));
860 decoder->private_->metadata_filter_ids_count++;
865 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
867 FLAC__ASSERT(0 != decoder);
868 FLAC__ASSERT(0 != decoder->private_);
869 FLAC__ASSERT(0 != decoder->protected_);
870 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
872 memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
873 decoder->private_->metadata_filter_ids_count = 0;
877 FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
879 FLAC__ASSERT(0 != decoder);
880 FLAC__ASSERT(0 != decoder->protected_);
881 return decoder->protected_->state;
884 FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
886 return FLAC__StreamDecoderStateString[decoder->protected_->state];
889 FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
891 FLAC__ASSERT(0 != decoder);
892 FLAC__ASSERT(0 != decoder->protected_);
893 return decoder->protected_->md5_checking;
896 FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
898 FLAC__ASSERT(0 != decoder);
899 FLAC__ASSERT(0 != decoder->protected_);
900 return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
903 FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
905 FLAC__ASSERT(0 != decoder);
906 FLAC__ASSERT(0 != decoder->protected_);
907 return decoder->protected_->channels;
910 FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
912 FLAC__ASSERT(0 != decoder);
913 FLAC__ASSERT(0 != decoder->protected_);
914 return decoder->protected_->channel_assignment;
917 FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
919 FLAC__ASSERT(0 != decoder);
920 FLAC__ASSERT(0 != decoder->protected_);
921 return decoder->protected_->bits_per_sample;
924 FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
926 FLAC__ASSERT(0 != decoder);
927 FLAC__ASSERT(0 != decoder->protected_);
928 return decoder->protected_->sample_rate;
931 FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
933 FLAC__ASSERT(0 != decoder);
934 FLAC__ASSERT(0 != decoder->protected_);
935 return decoder->protected_->blocksize;
938 FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
940 FLAC__ASSERT(0 != decoder);
941 FLAC__ASSERT(0 != decoder->private_);
942 FLAC__ASSERT(0 != position);
945 if(decoder->private_->is_ogg)
948 if(0 == decoder->private_->tell_callback)
950 if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
952 /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
953 if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
955 FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
956 *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
960 FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
962 FLAC__ASSERT(0 != decoder);
963 FLAC__ASSERT(0 != decoder->private_);
964 FLAC__ASSERT(0 != decoder->protected_);
966 decoder->private_->samples_decoded = 0;
967 decoder->private_->do_md5_checking = false;
970 if(decoder->private_->is_ogg)
971 FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
974 if(!FLAC__bitreader_clear(decoder->private_->input)) {
975 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
978 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
983 FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
985 FLAC__ASSERT(0 != decoder);
986 FLAC__ASSERT(0 != decoder->private_);
987 FLAC__ASSERT(0 != decoder->protected_);
989 if(!FLAC__stream_decoder_flush(decoder)) {
990 /* above call sets the state for us */
995 /*@@@ could go in !internal_reset_hack block below */
996 if(decoder->private_->is_ogg)
997 FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
1000 /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
1001 * (internal_reset_hack) don't try to rewind since we are already at
1002 * the beginning of the stream and don't want to fail if the input is
1005 if(!decoder->private_->internal_reset_hack) {
1006 if(decoder->private_->file == stdin)
1007 return false; /* can't rewind stdin, reset fails */
1008 if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
1009 return false; /* seekable and seek fails, reset fails */
1012 decoder->private_->internal_reset_hack = false;
1014 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
1016 decoder->private_->has_stream_info = false;
1017 if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
1018 free(decoder->private_->seek_table.data.seek_table.points);
1019 decoder->private_->seek_table.data.seek_table.points = 0;
1020 decoder->private_->has_seek_table = false;
1022 decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
1024 * This goes in reset() and not flush() because according to the spec, a
1025 * fixed-blocksize stream must stay that way through the whole stream.
1027 decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
1029 /* We initialize the FLAC__MD5Context even though we may never use it. This
1030 * is because md5 checking may be turned on to start and then turned off if
1031 * a seek occurs. So we init the context here and finalize it in
1032 * FLAC__stream_decoder_finish() to make sure things are always cleaned up
1035 FLAC__MD5Init(&decoder->private_->md5context);
1037 decoder->private_->first_frame_offset = 0;
1038 decoder->private_->unparseable_frame_count = 0;
1043 FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
1045 FLAC__bool got_a_frame;
1046 FLAC__ASSERT(0 != decoder);
1047 FLAC__ASSERT(0 != decoder->protected_);
1050 switch(decoder->protected_->state) {
1051 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1052 if(!find_metadata_(decoder))
1053 return false; /* above function sets the status for us */
1055 case FLAC__STREAM_DECODER_READ_METADATA:
1056 if(!read_metadata_(decoder))
1057 return false; /* above function sets the status for us */
1060 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1061 if(!frame_sync_(decoder))
1062 return true; /* above function sets the status for us */
1064 case FLAC__STREAM_DECODER_READ_FRAME:
1065 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
1066 return false; /* above function sets the status for us */
1068 return true; /* above function sets the status for us */
1070 case FLAC__STREAM_DECODER_END_OF_STREAM:
1071 case FLAC__STREAM_DECODER_ABORTED:
1080 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
1082 FLAC__ASSERT(0 != decoder);
1083 FLAC__ASSERT(0 != decoder->protected_);
1086 switch(decoder->protected_->state) {
1087 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1088 if(!find_metadata_(decoder))
1089 return false; /* above function sets the status for us */
1091 case FLAC__STREAM_DECODER_READ_METADATA:
1092 if(!read_metadata_(decoder))
1093 return false; /* above function sets the status for us */
1095 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1096 case FLAC__STREAM_DECODER_READ_FRAME:
1097 case FLAC__STREAM_DECODER_END_OF_STREAM:
1098 case FLAC__STREAM_DECODER_ABORTED:
1107 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
1110 FLAC__ASSERT(0 != decoder);
1111 FLAC__ASSERT(0 != decoder->protected_);
1114 switch(decoder->protected_->state) {
1115 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1116 if(!find_metadata_(decoder))
1117 return false; /* above function sets the status for us */
1119 case FLAC__STREAM_DECODER_READ_METADATA:
1120 if(!read_metadata_(decoder))
1121 return false; /* above function sets the status for us */
1123 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1124 if(!frame_sync_(decoder))
1125 return true; /* above function sets the status for us */
1127 case FLAC__STREAM_DECODER_READ_FRAME:
1128 if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
1129 return false; /* above function sets the status for us */
1131 case FLAC__STREAM_DECODER_END_OF_STREAM:
1132 case FLAC__STREAM_DECODER_ABORTED:
1141 FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
1143 FLAC__bool got_a_frame;
1144 FLAC__ASSERT(0 != decoder);
1145 FLAC__ASSERT(0 != decoder->protected_);
1148 switch(decoder->protected_->state) {
1149 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1150 case FLAC__STREAM_DECODER_READ_METADATA:
1151 return false; /* above function sets the status for us */
1152 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1153 if(!frame_sync_(decoder))
1154 return true; /* above function sets the status for us */
1156 case FLAC__STREAM_DECODER_READ_FRAME:
1157 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
1158 return false; /* above function sets the status for us */
1160 return true; /* above function sets the status for us */
1162 case FLAC__STREAM_DECODER_END_OF_STREAM:
1163 case FLAC__STREAM_DECODER_ABORTED:
1172 FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
1174 FLAC__uint64 length;
1176 FLAC__ASSERT(0 != decoder);
1179 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
1180 decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
1181 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
1182 decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
1183 decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
1187 if(0 == decoder->private_->seek_callback)
1190 FLAC__ASSERT(decoder->private_->seek_callback);
1191 FLAC__ASSERT(decoder->private_->tell_callback);
1192 FLAC__ASSERT(decoder->private_->length_callback);
1193 FLAC__ASSERT(decoder->private_->eof_callback);
1195 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
1198 decoder->private_->is_seeking = true;
1200 /* turn off md5 checking if a seek is attempted */
1201 decoder->private_->do_md5_checking = false;
1203 /* 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) */
1204 if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
1205 decoder->private_->is_seeking = false;
1209 /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
1211 decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
1212 decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
1214 if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
1215 /* above call sets the state for us */
1216 decoder->private_->is_seeking = false;
1219 /* check this again in case we didn't know total_samples the first time */
1220 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
1221 decoder->private_->is_seeking = false;
1227 const FLAC__bool ok =
1229 decoder->private_->is_ogg?
1230 seek_to_absolute_sample_ogg_(decoder, length, sample) :
1232 seek_to_absolute_sample_(decoder, length, sample)
1234 decoder->private_->is_seeking = false;
1239 /***********************************************************************
1241 * Protected class methods
1243 ***********************************************************************/
1245 unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
1247 FLAC__ASSERT(0 != decoder);
1248 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1249 FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
1250 return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
1253 /***********************************************************************
1255 * Private class methods
1257 ***********************************************************************/
1259 void set_defaults_(FLAC__StreamDecoder *decoder)
1262 decoder->private_->is_ogg = false;
1264 decoder->private_->read_callback = 0;
1265 decoder->private_->seek_callback = 0;
1266 decoder->private_->tell_callback = 0;
1267 decoder->private_->length_callback = 0;
1268 decoder->private_->eof_callback = 0;
1269 decoder->private_->write_callback = 0;
1270 decoder->private_->metadata_callback = 0;
1271 decoder->private_->error_callback = 0;
1272 decoder->private_->client_data = 0;
1274 memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
1275 decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
1276 decoder->private_->metadata_filter_ids_count = 0;
1278 decoder->protected_->md5_checking = false;
1281 FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
1286 * This will forcibly set stdin to binary mode (for OSes that require it)
1288 FILE *get_binary_stdin_(void)
1290 /* if something breaks here it is probably due to the presence or
1291 * absence of an underscore before the identifiers 'setmode',
1292 * 'fileno', and/or 'O_BINARY'; check your system header files.
1294 #if defined _MSC_VER || defined __MINGW32__
1295 _setmode(_fileno(stdin), _O_BINARY);
1296 #elif defined __CYGWIN__
1297 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
1298 setmode(_fileno(stdin), _O_BINARY);
1299 #elif defined __EMX__
1300 setmode(fileno(stdin), O_BINARY);
1306 FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
1311 if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
1314 /* simply using realloc() is not practical because the number of channels may change mid-stream */
1316 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
1317 if(0 != decoder->private_->output[i]) {
1318 free(decoder->private_->output[i]-4);
1319 decoder->private_->output[i] = 0;
1321 if(0 != decoder->private_->residual_unaligned[i]) {
1322 free(decoder->private_->residual_unaligned[i]);
1323 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
1327 for(i = 0; i < channels; i++) {
1329 * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
1330 * output arrays have a buffer of up to 3 zeroes in front
1331 * (at negative indices) for alignment purposes; we use 4
1332 * to keep the data well-aligned.
1334 tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
1336 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1339 memset(tmp, 0, sizeof(FLAC__int32)*4);
1340 decoder->private_->output[i] = tmp + 4;
1343 * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
1345 if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
1346 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1351 decoder->private_->output_capacity = size;
1352 decoder->private_->output_channels = channels;
1357 FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
1361 FLAC__ASSERT(0 != decoder);
1362 FLAC__ASSERT(0 != decoder->private_);
1364 for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
1365 if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
1371 FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
1375 FLAC__bool first = true;
1377 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1379 for(i = id = 0; i < 4; ) {
1380 if(decoder->private_->cached) {
1381 x = (FLAC__uint32)decoder->private_->lookahead;
1382 decoder->private_->cached = false;
1385 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1386 return false; /* read_callback_ sets the state for us */
1388 if(x == FLAC__STREAM_SYNC_STRING[i]) {
1394 if(x == ID3V2_TAG_[id]) {
1398 if(!skip_id3v2_tag_(decoder))
1399 return false; /* skip_id3v2_tag_ sets the state for us */
1404 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1405 decoder->private_->header_warmup[0] = (FLAC__byte)x;
1406 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1407 return false; /* read_callback_ sets the state for us */
1409 /* 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 */
1410 /* else we have to check if the second byte is the end of a sync code */
1411 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1412 decoder->private_->lookahead = (FLAC__byte)x;
1413 decoder->private_->cached = true;
1415 else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1416 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1417 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1423 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1428 decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
1432 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
1435 FLAC__uint32 i, x, type, length;
1437 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1439 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
1440 return false; /* read_callback_ sets the state for us */
1441 is_last = x? true : false;
1443 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
1444 return false; /* read_callback_ sets the state for us */
1446 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
1447 return false; /* read_callback_ sets the state for us */
1449 if(type == FLAC__METADATA_TYPE_STREAMINFO) {
1450 if(!read_metadata_streaminfo_(decoder, is_last, length))
1453 decoder->private_->has_stream_info = true;
1454 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))
1455 decoder->private_->do_md5_checking = false;
1456 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
1457 decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
1459 else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
1460 if(!read_metadata_seektable_(decoder, is_last, length))
1463 decoder->private_->has_seek_table = true;
1464 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
1465 decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
1468 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
1469 unsigned real_length = length;
1470 FLAC__StreamMetadata block;
1472 block.is_last = is_last;
1473 block.type = (FLAC__MetadataType)type;
1474 block.length = length;
1476 if(type == FLAC__METADATA_TYPE_APPLICATION) {
1477 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
1478 return false; /* read_callback_ sets the state for us */
1480 if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
1481 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
1485 real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
1487 if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
1492 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
1493 return false; /* read_callback_ sets the state for us */
1497 case FLAC__METADATA_TYPE_PADDING:
1498 /* skip the padding bytes */
1499 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
1500 return false; /* read_callback_ sets the state for us */
1502 case FLAC__METADATA_TYPE_APPLICATION:
1503 /* remember, we read the ID already */
1504 if(real_length > 0) {
1505 if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
1506 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1509 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
1510 return false; /* read_callback_ sets the state for us */
1513 block.data.application.data = 0;
1515 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1516 if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
1519 case FLAC__METADATA_TYPE_CUESHEET:
1520 if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
1523 case FLAC__METADATA_TYPE_PICTURE:
1524 if(!read_metadata_picture_(decoder, &block.data.picture))
1527 case FLAC__METADATA_TYPE_STREAMINFO:
1528 case FLAC__METADATA_TYPE_SEEKTABLE:
1532 if(real_length > 0) {
1533 if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
1534 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1537 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
1538 return false; /* read_callback_ sets the state for us */
1541 block.data.unknown.data = 0;
1544 if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
1545 decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1547 /* now we have to free any malloc()ed data in the block */
1549 case FLAC__METADATA_TYPE_PADDING:
1551 case FLAC__METADATA_TYPE_APPLICATION:
1552 if(0 != block.data.application.data)
1553 free(block.data.application.data);
1555 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1556 if(0 != block.data.vorbis_comment.vendor_string.entry)
1557 free(block.data.vorbis_comment.vendor_string.entry);
1558 if(block.data.vorbis_comment.num_comments > 0)
1559 for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
1560 if(0 != block.data.vorbis_comment.comments[i].entry)
1561 free(block.data.vorbis_comment.comments[i].entry);
1562 if(0 != block.data.vorbis_comment.comments)
1563 free(block.data.vorbis_comment.comments);
1565 case FLAC__METADATA_TYPE_CUESHEET:
1566 if(block.data.cue_sheet.num_tracks > 0)
1567 for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
1568 if(0 != block.data.cue_sheet.tracks[i].indices)
1569 free(block.data.cue_sheet.tracks[i].indices);
1570 if(0 != block.data.cue_sheet.tracks)
1571 free(block.data.cue_sheet.tracks);
1573 case FLAC__METADATA_TYPE_PICTURE:
1574 if(0 != block.data.picture.mime_type)
1575 free(block.data.picture.mime_type);
1576 if(0 != block.data.picture.description)
1577 free(block.data.picture.description);
1578 if(0 != block.data.picture.data)
1579 free(block.data.picture.data);
1581 case FLAC__METADATA_TYPE_STREAMINFO:
1582 case FLAC__METADATA_TYPE_SEEKTABLE:
1585 if(0 != block.data.unknown.data)
1586 free(block.data.unknown.data);
1593 /* if this fails, it's OK, it's just a hint for the seek routine */
1594 if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
1595 decoder->private_->first_frame_offset = 0;
1596 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1602 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1605 unsigned bits, used_bits = 0;
1607 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1609 decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
1610 decoder->private_->stream_info.is_last = is_last;
1611 decoder->private_->stream_info.length = length;
1613 bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1614 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
1615 return false; /* read_callback_ sets the state for us */
1616 decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1619 bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1620 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
1621 return false; /* read_callback_ sets the state for us */
1622 decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1625 bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1626 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
1627 return false; /* read_callback_ sets the state for us */
1628 decoder->private_->stream_info.data.stream_info.min_framesize = x;
1631 bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1632 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
1633 return false; /* read_callback_ sets the state for us */
1634 decoder->private_->stream_info.data.stream_info.max_framesize = x;
1637 bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1638 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
1639 return false; /* read_callback_ sets the state for us */
1640 decoder->private_->stream_info.data.stream_info.sample_rate = x;
1643 bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1644 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
1645 return false; /* read_callback_ sets the state for us */
1646 decoder->private_->stream_info.data.stream_info.channels = x+1;
1649 bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1650 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
1651 return false; /* read_callback_ sets the state for us */
1652 decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1655 bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1656 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))
1657 return false; /* read_callback_ sets the state for us */
1660 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
1661 return false; /* read_callback_ sets the state for us */
1664 /* skip the rest of the block */
1665 FLAC__ASSERT(used_bits % 8 == 0);
1666 length -= (used_bits / 8);
1667 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
1668 return false; /* read_callback_ sets the state for us */
1673 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1678 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1680 decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1681 decoder->private_->seek_table.is_last = is_last;
1682 decoder->private_->seek_table.length = length;
1684 decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1686 /* use realloc since we may pass through here several times (e.g. after seeking) */
1687 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)))) {
1688 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1691 for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1692 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
1693 return false; /* read_callback_ sets the state for us */
1694 decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1696 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
1697 return false; /* read_callback_ sets the state for us */
1698 decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1700 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
1701 return false; /* read_callback_ sets the state for us */
1702 decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1704 length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1705 /* if there is a partial point left, skip over it */
1707 /*@@@ do a send_error_to_client_() here? there's an argument for either way */
1708 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
1709 return false; /* read_callback_ sets the state for us */
1715 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1719 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1721 /* read vendor string */
1722 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1723 if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
1724 return false; /* read_callback_ sets the state for us */
1725 if(obj->vendor_string.length > 0) {
1726 if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
1727 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1730 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
1731 return false; /* read_callback_ sets the state for us */
1732 obj->vendor_string.entry[obj->vendor_string.length] = '\0';
1735 obj->vendor_string.entry = 0;
1737 /* read num comments */
1738 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1739 if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
1740 return false; /* read_callback_ sets the state for us */
1743 if(obj->num_comments > 0) {
1744 if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1745 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1748 for(i = 0; i < obj->num_comments; i++) {
1749 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1750 if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
1751 return false; /* read_callback_ sets the state for us */
1752 if(obj->comments[i].length > 0) {
1753 if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
1754 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1757 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
1758 return false; /* read_callback_ sets the state for us */
1759 obj->comments[i].entry[obj->comments[i].length] = '\0';
1762 obj->comments[i].entry = 0;
1772 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1774 FLAC__uint32 i, j, x;
1776 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1778 memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1780 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1781 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))
1782 return false; /* read_callback_ sets the state for us */
1784 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
1785 return false; /* read_callback_ sets the state for us */
1787 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
1788 return false; /* read_callback_ sets the state for us */
1789 obj->is_cd = x? true : false;
1791 if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
1792 return false; /* read_callback_ sets the state for us */
1794 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
1795 return false; /* read_callback_ sets the state for us */
1796 obj->num_tracks = x;
1798 if(obj->num_tracks > 0) {
1799 if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1800 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1803 for(i = 0; i < obj->num_tracks; i++) {
1804 FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1805 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
1806 return false; /* read_callback_ sets the state for us */
1808 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
1809 return false; /* read_callback_ sets the state for us */
1810 track->number = (FLAC__byte)x;
1812 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1813 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
1814 return false; /* read_callback_ sets the state for us */
1816 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
1817 return false; /* read_callback_ sets the state for us */
1820 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
1821 return false; /* read_callback_ sets the state for us */
1822 track->pre_emphasis = x;
1824 if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
1825 return false; /* read_callback_ sets the state for us */
1827 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
1828 return false; /* read_callback_ sets the state for us */
1829 track->num_indices = (FLAC__byte)x;
1831 if(track->num_indices > 0) {
1832 if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1833 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1836 for(j = 0; j < track->num_indices; j++) {
1837 FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1838 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
1839 return false; /* read_callback_ sets the state for us */
1841 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
1842 return false; /* read_callback_ sets the state for us */
1843 index->number = (FLAC__byte)x;
1845 if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
1846 return false; /* read_callback_ sets the state for us */
1855 FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
1859 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1862 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
1863 return false; /* read_callback_ sets the state for us */
1866 /* read MIME type */
1867 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
1868 return false; /* read_callback_ sets the state for us */
1869 if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
1870 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1874 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
1875 return false; /* read_callback_ sets the state for us */
1877 obj->mime_type[x] = '\0';
1879 /* read description */
1880 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
1881 return false; /* read_callback_ sets the state for us */
1882 if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
1883 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1887 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
1888 return false; /* read_callback_ sets the state for us */
1890 obj->description[x] = '\0';
1893 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
1894 return false; /* read_callback_ sets the state for us */
1897 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
1898 return false; /* read_callback_ sets the state for us */
1901 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
1902 return false; /* read_callback_ sets the state for us */
1905 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
1906 return false; /* read_callback_ sets the state for us */
1909 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
1910 return false; /* read_callback_ sets the state for us */
1911 if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
1912 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1915 if(obj->data_length > 0) {
1916 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
1917 return false; /* read_callback_ sets the state for us */
1923 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1928 /* skip the version and flags bytes */
1929 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
1930 return false; /* read_callback_ sets the state for us */
1931 /* get the size (in bytes) to skip */
1933 for(i = 0; i < 4; i++) {
1934 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1935 return false; /* read_callback_ sets the state for us */
1939 /* skip the rest of the tag */
1940 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
1941 return false; /* read_callback_ sets the state for us */
1945 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1948 FLAC__bool first = true;
1950 /* If we know the total number of samples in the stream, stop if we've read that many. */
1951 /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1952 if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
1953 if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
1954 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1959 /* make sure we're byte aligned */
1960 if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
1961 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
1962 return false; /* read_callback_ sets the state for us */
1966 if(decoder->private_->cached) {
1967 x = (FLAC__uint32)decoder->private_->lookahead;
1968 decoder->private_->cached = false;
1971 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1972 return false; /* read_callback_ sets the state for us */
1974 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1975 decoder->private_->header_warmup[0] = (FLAC__byte)x;
1976 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1977 return false; /* read_callback_ sets the state for us */
1979 /* 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 */
1980 /* else we have to check if the second byte is the end of a sync code */
1981 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1982 decoder->private_->lookahead = (FLAC__byte)x;
1983 decoder->private_->cached = true;
1985 else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1986 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1987 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1992 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2000 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
2004 FLAC__int32 mid, side;
2005 unsigned frame_crc; /* the one we calculate from the input stream */
2008 *got_a_frame = false;
2012 frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
2013 frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
2014 FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
2016 if(!read_frame_header_(decoder))
2018 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
2020 if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
2022 for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2024 * first figure the correct bits-per-sample of the subframe
2026 unsigned bps = decoder->private_->frame.header.bits_per_sample;
2027 switch(decoder->private_->frame.header.channel_assignment) {
2028 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2029 /* no adjustment needed */
2031 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2032 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2036 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2037 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2041 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2042 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2052 if(!read_subframe_(decoder, channel, bps, do_full_decode))
2054 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2057 if(!read_zero_padding_(decoder))
2059 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) */
2063 * Read the frame CRC-16 from the footer and check
2065 frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
2066 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
2067 return false; /* read_callback_ sets the state for us */
2068 if(frame_crc == x) {
2069 if(do_full_decode) {
2070 /* Undo any special channel coding */
2071 switch(decoder->private_->frame.header.channel_assignment) {
2072 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2075 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2076 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2077 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2078 decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
2080 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2081 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2082 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2083 decoder->private_->output[0][i] += decoder->private_->output[1][i];
2085 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2086 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2087 for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2089 mid = decoder->private_->output[0][i];
2090 side = decoder->private_->output[1][i];
2092 mid |= (side & 1); /* i.e. if 'side' is odd... */
2093 decoder->private_->output[0][i] = (mid + side) >> 1;
2094 decoder->private_->output[1][i] = (mid - side) >> 1;
2096 /* OPT: without 'side' temp variable */
2097 mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
2098 decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
2099 decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
2110 /* Bad frame, emit error and zero the output signal */
2111 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
2112 if(do_full_decode) {
2113 for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2114 memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2119 *got_a_frame = true;
2121 /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
2122 if(decoder->private_->next_fixed_block_size)
2123 decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
2125 /* put the latest values into the public section of the decoder instance */
2126 decoder->protected_->channels = decoder->private_->frame.header.channels;
2127 decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
2128 decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
2129 decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
2130 decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
2132 FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2133 decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
2136 if(do_full_decode) {
2137 if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
2141 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2145 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
2149 unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
2150 FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
2151 unsigned raw_header_len;
2152 FLAC__bool is_unparseable = false;
2154 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
2156 /* init the raw header with the saved bits from synchronization */
2157 raw_header[0] = decoder->private_->header_warmup[0];
2158 raw_header[1] = decoder->private_->header_warmup[1];
2161 /* check to make sure that reserved bit is 0 */
2162 if(raw_header[1] & 0x02) /* MAGIC NUMBER */
2163 is_unparseable = true;
2166 * Note that along the way as we read the header, we look for a sync
2167 * code inside. If we find one it would indicate that our original
2168 * sync was bad since there cannot be a sync code in a valid header.
2170 * Three kinds of things can go wrong when reading the frame header:
2171 * 1) We may have sync'ed incorrectly and not landed on a frame header.
2172 * If we don't find a sync code, it can end up looking like we read
2173 * a valid but unparseable header, until getting to the frame header
2174 * CRC. Even then we could get a false positive on the CRC.
2175 * 2) We may have sync'ed correctly but on an unparseable frame (from a
2177 * 3) We may be on a damaged frame which appears valid but unparseable.
2179 * For all these reasons, we try and read a complete frame header as
2180 * long as it seems valid, even if unparseable, up until the frame
2185 * read in the raw header as bytes so we can CRC it, and parse it on the way
2187 for(i = 0; i < 2; i++) {
2188 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2189 return false; /* read_callback_ sets the state for us */
2190 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
2191 /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
2192 decoder->private_->lookahead = (FLAC__byte)x;
2193 decoder->private_->cached = true;
2194 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2195 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2198 raw_header[raw_header_len++] = (FLAC__byte)x;
2201 switch(x = raw_header[2] >> 4) {
2203 is_unparseable = true;
2206 decoder->private_->frame.header.blocksize = 192;
2212 decoder->private_->frame.header.blocksize = 576 << (x-2);
2226 decoder->private_->frame.header.blocksize = 256 << (x-8);
2233 switch(x = raw_header[2] & 0x0f) {
2235 if(decoder->private_->has_stream_info)
2236 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
2238 is_unparseable = true;
2241 decoder->private_->frame.header.sample_rate = 88200;
2244 decoder->private_->frame.header.sample_rate = 176400;
2247 decoder->private_->frame.header.sample_rate = 192000;
2250 decoder->private_->frame.header.sample_rate = 8000;
2253 decoder->private_->frame.header.sample_rate = 16000;
2256 decoder->private_->frame.header.sample_rate = 22050;
2259 decoder->private_->frame.header.sample_rate = 24000;
2262 decoder->private_->frame.header.sample_rate = 32000;
2265 decoder->private_->frame.header.sample_rate = 44100;
2268 decoder->private_->frame.header.sample_rate = 48000;
2271 decoder->private_->frame.header.sample_rate = 96000;
2276 sample_rate_hint = x;
2279 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2280 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2286 x = (unsigned)(raw_header[3] >> 4);
2288 decoder->private_->frame.header.channels = 2;
2291 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2294 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2297 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2300 is_unparseable = true;
2305 decoder->private_->frame.header.channels = (unsigned)x + 1;
2306 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2309 switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2311 if(decoder->private_->has_stream_info)
2312 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2314 is_unparseable = true;
2317 decoder->private_->frame.header.bits_per_sample = 8;
2320 decoder->private_->frame.header.bits_per_sample = 12;
2323 decoder->private_->frame.header.bits_per_sample = 16;
2326 decoder->private_->frame.header.bits_per_sample = 20;
2329 decoder->private_->frame.header.bits_per_sample = 24;
2333 is_unparseable = true;
2340 /* check to make sure that reserved bit is 0 */
2341 if(raw_header[3] & 0x01) /* MAGIC NUMBER */
2342 is_unparseable = true;
2344 /* read the frame's starting sample number (or frame number as the case may be) */
2346 raw_header[1] & 0x01 ||
2347 /*@@@ 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 */
2348 (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
2349 ) { /* variable blocksize */
2350 if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
2351 return false; /* read_callback_ sets the state for us */
2352 if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
2353 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2354 decoder->private_->cached = true;
2355 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2356 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2359 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2360 decoder->private_->frame.header.number.sample_number = xx;
2362 else { /* fixed blocksize */
2363 if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
2364 return false; /* read_callback_ sets the state for us */
2365 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
2366 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2367 decoder->private_->cached = true;
2368 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2369 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2372 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2373 decoder->private_->frame.header.number.frame_number = x;
2376 if(blocksize_hint) {
2377 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2378 return false; /* read_callback_ sets the state for us */
2379 raw_header[raw_header_len++] = (FLAC__byte)x;
2380 if(blocksize_hint == 7) {
2382 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2383 return false; /* read_callback_ sets the state for us */
2384 raw_header[raw_header_len++] = (FLAC__byte)_x;
2387 decoder->private_->frame.header.blocksize = x+1;
2390 if(sample_rate_hint) {
2391 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2392 return false; /* read_callback_ sets the state for us */
2393 raw_header[raw_header_len++] = (FLAC__byte)x;
2394 if(sample_rate_hint != 12) {
2396 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2397 return false; /* read_callback_ sets the state for us */
2398 raw_header[raw_header_len++] = (FLAC__byte)_x;
2401 if(sample_rate_hint == 12)
2402 decoder->private_->frame.header.sample_rate = x*1000;
2403 else if(sample_rate_hint == 13)
2404 decoder->private_->frame.header.sample_rate = x;
2406 decoder->private_->frame.header.sample_rate = x*10;
2409 /* read the CRC-8 byte */
2410 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2411 return false; /* read_callback_ sets the state for us */
2412 crc8 = (FLAC__byte)x;
2414 if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
2415 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2416 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2420 /* calculate the sample number from the frame number if needed */
2421 decoder->private_->next_fixed_block_size = 0;
2422 if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
2423 x = decoder->private_->frame.header.number.frame_number;
2424 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2425 if(decoder->private_->fixed_block_size)
2426 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
2427 else if(decoder->private_->has_stream_info) {
2428 if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
2429 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
2430 decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
2433 is_unparseable = true;
2436 decoder->private_->frame.header.number.sample_number = 0;
2437 decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
2440 /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
2441 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
2445 if(is_unparseable) {
2446 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2447 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2454 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2457 FLAC__bool wasted_bits;
2460 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
2461 return false; /* read_callback_ sets the state for us */
2463 wasted_bits = (x & 1);
2468 if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
2469 return false; /* read_callback_ sets the state for us */
2470 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
2471 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
2474 decoder->private_->frame.subframes[channel].wasted_bits = 0;
2477 * Lots of magic numbers here
2480 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2481 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2485 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2489 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2493 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2494 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2498 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2500 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2504 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2505 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2509 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2511 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2515 if(wasted_bits && do_full_decode) {
2516 x = decoder->private_->frame.subframes[channel].wasted_bits;
2517 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2518 decoder->private_->output[channel][i] <<= x;
2524 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2526 FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2529 FLAC__int32 *output = decoder->private_->output[channel];
2531 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2533 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2534 return false; /* read_callback_ sets the state for us */
2536 subframe->value = x;
2538 /* decode the subframe */
2539 if(do_full_decode) {
2540 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2547 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2549 FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2554 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2556 subframe->residual = decoder->private_->residual[channel];
2557 subframe->order = order;
2559 /* read warm-up samples */
2560 for(u = 0; u < order; u++) {
2561 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2562 return false; /* read_callback_ sets the state for us */
2563 subframe->warmup[u] = i32;
2566 /* read entropy coding method info */
2567 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2568 return false; /* read_callback_ sets the state for us */
2569 subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2570 switch(subframe->entropy_coding_method.type) {
2571 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2572 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2573 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2574 return false; /* read_callback_ sets the state for us */
2575 subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2576 subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2579 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2580 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2585 switch(subframe->entropy_coding_method.type) {
2586 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2587 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2588 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))
2595 /* decode the subframe */
2596 if(do_full_decode) {
2597 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2598 FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
2604 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2606 FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2611 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2613 subframe->residual = decoder->private_->residual[channel];
2614 subframe->order = order;
2616 /* read warm-up samples */
2617 for(u = 0; u < order; u++) {
2618 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2619 return false; /* read_callback_ sets the state for us */
2620 subframe->warmup[u] = i32;
2623 /* read qlp coeff precision */
2624 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
2625 return false; /* read_callback_ sets the state for us */
2626 if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
2627 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2628 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2631 subframe->qlp_coeff_precision = u32+1;
2633 /* read qlp shift */
2634 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
2635 return false; /* read_callback_ sets the state for us */
2636 subframe->quantization_level = i32;
2638 /* read quantized lp coefficiencts */
2639 for(u = 0; u < order; u++) {
2640 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
2641 return false; /* read_callback_ sets the state for us */
2642 subframe->qlp_coeff[u] = i32;
2645 /* read entropy coding method info */
2646 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2647 return false; /* read_callback_ sets the state for us */
2648 subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2649 switch(subframe->entropy_coding_method.type) {
2650 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2651 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2652 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2653 return false; /* read_callback_ sets the state for us */
2654 subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2655 subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2658 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2659 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2664 switch(subframe->entropy_coding_method.type) {
2665 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2666 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2667 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))
2674 /* decode the subframe */
2675 if(do_full_decode) {
2676 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2677 /*@@@@@@ technically not pessimistic enough, should be more like
2678 if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
2680 if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2681 if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2683 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);
2685 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);
2688 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);
2690 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);
2696 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2698 FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2699 FLAC__int32 x, *residual = decoder->private_->residual[channel];
2702 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2704 subframe->data = residual;
2706 for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2707 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2708 return false; /* read_callback_ sets the state for us */
2712 /* decode the subframe */
2714 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2719 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)
2721 FLAC__uint32 rice_parameter;
2723 unsigned partition, sample, u;
2724 const unsigned partitions = 1u << partition_order;
2725 const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2726 const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
2727 const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
2730 if(partition_order == 0) {
2731 if(decoder->private_->frame.header.blocksize < predictor_order) {
2732 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2733 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2738 if(partition_samples < predictor_order) {
2739 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2740 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2745 if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2746 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2751 for(partition = 0; partition < partitions; partition++) {
2752 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
2753 return false; /* read_callback_ sets the state for us */
2754 partitioned_rice_contents->parameters[partition] = rice_parameter;
2755 if(rice_parameter < pesc) {
2756 partitioned_rice_contents->raw_bits[partition] = 0;
2757 u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2758 if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter))
2759 return false; /* read_callback_ sets the state for us */
2763 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
2764 return false; /* read_callback_ sets the state for us */
2765 partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2766 for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2767 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i, rice_parameter))
2768 return false; /* read_callback_ sets the state for us */
2769 residual[sample] = i;
2777 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2779 if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
2780 FLAC__uint32 zero = 0;
2781 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
2782 return false; /* read_callback_ sets the state for us */
2784 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2785 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2791 FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
2793 FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2797 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2798 !decoder->private_->is_ogg &&
2800 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2803 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2806 else if(*bytes > 0) {
2807 /* While seeking, it is possible for our seek to land in the
2808 * middle of audio data that looks exactly like a frame header
2809 * from a future version of an encoder. When that happens, our
2810 * error callback will get an
2811 * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
2812 * unparseable_frame_count. But there is a remote possibility
2813 * that it is properly synced at such a "future-codec frame",
2814 * so to make sure, we wait to see many "unparseable" errors in
2815 * a row before bailing out.
2817 if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2818 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2822 const FLAC__StreamDecoderReadStatus status =
2824 decoder->private_->is_ogg?
2825 read_callback_ogg_aspect_(decoder, buffer, bytes) :
2827 decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
2829 if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
2830 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2833 else if(*bytes == 0) {
2835 status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
2838 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2839 !decoder->private_->is_ogg &&
2841 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2844 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2855 /* abort to avoid a deadlock */
2856 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2859 /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
2860 * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
2861 * and at the same time hit the end of the stream (for example, seeking
2862 * to a point that is after the beginning of the last Ogg page). There
2863 * is no way to report an Ogg sync loss through the callbacks (see note
2864 * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
2865 * So to keep the decoder from stopping at this point we gate the call
2866 * to the eof_callback and let the Ogg decoder aspect set the
2867 * end-of-stream state when it is needed.
2872 FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
2874 switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
2875 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
2876 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2877 /* we don't really have a way to handle lost sync via read
2878 * callback so we'll let it pass and let the underlying
2879 * FLAC decoder catch the error
2881 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
2882 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2883 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
2884 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2885 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
2886 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
2887 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
2888 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
2889 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
2890 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2893 /* double protection */
2894 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2898 FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
2900 FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
2902 switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
2903 case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
2904 return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
2905 case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
2906 return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
2907 case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
2908 return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2910 /* double protection: */
2912 return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2917 FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2919 if(decoder->private_->is_seeking) {
2920 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
2921 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
2922 FLAC__uint64 target_sample = decoder->private_->target_sample;
2924 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2927 decoder->private_->got_a_frame = true;
2929 decoder->private_->last_frame = *frame; /* save the frame */
2930 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
2931 unsigned delta = (unsigned)(target_sample - this_frame_sample);
2932 /* kick out of seek mode */
2933 decoder->private_->is_seeking = false;
2934 /* shift out the samples before target_sample */
2937 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
2938 for(channel = 0; channel < frame->header.channels; channel++)
2939 newbuffer[channel] = buffer[channel] + delta;
2940 decoder->private_->last_frame.header.blocksize -= delta;
2941 decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
2942 /* write the relevant samples */
2943 return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
2946 /* write the relevant samples */
2947 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2951 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2956 * If we never got STREAMINFO, turn off MD5 checking to save
2957 * cycles since we don't have a sum to compare to anyway
2959 if(!decoder->private_->has_stream_info)
2960 decoder->private_->do_md5_checking = false;
2961 if(decoder->private_->do_md5_checking) {
2962 if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
2963 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2965 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2969 void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2971 if(!decoder->private_->is_seeking)
2972 decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
2973 else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
2974 decoder->private_->unparseable_frame_count++;
2977 FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2979 FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
2980 FLAC__int64 pos = -1;
2982 unsigned approx_bytes_per_frame;
2983 FLAC__bool first_seek = true;
2984 const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
2985 const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2986 const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
2987 const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
2988 const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
2989 /* take these from the current frame in case they've changed mid-stream */
2990 unsigned channels = FLAC__stream_decoder_get_channels(decoder);
2991 unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
2992 const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
2994 /* use values from stream info if we didn't decode a frame */
2996 channels = decoder->private_->stream_info.data.stream_info.channels;
2998 bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
3000 /* we are just guessing here */
3001 if(max_framesize > 0)
3002 approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
3004 * Check if it's a known fixed-blocksize stream. Note that though
3005 * the spec doesn't allow zeroes in the STREAMINFO block, we may
3006 * never get a STREAMINFO block when decoding so the value of
3007 * min_blocksize might be zero.
3009 else if(min_blocksize == max_blocksize && min_blocksize > 0) {
3010 /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
3011 approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
3014 approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
3017 * First, we set an upper and lower bound on where in the
3018 * stream we will search. For now we assume the worst case
3019 * scenario, which is our best guess at the beginning of
3020 * the first frame and end of the stream.
3022 lower_bound = first_frame_offset;
3023 lower_bound_sample = 0;
3024 upper_bound = stream_length;
3025 upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
3028 * Now we refine the bounds if we have a seektable with
3029 * suitable points. Note that according to the spec they
3030 * must be ordered by ascending sample number.
3032 * Note: to protect against invalid seek tables we will ignore points
3033 * that have frame_samples==0 or sample_number>=total_samples
3036 FLAC__uint64 new_lower_bound = lower_bound;
3037 FLAC__uint64 new_upper_bound = upper_bound;
3038 FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
3039 FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
3041 /* find the closest seek point <= target_sample, if it exists */
3042 for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
3044 seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
3045 seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
3046 (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
3047 seek_table->points[i].sample_number <= target_sample
3051 if(i >= 0) { /* i.e. we found a suitable seek point... */
3052 new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
3053 new_lower_bound_sample = seek_table->points[i].sample_number;
3056 /* find the closest seek point > target_sample, if it exists */
3057 for(i = 0; i < (int)seek_table->num_points; i++) {
3059 seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
3060 seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
3061 (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
3062 seek_table->points[i].sample_number > target_sample
3066 if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
3067 new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
3068 new_upper_bound_sample = seek_table->points[i].sample_number;
3070 /* final protection against unsorted seek tables; keep original values if bogus */
3071 if(new_upper_bound >= new_lower_bound) {
3072 lower_bound = new_lower_bound;
3073 upper_bound = new_upper_bound;
3074 lower_bound_sample = new_lower_bound_sample;
3075 upper_bound_sample = new_upper_bound_sample;
3079 FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
3080 /* there are 2 insidious ways that the following equality occurs, which
3082 * 1) total_samples is 0 (unknown) and target_sample is 0
3083 * 2) total_samples is 0 (unknown) and target_sample happens to be
3084 * exactly equal to the last seek point in the seek table; this
3085 * means there is no seek point above it, and upper_bound_samples
3086 * remains equal to the estimate (of target_samples) we made above
3087 * in either case it does not hurt to move upper_bound_sample up by 1
3089 if(upper_bound_sample == lower_bound_sample)
3090 upper_bound_sample++;
3092 decoder->private_->target_sample = target_sample;
3094 /* check if the bounds are still ok */
3095 if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
3096 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3099 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3100 #if defined _MSC_VER || defined __MINGW32__
3101 /* with VC++ you have to spoon feed it the casting */
3102 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;
3104 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;
3107 /* a little less accurate: */
3108 if(upper_bound - lower_bound < 0xffffffff)
3109 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;
3110 else /* @@@ WATCHOUT, ~2TB limit */
3111 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;
3113 if(pos >= (FLAC__int64)upper_bound)
3114 pos = (FLAC__int64)upper_bound - 1;
3115 if(pos < (FLAC__int64)lower_bound)
3116 pos = (FLAC__int64)lower_bound;
3117 if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3118 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3121 if(!FLAC__stream_decoder_flush(decoder)) {
3122 /* above call sets the state for us */
3125 /* Now we need to get a frame. First we need to reset our
3126 * unparseable_frame_count; if we get too many unparseable
3127 * frames in a row, the read callback will return
3128 * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
3129 * FLAC__stream_decoder_process_single() to return false.
3131 decoder->private_->unparseable_frame_count = 0;
3132 if(!FLAC__stream_decoder_process_single(decoder)) {
3133 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3136 /* our write callback will change the state when it gets to the target frame */
3137 /* 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 */
3139 /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
3140 if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
3143 if(!decoder->private_->is_seeking)
3146 FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3147 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3149 if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
3150 if (pos == (FLAC__int64)lower_bound) {
3151 /* can't move back any more than the first frame, something is fatally wrong */
3152 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3155 /* our last move backwards wasn't big enough, try again */
3156 approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
3159 /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
3162 /* make sure we are not seeking in corrupted stream */
3163 if (this_frame_sample < lower_bound_sample) {
3164 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3168 /* we need to narrow the search */
3169 if(target_sample < this_frame_sample) {
3170 upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
3171 /*@@@@@@ what will decode position be if at end of stream? */
3172 if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
3173 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3176 approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
3178 else { /* target_sample >= this_frame_sample + this frame's blocksize */
3179 lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
3180 if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
3181 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3184 approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
3192 FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
3194 FLAC__uint64 left_pos = 0, right_pos = stream_length;
3195 FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
3196 FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
3197 FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
3198 FLAC__bool did_a_seek;
3199 unsigned iteration = 0;
3201 /* In the first iterations, we will calculate the target byte position
3202 * by the distance from the target sample to left_sample and
3203 * right_sample (let's call it "proportional search"). After that, we
3204 * will switch to binary search.
3206 unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
3208 /* We will switch to a linear search once our current sample is less
3209 * than this number of samples ahead of the target sample
3211 static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
3213 /* If the total number of samples is unknown, use a large value, and
3214 * force binary search immediately.
3216 if(right_sample == 0) {
3217 right_sample = (FLAC__uint64)(-1);
3218 BINARY_SEARCH_AFTER_ITERATION = 0;
3221 decoder->private_->target_sample = target_sample;
3222 for( ; ; iteration++) {
3223 if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
3224 if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
3225 pos = (right_pos + left_pos) / 2;
3228 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3229 #if defined _MSC_VER || defined __MINGW32__
3230 /* with MSVC you have to spoon feed it the casting */
3231 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));
3233 pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
3236 /* a little less accurate: */
3237 if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
3238 pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
3239 else /* @@@ WATCHOUT, ~2TB limit */
3240 pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
3242 /* @@@ TODO: might want to limit pos to some distance
3243 * before EOF, to make sure we land before the last frame,
3244 * thereby getting a this_frame_sample and so having a better
3250 if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3251 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3254 if(!FLAC__stream_decoder_flush(decoder)) {
3255 /* above call sets the state for us */
3263 decoder->private_->got_a_frame = false;
3264 if(!FLAC__stream_decoder_process_single(decoder)) {
3265 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3268 if(!decoder->private_->got_a_frame) {
3270 /* this can happen if we seek to a point after the last frame; we drop
3271 * to binary search right away in this case to avoid any wasted
3272 * iterations of proportional search.
3275 BINARY_SEARCH_AFTER_ITERATION = 0;
3278 /* this can probably only happen if total_samples is unknown and the
3279 * target_sample is past the end of the stream
3281 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3285 /* our write callback will change the state when it gets to the target frame */
3286 else if(!decoder->private_->is_seeking) {
3290 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3291 FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3294 if (this_frame_sample <= target_sample) {
3295 /* The 'equal' case should not happen, since
3296 * FLAC__stream_decoder_process_single()
3297 * should recognize that it has hit the
3298 * target sample and we would exit through
3299 * the 'break' above.
3301 FLAC__ASSERT(this_frame_sample != target_sample);
3303 left_sample = this_frame_sample;
3304 /* sanity check to avoid infinite loop */
3305 if (left_pos == pos) {
3306 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3311 else if(this_frame_sample > target_sample) {
3312 right_sample = this_frame_sample;
3313 /* sanity check to avoid infinite loop */
3314 if (right_pos == pos) {
3315 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3328 FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
3333 *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
3334 if(ferror(decoder->private_->file))
3335 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
3336 else if(*bytes == 0)
3337 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
3339 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
3342 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
3345 FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
3349 if(decoder->private_->file == stdin)
3350 return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
3351 else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
3352 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
3354 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
3357 FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
3362 if(decoder->private_->file == stdin)
3363 return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
3364 else if((pos = ftello(decoder->private_->file)) < 0)
3365 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
3367 *absolute_byte_offset = (FLAC__uint64)pos;
3368 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
3372 FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
3374 struct stat filestats;
3377 if(decoder->private_->file == stdin)
3378 return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
3379 else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
3380 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
3382 *stream_length = (FLAC__uint64)filestats.st_size;
3383 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
3387 FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
3391 return feof(decoder->private_->file)? true : false;