1 /* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009 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] */
59 #include "FLAC/assert.h"
60 #include "share/alloc.h"
61 #include "protected/stream_decoder.h"
62 #include "private/bitreader.h"
63 #include "private/bitmath.h"
64 #include "private/cpu.h"
65 #include "private/crc.h"
66 #include "private/fixed.h"
67 #include "private/format.h"
68 #include "private/lpc.h"
69 #include "private/md5.h"
70 #include "private/memory.h"
75 #define max(a,b) ((a)>(b)?(a):(b))
77 /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
79 #define FLAC__U64L(x) x
81 #define FLAC__U64L(x) x##LLU
85 /* technically this should be in an "export.c" but this is convenient enough */
86 FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
95 /***********************************************************************
99 ***********************************************************************/
101 static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
103 /***********************************************************************
105 * Private class method prototypes
107 ***********************************************************************/
109 static void set_defaults_(FLAC__StreamDecoder *decoder);
110 static FILE *get_binary_stdin_(void);
111 static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
112 static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
113 static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
114 static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
115 static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
116 static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
117 static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
118 static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
119 static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
120 static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
121 static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
122 static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
123 static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
124 static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
125 static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
126 static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
127 static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
128 static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
129 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);
130 static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
131 static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
133 static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
134 static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
136 static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
137 static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
138 static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
140 static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
142 static FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
143 static FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
144 static FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
145 static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
146 static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
148 /***********************************************************************
152 ***********************************************************************/
154 typedef struct FLAC__StreamDecoderPrivate {
158 FLAC__StreamDecoderReadCallback read_callback;
159 FLAC__StreamDecoderSeekCallback seek_callback;
160 FLAC__StreamDecoderTellCallback tell_callback;
161 FLAC__StreamDecoderLengthCallback length_callback;
162 FLAC__StreamDecoderEofCallback eof_callback;
163 FLAC__StreamDecoderWriteCallback write_callback;
164 FLAC__StreamDecoderMetadataCallback metadata_callback;
165 FLAC__StreamDecoderErrorCallback error_callback;
166 /* generic 32-bit datapath: */
167 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[]);
168 /* generic 64-bit datapath: */
169 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[]);
170 /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
171 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[]);
172 /* 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: */
173 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[]);
174 FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
176 FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
177 FLAC__BitReader *input;
178 FLAC__int32 *output[FLAC__MAX_CHANNELS];
179 FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
180 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
181 unsigned output_capacity, output_channels;
182 FLAC__uint32 fixed_block_size, next_fixed_block_size;
183 FLAC__uint64 samples_decoded;
184 FLAC__bool has_stream_info, has_seek_table;
185 FLAC__StreamMetadata stream_info;
186 FLAC__StreamMetadata seek_table;
187 FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
188 FLAC__byte *metadata_filter_ids;
189 size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
191 FLAC__bool cached; /* true if there is a byte in lookahead */
192 FLAC__CPUInfo cpuinfo;
193 FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
194 FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
195 /* unaligned (original) pointers to allocated data */
196 FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
197 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 */
198 FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
199 FLAC__bool is_seeking;
200 FLAC__MD5Context md5context;
201 FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
202 /* (the rest of these are only used for seeking) */
203 FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
204 FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
205 FLAC__uint64 target_sample;
206 unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
208 FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
210 } FLAC__StreamDecoderPrivate;
212 /***********************************************************************
214 * Public static class data
216 ***********************************************************************/
218 FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
219 "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
220 "FLAC__STREAM_DECODER_READ_METADATA",
221 "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
222 "FLAC__STREAM_DECODER_READ_FRAME",
223 "FLAC__STREAM_DECODER_END_OF_STREAM",
224 "FLAC__STREAM_DECODER_OGG_ERROR",
225 "FLAC__STREAM_DECODER_SEEK_ERROR",
226 "FLAC__STREAM_DECODER_ABORTED",
227 "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
228 "FLAC__STREAM_DECODER_UNINITIALIZED"
231 FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
232 "FLAC__STREAM_DECODER_INIT_STATUS_OK",
233 "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
234 "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
235 "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
236 "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
237 "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
240 FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
241 "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
242 "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
243 "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
246 FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
247 "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
248 "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
249 "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
252 FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
253 "FLAC__STREAM_DECODER_TELL_STATUS_OK",
254 "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
255 "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
258 FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
259 "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
260 "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
261 "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
264 FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
265 "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
266 "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
269 FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
270 "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
271 "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
272 "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
273 "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
276 /***********************************************************************
278 * Class constructor/destructor
280 ***********************************************************************/
281 FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
283 FLAC__StreamDecoder *decoder;
286 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
288 decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
293 decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
294 if(decoder->protected_ == 0) {
299 decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
300 if(decoder->private_ == 0) {
301 free(decoder->protected_);
306 decoder->private_->input = FLAC__bitreader_new();
307 if(decoder->private_->input == 0) {
308 free(decoder->private_);
309 free(decoder->protected_);
314 decoder->private_->metadata_filter_ids_capacity = 16;
315 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
316 FLAC__bitreader_delete(decoder->private_->input);
317 free(decoder->private_);
318 free(decoder->protected_);
323 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
324 decoder->private_->output[i] = 0;
325 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
328 decoder->private_->output_capacity = 0;
329 decoder->private_->output_channels = 0;
330 decoder->private_->has_seek_table = false;
332 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
333 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
335 decoder->private_->file = 0;
337 set_defaults_(decoder);
339 decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
344 FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
348 FLAC__ASSERT(0 != decoder);
349 FLAC__ASSERT(0 != decoder->protected_);
350 FLAC__ASSERT(0 != decoder->private_);
351 FLAC__ASSERT(0 != decoder->private_->input);
353 (void)FLAC__stream_decoder_finish(decoder);
355 if(0 != decoder->private_->metadata_filter_ids)
356 free(decoder->private_->metadata_filter_ids);
358 FLAC__bitreader_delete(decoder->private_->input);
360 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
361 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
363 free(decoder->private_);
364 free(decoder->protected_);
368 /***********************************************************************
370 * Public class methods
372 ***********************************************************************/
374 static FLAC__StreamDecoderInitStatus init_stream_internal_(
375 FLAC__StreamDecoder *decoder,
376 FLAC__StreamDecoderReadCallback read_callback,
377 FLAC__StreamDecoderSeekCallback seek_callback,
378 FLAC__StreamDecoderTellCallback tell_callback,
379 FLAC__StreamDecoderLengthCallback length_callback,
380 FLAC__StreamDecoderEofCallback eof_callback,
381 FLAC__StreamDecoderWriteCallback write_callback,
382 FLAC__StreamDecoderMetadataCallback metadata_callback,
383 FLAC__StreamDecoderErrorCallback error_callback,
388 FLAC__ASSERT(0 != decoder);
390 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
391 return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
395 return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
399 0 == read_callback ||
400 0 == write_callback ||
401 0 == error_callback ||
402 (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
404 return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
407 decoder->private_->is_ogg = is_ogg;
408 if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
409 return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
413 * get the CPU info and set the function pointers
415 FLAC__cpu_info(&decoder->private_->cpuinfo);
416 /* first default to the non-asm routines */
417 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
418 decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
419 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
420 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
421 decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
422 /* now override with asm where appropriate */
424 if(decoder->private_->cpuinfo.use_asm) {
425 #ifdef FLAC__CPU_IA32
426 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
427 #ifdef FLAC__HAS_NASM
428 #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
429 if(decoder->private_->cpuinfo.data.ia32.bswap)
430 decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
432 if(decoder->private_->cpuinfo.data.ia32.mmx) {
433 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
434 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
435 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
438 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
439 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
440 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
443 #elif defined FLAC__CPU_PPC
444 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
445 if(decoder->private_->cpuinfo.data.ppc.altivec) {
446 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
447 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
453 /* from here on, errors are fatal */
455 if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
456 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
457 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
460 decoder->private_->read_callback = read_callback;
461 decoder->private_->seek_callback = seek_callback;
462 decoder->private_->tell_callback = tell_callback;
463 decoder->private_->length_callback = length_callback;
464 decoder->private_->eof_callback = eof_callback;
465 decoder->private_->write_callback = write_callback;
466 decoder->private_->metadata_callback = metadata_callback;
467 decoder->private_->error_callback = error_callback;
468 decoder->private_->client_data = client_data;
469 decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
470 decoder->private_->samples_decoded = 0;
471 decoder->private_->has_stream_info = false;
472 decoder->private_->cached = false;
474 decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
475 decoder->private_->is_seeking = false;
477 decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
478 if(!FLAC__stream_decoder_reset(decoder)) {
479 /* above call sets the state for us */
480 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
483 return FLAC__STREAM_DECODER_INIT_STATUS_OK;
486 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
487 FLAC__StreamDecoder *decoder,
488 FLAC__StreamDecoderReadCallback read_callback,
489 FLAC__StreamDecoderSeekCallback seek_callback,
490 FLAC__StreamDecoderTellCallback tell_callback,
491 FLAC__StreamDecoderLengthCallback length_callback,
492 FLAC__StreamDecoderEofCallback eof_callback,
493 FLAC__StreamDecoderWriteCallback write_callback,
494 FLAC__StreamDecoderMetadataCallback metadata_callback,
495 FLAC__StreamDecoderErrorCallback error_callback,
499 return init_stream_internal_(
514 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
515 FLAC__StreamDecoder *decoder,
516 FLAC__StreamDecoderReadCallback read_callback,
517 FLAC__StreamDecoderSeekCallback seek_callback,
518 FLAC__StreamDecoderTellCallback tell_callback,
519 FLAC__StreamDecoderLengthCallback length_callback,
520 FLAC__StreamDecoderEofCallback eof_callback,
521 FLAC__StreamDecoderWriteCallback write_callback,
522 FLAC__StreamDecoderMetadataCallback metadata_callback,
523 FLAC__StreamDecoderErrorCallback error_callback,
527 return init_stream_internal_(
542 static FLAC__StreamDecoderInitStatus init_FILE_internal_(
543 FLAC__StreamDecoder *decoder,
545 FLAC__StreamDecoderWriteCallback write_callback,
546 FLAC__StreamDecoderMetadataCallback metadata_callback,
547 FLAC__StreamDecoderErrorCallback error_callback,
552 FLAC__ASSERT(0 != decoder);
553 FLAC__ASSERT(0 != file);
555 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
556 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
558 if(0 == write_callback || 0 == error_callback)
559 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
562 * To make sure that our file does not go unclosed after an error, we
563 * must assign the FILE pointer before any further error can occur in
567 file = get_binary_stdin_(); /* just to be safe */
569 decoder->private_->file = file;
571 return init_stream_internal_(
574 decoder->private_->file == stdin? 0: file_seek_callback_,
575 decoder->private_->file == stdin? 0: file_tell_callback_,
576 decoder->private_->file == stdin? 0: file_length_callback_,
586 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
587 FLAC__StreamDecoder *decoder,
589 FLAC__StreamDecoderWriteCallback write_callback,
590 FLAC__StreamDecoderMetadataCallback metadata_callback,
591 FLAC__StreamDecoderErrorCallback error_callback,
595 return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
598 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
599 FLAC__StreamDecoder *decoder,
601 FLAC__StreamDecoderWriteCallback write_callback,
602 FLAC__StreamDecoderMetadataCallback metadata_callback,
603 FLAC__StreamDecoderErrorCallback error_callback,
607 return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
610 static FLAC__StreamDecoderInitStatus init_file_internal_(
611 FLAC__StreamDecoder *decoder,
612 const char *filename,
613 FLAC__StreamDecoderWriteCallback write_callback,
614 FLAC__StreamDecoderMetadataCallback metadata_callback,
615 FLAC__StreamDecoderErrorCallback error_callback,
622 FLAC__ASSERT(0 != decoder);
625 * To make sure that our file does not go unclosed after an error, we
626 * have to do the same entrance checks here that are later performed
627 * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
629 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
630 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
632 if(0 == write_callback || 0 == error_callback)
633 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
635 file = filename? fopen(filename, "rb") : stdin;
638 return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
640 return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
643 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
644 FLAC__StreamDecoder *decoder,
645 const char *filename,
646 FLAC__StreamDecoderWriteCallback write_callback,
647 FLAC__StreamDecoderMetadataCallback metadata_callback,
648 FLAC__StreamDecoderErrorCallback error_callback,
652 return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
655 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
656 FLAC__StreamDecoder *decoder,
657 const char *filename,
658 FLAC__StreamDecoderWriteCallback write_callback,
659 FLAC__StreamDecoderMetadataCallback metadata_callback,
660 FLAC__StreamDecoderErrorCallback error_callback,
664 return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
667 FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
669 FLAC__bool md5_failed = false;
672 FLAC__ASSERT(0 != decoder);
673 FLAC__ASSERT(0 != decoder->private_);
674 FLAC__ASSERT(0 != decoder->protected_);
676 if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
679 /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
680 * always call FLAC__MD5Final()
682 FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
684 if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
685 free(decoder->private_->seek_table.data.seek_table.points);
686 decoder->private_->seek_table.data.seek_table.points = 0;
687 decoder->private_->has_seek_table = false;
689 FLAC__bitreader_free(decoder->private_->input);
690 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
692 * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
693 * output arrays have a buffer of up to 3 zeroes in front
694 * (at negative indices) for alignment purposes; we use 4
695 * to keep the data well-aligned.
697 if(0 != decoder->private_->output[i]) {
698 free(decoder->private_->output[i]-4);
699 decoder->private_->output[i] = 0;
701 if(0 != decoder->private_->residual_unaligned[i]) {
702 free(decoder->private_->residual_unaligned[i]);
703 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
706 decoder->private_->output_capacity = 0;
707 decoder->private_->output_channels = 0;
710 if(decoder->private_->is_ogg)
711 FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
714 if(0 != decoder->private_->file) {
715 if(decoder->private_->file != stdin)
716 fclose(decoder->private_->file);
717 decoder->private_->file = 0;
720 if(decoder->private_->do_md5_checking) {
721 if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
724 decoder->private_->is_seeking = false;
726 set_defaults_(decoder);
728 decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
733 FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
735 FLAC__ASSERT(0 != decoder);
736 FLAC__ASSERT(0 != decoder->private_);
737 FLAC__ASSERT(0 != decoder->protected_);
738 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
741 /* can't check decoder->private_->is_ogg since that's not set until init time */
742 FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
750 FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
752 FLAC__ASSERT(0 != decoder);
753 FLAC__ASSERT(0 != decoder->protected_);
754 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
756 decoder->protected_->md5_checking = value;
760 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
762 FLAC__ASSERT(0 != decoder);
763 FLAC__ASSERT(0 != decoder->private_);
764 FLAC__ASSERT(0 != decoder->protected_);
765 FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
766 /* double protection */
767 if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
769 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
771 decoder->private_->metadata_filter[type] = true;
772 if(type == FLAC__METADATA_TYPE_APPLICATION)
773 decoder->private_->metadata_filter_ids_count = 0;
777 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
779 FLAC__ASSERT(0 != decoder);
780 FLAC__ASSERT(0 != decoder->private_);
781 FLAC__ASSERT(0 != decoder->protected_);
782 FLAC__ASSERT(0 != id);
783 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
786 if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
789 FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
791 if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
792 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))) {
793 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
796 decoder->private_->metadata_filter_ids_capacity *= 2;
799 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));
800 decoder->private_->metadata_filter_ids_count++;
805 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
808 FLAC__ASSERT(0 != decoder);
809 FLAC__ASSERT(0 != decoder->private_);
810 FLAC__ASSERT(0 != decoder->protected_);
811 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
813 for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
814 decoder->private_->metadata_filter[i] = true;
815 decoder->private_->metadata_filter_ids_count = 0;
819 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
821 FLAC__ASSERT(0 != decoder);
822 FLAC__ASSERT(0 != decoder->private_);
823 FLAC__ASSERT(0 != decoder->protected_);
824 FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
825 /* double protection */
826 if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
828 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
830 decoder->private_->metadata_filter[type] = false;
831 if(type == FLAC__METADATA_TYPE_APPLICATION)
832 decoder->private_->metadata_filter_ids_count = 0;
836 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
838 FLAC__ASSERT(0 != decoder);
839 FLAC__ASSERT(0 != decoder->private_);
840 FLAC__ASSERT(0 != decoder->protected_);
841 FLAC__ASSERT(0 != id);
842 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
845 if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
848 FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
850 if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
851 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))) {
852 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
855 decoder->private_->metadata_filter_ids_capacity *= 2;
858 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));
859 decoder->private_->metadata_filter_ids_count++;
864 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
866 FLAC__ASSERT(0 != decoder);
867 FLAC__ASSERT(0 != decoder->private_);
868 FLAC__ASSERT(0 != decoder->protected_);
869 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
871 memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
872 decoder->private_->metadata_filter_ids_count = 0;
876 FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
878 FLAC__ASSERT(0 != decoder);
879 FLAC__ASSERT(0 != decoder->protected_);
880 return decoder->protected_->state;
883 FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
885 return FLAC__StreamDecoderStateString[decoder->protected_->state];
888 FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
890 FLAC__ASSERT(0 != decoder);
891 FLAC__ASSERT(0 != decoder->protected_);
892 return decoder->protected_->md5_checking;
895 FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
897 FLAC__ASSERT(0 != decoder);
898 FLAC__ASSERT(0 != decoder->protected_);
899 return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
902 FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
904 FLAC__ASSERT(0 != decoder);
905 FLAC__ASSERT(0 != decoder->protected_);
906 return decoder->protected_->channels;
909 FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
911 FLAC__ASSERT(0 != decoder);
912 FLAC__ASSERT(0 != decoder->protected_);
913 return decoder->protected_->channel_assignment;
916 FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
918 FLAC__ASSERT(0 != decoder);
919 FLAC__ASSERT(0 != decoder->protected_);
920 return decoder->protected_->bits_per_sample;
923 FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
925 FLAC__ASSERT(0 != decoder);
926 FLAC__ASSERT(0 != decoder->protected_);
927 return decoder->protected_->sample_rate;
930 FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
932 FLAC__ASSERT(0 != decoder);
933 FLAC__ASSERT(0 != decoder->protected_);
934 return decoder->protected_->blocksize;
937 FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
939 FLAC__ASSERT(0 != decoder);
940 FLAC__ASSERT(0 != decoder->private_);
941 FLAC__ASSERT(0 != position);
944 if(decoder->private_->is_ogg)
947 if(0 == decoder->private_->tell_callback)
949 if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
951 /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
952 if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
954 FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
955 *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
959 FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
961 FLAC__ASSERT(0 != decoder);
962 FLAC__ASSERT(0 != decoder->private_);
963 FLAC__ASSERT(0 != decoder->protected_);
965 decoder->private_->samples_decoded = 0;
966 decoder->private_->do_md5_checking = false;
969 if(decoder->private_->is_ogg)
970 FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
973 if(!FLAC__bitreader_clear(decoder->private_->input)) {
974 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
977 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
982 FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
984 FLAC__ASSERT(0 != decoder);
985 FLAC__ASSERT(0 != decoder->private_);
986 FLAC__ASSERT(0 != decoder->protected_);
988 if(!FLAC__stream_decoder_flush(decoder)) {
989 /* above call sets the state for us */
994 /*@@@ could go in !internal_reset_hack block below */
995 if(decoder->private_->is_ogg)
996 FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
999 /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
1000 * (internal_reset_hack) don't try to rewind since we are already at
1001 * the beginning of the stream and don't want to fail if the input is
1004 if(!decoder->private_->internal_reset_hack) {
1005 if(decoder->private_->file == stdin)
1006 return false; /* can't rewind stdin, reset fails */
1007 if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
1008 return false; /* seekable and seek fails, reset fails */
1011 decoder->private_->internal_reset_hack = false;
1013 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
1015 decoder->private_->has_stream_info = false;
1016 if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
1017 free(decoder->private_->seek_table.data.seek_table.points);
1018 decoder->private_->seek_table.data.seek_table.points = 0;
1019 decoder->private_->has_seek_table = false;
1021 decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
1023 * This goes in reset() and not flush() because according to the spec, a
1024 * fixed-blocksize stream must stay that way through the whole stream.
1026 decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
1028 /* We initialize the FLAC__MD5Context even though we may never use it. This
1029 * is because md5 checking may be turned on to start and then turned off if
1030 * a seek occurs. So we init the context here and finalize it in
1031 * FLAC__stream_decoder_finish() to make sure things are always cleaned up
1034 FLAC__MD5Init(&decoder->private_->md5context);
1036 decoder->private_->first_frame_offset = 0;
1037 decoder->private_->unparseable_frame_count = 0;
1042 FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
1044 FLAC__bool got_a_frame;
1045 FLAC__ASSERT(0 != decoder);
1046 FLAC__ASSERT(0 != decoder->protected_);
1049 switch(decoder->protected_->state) {
1050 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1051 if(!find_metadata_(decoder))
1052 return false; /* above function sets the status for us */
1054 case FLAC__STREAM_DECODER_READ_METADATA:
1055 if(!read_metadata_(decoder))
1056 return false; /* above function sets the status for us */
1059 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1060 if(!frame_sync_(decoder))
1061 return true; /* above function sets the status for us */
1063 case FLAC__STREAM_DECODER_READ_FRAME:
1064 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
1065 return false; /* above function sets the status for us */
1067 return true; /* above function sets the status for us */
1069 case FLAC__STREAM_DECODER_END_OF_STREAM:
1070 case FLAC__STREAM_DECODER_ABORTED:
1079 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
1081 FLAC__ASSERT(0 != decoder);
1082 FLAC__ASSERT(0 != decoder->protected_);
1085 switch(decoder->protected_->state) {
1086 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1087 if(!find_metadata_(decoder))
1088 return false; /* above function sets the status for us */
1090 case FLAC__STREAM_DECODER_READ_METADATA:
1091 if(!read_metadata_(decoder))
1092 return false; /* above function sets the status for us */
1094 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1095 case FLAC__STREAM_DECODER_READ_FRAME:
1096 case FLAC__STREAM_DECODER_END_OF_STREAM:
1097 case FLAC__STREAM_DECODER_ABORTED:
1106 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
1109 FLAC__ASSERT(0 != decoder);
1110 FLAC__ASSERT(0 != decoder->protected_);
1113 switch(decoder->protected_->state) {
1114 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1115 if(!find_metadata_(decoder))
1116 return false; /* above function sets the status for us */
1118 case FLAC__STREAM_DECODER_READ_METADATA:
1119 if(!read_metadata_(decoder))
1120 return false; /* above function sets the status for us */
1122 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1123 if(!frame_sync_(decoder))
1124 return true; /* above function sets the status for us */
1126 case FLAC__STREAM_DECODER_READ_FRAME:
1127 if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
1128 return false; /* above function sets the status for us */
1130 case FLAC__STREAM_DECODER_END_OF_STREAM:
1131 case FLAC__STREAM_DECODER_ABORTED:
1140 FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
1142 FLAC__bool got_a_frame;
1143 FLAC__ASSERT(0 != decoder);
1144 FLAC__ASSERT(0 != decoder->protected_);
1147 switch(decoder->protected_->state) {
1148 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1149 case FLAC__STREAM_DECODER_READ_METADATA:
1150 return false; /* above function sets the status for us */
1151 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1152 if(!frame_sync_(decoder))
1153 return true; /* above function sets the status for us */
1155 case FLAC__STREAM_DECODER_READ_FRAME:
1156 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
1157 return false; /* above function sets the status for us */
1159 return true; /* above function sets the status for us */
1161 case FLAC__STREAM_DECODER_END_OF_STREAM:
1162 case FLAC__STREAM_DECODER_ABORTED:
1171 FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
1173 FLAC__uint64 length;
1175 FLAC__ASSERT(0 != decoder);
1178 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
1179 decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
1180 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
1181 decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
1182 decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
1186 if(0 == decoder->private_->seek_callback)
1189 FLAC__ASSERT(decoder->private_->seek_callback);
1190 FLAC__ASSERT(decoder->private_->tell_callback);
1191 FLAC__ASSERT(decoder->private_->length_callback);
1192 FLAC__ASSERT(decoder->private_->eof_callback);
1194 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
1197 decoder->private_->is_seeking = true;
1199 /* turn off md5 checking if a seek is attempted */
1200 decoder->private_->do_md5_checking = false;
1202 /* 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) */
1203 if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
1204 decoder->private_->is_seeking = false;
1208 /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
1210 decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
1211 decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
1213 if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
1214 /* above call sets the state for us */
1215 decoder->private_->is_seeking = false;
1218 /* check this again in case we didn't know total_samples the first time */
1219 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
1220 decoder->private_->is_seeking = false;
1226 const FLAC__bool ok =
1228 decoder->private_->is_ogg?
1229 seek_to_absolute_sample_ogg_(decoder, length, sample) :
1231 seek_to_absolute_sample_(decoder, length, sample)
1233 decoder->private_->is_seeking = false;
1238 /***********************************************************************
1240 * Protected class methods
1242 ***********************************************************************/
1244 unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
1246 FLAC__ASSERT(0 != decoder);
1247 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1248 FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
1249 return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
1252 /***********************************************************************
1254 * Private class methods
1256 ***********************************************************************/
1258 void set_defaults_(FLAC__StreamDecoder *decoder)
1261 decoder->private_->is_ogg = false;
1263 decoder->private_->read_callback = 0;
1264 decoder->private_->seek_callback = 0;
1265 decoder->private_->tell_callback = 0;
1266 decoder->private_->length_callback = 0;
1267 decoder->private_->eof_callback = 0;
1268 decoder->private_->write_callback = 0;
1269 decoder->private_->metadata_callback = 0;
1270 decoder->private_->error_callback = 0;
1271 decoder->private_->client_data = 0;
1273 memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
1274 decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
1275 decoder->private_->metadata_filter_ids_count = 0;
1277 decoder->protected_->md5_checking = false;
1280 FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
1285 * This will forcibly set stdin to binary mode (for OSes that require it)
1287 FILE *get_binary_stdin_(void)
1289 /* if something breaks here it is probably due to the presence or
1290 * absence of an underscore before the identifiers 'setmode',
1291 * 'fileno', and/or 'O_BINARY'; check your system header files.
1293 #if defined _MSC_VER || defined __MINGW32__
1294 _setmode(_fileno(stdin), _O_BINARY);
1295 #elif defined __CYGWIN__
1296 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
1297 setmode(_fileno(stdin), _O_BINARY);
1298 #elif defined __EMX__
1299 setmode(fileno(stdin), O_BINARY);
1305 FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
1310 if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
1313 /* simply using realloc() is not practical because the number of channels may change mid-stream */
1315 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
1316 if(0 != decoder->private_->output[i]) {
1317 free(decoder->private_->output[i]-4);
1318 decoder->private_->output[i] = 0;
1320 if(0 != decoder->private_->residual_unaligned[i]) {
1321 free(decoder->private_->residual_unaligned[i]);
1322 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
1326 for(i = 0; i < channels; i++) {
1328 * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
1329 * output arrays have a buffer of up to 3 zeroes in front
1330 * (at negative indices) for alignment purposes; we use 4
1331 * to keep the data well-aligned.
1333 tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
1335 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1338 memset(tmp, 0, sizeof(FLAC__int32)*4);
1339 decoder->private_->output[i] = tmp + 4;
1342 * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
1344 if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
1345 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1350 decoder->private_->output_capacity = size;
1351 decoder->private_->output_channels = channels;
1356 FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
1360 FLAC__ASSERT(0 != decoder);
1361 FLAC__ASSERT(0 != decoder->private_);
1363 for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
1364 if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
1370 FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
1374 FLAC__bool first = true;
1376 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1378 for(i = id = 0; i < 4; ) {
1379 if(decoder->private_->cached) {
1380 x = (FLAC__uint32)decoder->private_->lookahead;
1381 decoder->private_->cached = false;
1384 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1385 return false; /* read_callback_ sets the state for us */
1387 if(x == FLAC__STREAM_SYNC_STRING[i]) {
1393 if(x == ID3V2_TAG_[id]) {
1397 if(!skip_id3v2_tag_(decoder))
1398 return false; /* skip_id3v2_tag_ sets the state for us */
1403 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1404 decoder->private_->header_warmup[0] = (FLAC__byte)x;
1405 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1406 return false; /* read_callback_ sets the state for us */
1408 /* 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 */
1409 /* else we have to check if the second byte is the end of a sync code */
1410 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1411 decoder->private_->lookahead = (FLAC__byte)x;
1412 decoder->private_->cached = true;
1414 else if(x >> 1 == 0x7c) { /* MAGIC NUMBER for the last 6 sync bits and reserved 7th bit */
1415 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1416 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1422 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1427 decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
1431 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
1434 FLAC__uint32 i, x, type, length;
1436 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1438 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
1439 return false; /* read_callback_ sets the state for us */
1440 is_last = x? true : false;
1442 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
1443 return false; /* read_callback_ sets the state for us */
1445 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
1446 return false; /* read_callback_ sets the state for us */
1448 if(type == FLAC__METADATA_TYPE_STREAMINFO) {
1449 if(!read_metadata_streaminfo_(decoder, is_last, length))
1452 decoder->private_->has_stream_info = true;
1453 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))
1454 decoder->private_->do_md5_checking = false;
1455 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
1456 decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
1458 else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
1459 if(!read_metadata_seektable_(decoder, is_last, length))
1462 decoder->private_->has_seek_table = true;
1463 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
1464 decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
1467 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
1468 unsigned real_length = length;
1469 FLAC__StreamMetadata block;
1471 block.is_last = is_last;
1472 block.type = (FLAC__MetadataType)type;
1473 block.length = length;
1475 if(type == FLAC__METADATA_TYPE_APPLICATION) {
1476 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
1477 return false; /* read_callback_ sets the state for us */
1479 if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
1480 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
1484 real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
1486 if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
1491 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
1492 return false; /* read_callback_ sets the state for us */
1496 case FLAC__METADATA_TYPE_PADDING:
1497 /* skip the padding bytes */
1498 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
1499 return false; /* read_callback_ sets the state for us */
1501 case FLAC__METADATA_TYPE_APPLICATION:
1502 /* remember, we read the ID already */
1503 if(real_length > 0) {
1504 if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
1505 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1508 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
1509 return false; /* read_callback_ sets the state for us */
1512 block.data.application.data = 0;
1514 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1515 if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
1518 case FLAC__METADATA_TYPE_CUESHEET:
1519 if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
1522 case FLAC__METADATA_TYPE_PICTURE:
1523 if(!read_metadata_picture_(decoder, &block.data.picture))
1526 case FLAC__METADATA_TYPE_STREAMINFO:
1527 case FLAC__METADATA_TYPE_SEEKTABLE:
1531 if(real_length > 0) {
1532 if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
1533 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1536 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
1537 return false; /* read_callback_ sets the state for us */
1540 block.data.unknown.data = 0;
1543 if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
1544 decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1546 /* now we have to free any malloc()ed data in the block */
1548 case FLAC__METADATA_TYPE_PADDING:
1550 case FLAC__METADATA_TYPE_APPLICATION:
1551 if(0 != block.data.application.data)
1552 free(block.data.application.data);
1554 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1555 if(0 != block.data.vorbis_comment.vendor_string.entry)
1556 free(block.data.vorbis_comment.vendor_string.entry);
1557 if(block.data.vorbis_comment.num_comments > 0)
1558 for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
1559 if(0 != block.data.vorbis_comment.comments[i].entry)
1560 free(block.data.vorbis_comment.comments[i].entry);
1561 if(0 != block.data.vorbis_comment.comments)
1562 free(block.data.vorbis_comment.comments);
1564 case FLAC__METADATA_TYPE_CUESHEET:
1565 if(block.data.cue_sheet.num_tracks > 0)
1566 for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
1567 if(0 != block.data.cue_sheet.tracks[i].indices)
1568 free(block.data.cue_sheet.tracks[i].indices);
1569 if(0 != block.data.cue_sheet.tracks)
1570 free(block.data.cue_sheet.tracks);
1572 case FLAC__METADATA_TYPE_PICTURE:
1573 if(0 != block.data.picture.mime_type)
1574 free(block.data.picture.mime_type);
1575 if(0 != block.data.picture.description)
1576 free(block.data.picture.description);
1577 if(0 != block.data.picture.data)
1578 free(block.data.picture.data);
1580 case FLAC__METADATA_TYPE_STREAMINFO:
1581 case FLAC__METADATA_TYPE_SEEKTABLE:
1584 if(0 != block.data.unknown.data)
1585 free(block.data.unknown.data);
1592 /* if this fails, it's OK, it's just a hint for the seek routine */
1593 if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
1594 decoder->private_->first_frame_offset = 0;
1595 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1601 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1604 unsigned bits, used_bits = 0;
1606 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1608 decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
1609 decoder->private_->stream_info.is_last = is_last;
1610 decoder->private_->stream_info.length = length;
1612 bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1613 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
1614 return false; /* read_callback_ sets the state for us */
1615 decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1618 bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1619 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
1620 return false; /* read_callback_ sets the state for us */
1621 decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1624 bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1625 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
1626 return false; /* read_callback_ sets the state for us */
1627 decoder->private_->stream_info.data.stream_info.min_framesize = x;
1630 bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1631 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
1632 return false; /* read_callback_ sets the state for us */
1633 decoder->private_->stream_info.data.stream_info.max_framesize = x;
1636 bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1637 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
1638 return false; /* read_callback_ sets the state for us */
1639 decoder->private_->stream_info.data.stream_info.sample_rate = x;
1642 bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1643 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
1644 return false; /* read_callback_ sets the state for us */
1645 decoder->private_->stream_info.data.stream_info.channels = x+1;
1648 bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1649 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
1650 return false; /* read_callback_ sets the state for us */
1651 decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1654 bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1655 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))
1656 return false; /* read_callback_ sets the state for us */
1659 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
1660 return false; /* read_callback_ sets the state for us */
1663 /* skip the rest of the block */
1664 FLAC__ASSERT(used_bits % 8 == 0);
1665 length -= (used_bits / 8);
1666 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
1667 return false; /* read_callback_ sets the state for us */
1672 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1677 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1679 decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1680 decoder->private_->seek_table.is_last = is_last;
1681 decoder->private_->seek_table.length = length;
1683 decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1685 /* use realloc since we may pass through here several times (e.g. after seeking) */
1686 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)))) {
1687 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1690 for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1691 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
1692 return false; /* read_callback_ sets the state for us */
1693 decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1695 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
1696 return false; /* read_callback_ sets the state for us */
1697 decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1699 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
1700 return false; /* read_callback_ sets the state for us */
1701 decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1703 length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1704 /* if there is a partial point left, skip over it */
1706 /*@@@ do a send_error_to_client_() here? there's an argument for either way */
1707 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
1708 return false; /* read_callback_ sets the state for us */
1714 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1718 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1720 /* read vendor string */
1721 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1722 if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
1723 return false; /* read_callback_ sets the state for us */
1724 if(obj->vendor_string.length > 0) {
1725 if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
1726 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1729 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
1730 return false; /* read_callback_ sets the state for us */
1731 obj->vendor_string.entry[obj->vendor_string.length] = '\0';
1734 obj->vendor_string.entry = 0;
1736 /* read num comments */
1737 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1738 if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
1739 return false; /* read_callback_ sets the state for us */
1742 if(obj->num_comments > 0) {
1743 if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1744 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1747 for(i = 0; i < obj->num_comments; i++) {
1748 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1749 if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
1750 return false; /* read_callback_ sets the state for us */
1751 if(obj->comments[i].length > 0) {
1752 if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
1753 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1756 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
1757 return false; /* read_callback_ sets the state for us */
1758 obj->comments[i].entry[obj->comments[i].length] = '\0';
1761 obj->comments[i].entry = 0;
1771 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1773 FLAC__uint32 i, j, x;
1775 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1777 memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1779 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1780 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))
1781 return false; /* read_callback_ sets the state for us */
1783 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
1784 return false; /* read_callback_ sets the state for us */
1786 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
1787 return false; /* read_callback_ sets the state for us */
1788 obj->is_cd = x? true : false;
1790 if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
1791 return false; /* read_callback_ sets the state for us */
1793 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
1794 return false; /* read_callback_ sets the state for us */
1795 obj->num_tracks = x;
1797 if(obj->num_tracks > 0) {
1798 if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1799 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1802 for(i = 0; i < obj->num_tracks; i++) {
1803 FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1804 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
1805 return false; /* read_callback_ sets the state for us */
1807 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
1808 return false; /* read_callback_ sets the state for us */
1809 track->number = (FLAC__byte)x;
1811 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1812 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
1813 return false; /* read_callback_ sets the state for us */
1815 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
1816 return false; /* read_callback_ sets the state for us */
1819 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
1820 return false; /* read_callback_ sets the state for us */
1821 track->pre_emphasis = x;
1823 if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
1824 return false; /* read_callback_ sets the state for us */
1826 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
1827 return false; /* read_callback_ sets the state for us */
1828 track->num_indices = (FLAC__byte)x;
1830 if(track->num_indices > 0) {
1831 if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1832 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1835 for(j = 0; j < track->num_indices; j++) {
1836 FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1837 if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
1838 return false; /* read_callback_ sets the state for us */
1840 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
1841 return false; /* read_callback_ sets the state for us */
1842 index->number = (FLAC__byte)x;
1844 if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
1845 return false; /* read_callback_ sets the state for us */
1854 FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
1858 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1861 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
1862 return false; /* read_callback_ sets the state for us */
1865 /* read MIME type */
1866 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
1867 return false; /* read_callback_ sets the state for us */
1868 if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
1869 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1873 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
1874 return false; /* read_callback_ sets the state for us */
1876 obj->mime_type[x] = '\0';
1878 /* read description */
1879 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
1880 return false; /* read_callback_ sets the state for us */
1881 if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
1882 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1886 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
1887 return false; /* read_callback_ sets the state for us */
1889 obj->description[x] = '\0';
1892 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
1893 return false; /* read_callback_ sets the state for us */
1896 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
1897 return false; /* read_callback_ sets the state for us */
1900 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
1901 return false; /* read_callback_ sets the state for us */
1904 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
1905 return false; /* read_callback_ sets the state for us */
1908 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
1909 return false; /* read_callback_ sets the state for us */
1910 if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
1911 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1914 if(obj->data_length > 0) {
1915 if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
1916 return false; /* read_callback_ sets the state for us */
1922 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1927 /* skip the version and flags bytes */
1928 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
1929 return false; /* read_callback_ sets the state for us */
1930 /* get the size (in bytes) to skip */
1932 for(i = 0; i < 4; i++) {
1933 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1934 return false; /* read_callback_ sets the state for us */
1938 /* skip the rest of the tag */
1939 if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
1940 return false; /* read_callback_ sets the state for us */
1944 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1947 FLAC__bool first = true;
1949 /* If we know the total number of samples in the stream, stop if we've read that many. */
1950 /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1951 if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
1952 if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
1953 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1958 /* make sure we're byte aligned */
1959 if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
1960 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
1961 return false; /* read_callback_ sets the state for us */
1965 if(decoder->private_->cached) {
1966 x = (FLAC__uint32)decoder->private_->lookahead;
1967 decoder->private_->cached = false;
1970 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1971 return false; /* read_callback_ sets the state for us */
1973 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1974 decoder->private_->header_warmup[0] = (FLAC__byte)x;
1975 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1976 return false; /* read_callback_ sets the state for us */
1978 /* 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 */
1979 /* else we have to check if the second byte is the end of a sync code */
1980 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1981 decoder->private_->lookahead = (FLAC__byte)x;
1982 decoder->private_->cached = true;
1984 else if(x >> 1 == 0x7c) { /* MAGIC NUMBER for the last 6 sync bits and reserved 7th bit */
1985 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1986 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1991 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1999 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
2003 FLAC__int32 mid, side;
2004 unsigned frame_crc; /* the one we calculate from the input stream */
2007 *got_a_frame = false;
2011 frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
2012 frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
2013 FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
2015 if(!read_frame_header_(decoder))
2017 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
2019 if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
2021 for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2023 * first figure the correct bits-per-sample of the subframe
2025 unsigned bps = decoder->private_->frame.header.bits_per_sample;
2026 switch(decoder->private_->frame.header.channel_assignment) {
2027 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2028 /* no adjustment needed */
2030 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2031 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2035 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2036 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2040 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2041 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2051 if(!read_subframe_(decoder, channel, bps, do_full_decode))
2053 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2056 if(!read_zero_padding_(decoder))
2058 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) */
2062 * Read the frame CRC-16 from the footer and check
2064 frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
2065 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
2066 return false; /* read_callback_ sets the state for us */
2067 if(frame_crc == x) {
2068 if(do_full_decode) {
2069 /* Undo any special channel coding */
2070 switch(decoder->private_->frame.header.channel_assignment) {
2071 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2074 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2075 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2076 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2077 decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
2079 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2080 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2081 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2082 decoder->private_->output[0][i] += decoder->private_->output[1][i];
2084 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2085 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2086 for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2088 mid = decoder->private_->output[0][i];
2089 side = decoder->private_->output[1][i];
2091 mid |= (side & 1); /* i.e. if 'side' is odd... */
2092 decoder->private_->output[0][i] = (mid + side) >> 1;
2093 decoder->private_->output[1][i] = (mid - side) >> 1;
2095 /* OPT: without 'side' temp variable */
2096 mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
2097 decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
2098 decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
2109 /* Bad frame, emit error and zero the output signal */
2110 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
2111 if(do_full_decode) {
2112 for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2113 memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2118 *got_a_frame = true;
2120 /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
2121 if(decoder->private_->next_fixed_block_size)
2122 decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
2124 /* put the latest values into the public section of the decoder instance */
2125 decoder->protected_->channels = decoder->private_->frame.header.channels;
2126 decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
2127 decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
2128 decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
2129 decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
2131 FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2132 decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
2135 if(do_full_decode) {
2136 if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
2140 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2144 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
2148 unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
2149 FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
2150 unsigned raw_header_len;
2151 FLAC__bool is_unparseable = false;
2153 FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
2155 /* init the raw header with the saved bits from synchronization */
2156 raw_header[0] = decoder->private_->header_warmup[0];
2157 raw_header[1] = decoder->private_->header_warmup[1];
2160 /* check to make sure that reserved bit is 0 */
2161 if(raw_header[1] & 0x02) /* MAGIC NUMBER */
2162 is_unparseable = true;
2165 * Note that along the way as we read the header, we look for a sync
2166 * code inside. If we find one it would indicate that our original
2167 * sync was bad since there cannot be a sync code in a valid header.
2169 * Three kinds of things can go wrong when reading the frame header:
2170 * 1) We may have sync'ed incorrectly and not landed on a frame header.
2171 * If we don't find a sync code, it can end up looking like we read
2172 * a valid but unparseable header, until getting to the frame header
2173 * CRC. Even then we could get a false positive on the CRC.
2174 * 2) We may have sync'ed correctly but on an unparseable frame (from a
2176 * 3) We may be on a damaged frame which appears valid but unparseable.
2178 * For all these reasons, we try and read a complete frame header as
2179 * long as it seems valid, even if unparseable, up until the frame
2184 * read in the raw header as bytes so we can CRC it, and parse it on the way
2186 for(i = 0; i < 2; i++) {
2187 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2188 return false; /* read_callback_ sets the state for us */
2189 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
2190 /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
2191 decoder->private_->lookahead = (FLAC__byte)x;
2192 decoder->private_->cached = true;
2193 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2194 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2197 raw_header[raw_header_len++] = (FLAC__byte)x;
2200 switch(x = raw_header[2] >> 4) {
2202 is_unparseable = true;
2205 decoder->private_->frame.header.blocksize = 192;
2211 decoder->private_->frame.header.blocksize = 576 << (x-2);
2225 decoder->private_->frame.header.blocksize = 256 << (x-8);
2232 switch(x = raw_header[2] & 0x0f) {
2234 if(decoder->private_->has_stream_info)
2235 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
2237 is_unparseable = true;
2240 decoder->private_->frame.header.sample_rate = 88200;
2243 decoder->private_->frame.header.sample_rate = 176400;
2246 decoder->private_->frame.header.sample_rate = 192000;
2249 decoder->private_->frame.header.sample_rate = 8000;
2252 decoder->private_->frame.header.sample_rate = 16000;
2255 decoder->private_->frame.header.sample_rate = 22050;
2258 decoder->private_->frame.header.sample_rate = 24000;
2261 decoder->private_->frame.header.sample_rate = 32000;
2264 decoder->private_->frame.header.sample_rate = 44100;
2267 decoder->private_->frame.header.sample_rate = 48000;
2270 decoder->private_->frame.header.sample_rate = 96000;
2275 sample_rate_hint = x;
2278 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2279 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2285 x = (unsigned)(raw_header[3] >> 4);
2287 decoder->private_->frame.header.channels = 2;
2290 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2293 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2296 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2299 is_unparseable = true;
2304 decoder->private_->frame.header.channels = (unsigned)x + 1;
2305 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2308 switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2310 if(decoder->private_->has_stream_info)
2311 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2313 is_unparseable = true;
2316 decoder->private_->frame.header.bits_per_sample = 8;
2319 decoder->private_->frame.header.bits_per_sample = 12;
2322 decoder->private_->frame.header.bits_per_sample = 16;
2325 decoder->private_->frame.header.bits_per_sample = 20;
2328 decoder->private_->frame.header.bits_per_sample = 24;
2332 is_unparseable = true;
2339 /* check to make sure that reserved bit is 0 */
2340 if(raw_header[3] & 0x01) /* MAGIC NUMBER */
2341 is_unparseable = true;
2343 /* read the frame's starting sample number (or frame number as the case may be) */
2345 raw_header[1] & 0x01 ||
2346 /*@@@ 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 */
2347 (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
2348 ) { /* variable blocksize */
2349 if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
2350 return false; /* read_callback_ sets the state for us */
2351 if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
2352 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2353 decoder->private_->cached = true;
2354 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2355 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2358 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2359 decoder->private_->frame.header.number.sample_number = xx;
2361 else { /* fixed blocksize */
2362 if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
2363 return false; /* read_callback_ sets the state for us */
2364 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
2365 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2366 decoder->private_->cached = true;
2367 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2368 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2371 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2372 decoder->private_->frame.header.number.frame_number = x;
2375 if(blocksize_hint) {
2376 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2377 return false; /* read_callback_ sets the state for us */
2378 raw_header[raw_header_len++] = (FLAC__byte)x;
2379 if(blocksize_hint == 7) {
2381 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2382 return false; /* read_callback_ sets the state for us */
2383 raw_header[raw_header_len++] = (FLAC__byte)_x;
2386 decoder->private_->frame.header.blocksize = x+1;
2389 if(sample_rate_hint) {
2390 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2391 return false; /* read_callback_ sets the state for us */
2392 raw_header[raw_header_len++] = (FLAC__byte)x;
2393 if(sample_rate_hint != 12) {
2395 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2396 return false; /* read_callback_ sets the state for us */
2397 raw_header[raw_header_len++] = (FLAC__byte)_x;
2400 if(sample_rate_hint == 12)
2401 decoder->private_->frame.header.sample_rate = x*1000;
2402 else if(sample_rate_hint == 13)
2403 decoder->private_->frame.header.sample_rate = x;
2405 decoder->private_->frame.header.sample_rate = x*10;
2408 /* read the CRC-8 byte */
2409 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2410 return false; /* read_callback_ sets the state for us */
2411 crc8 = (FLAC__byte)x;
2413 if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
2414 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2415 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2419 /* calculate the sample number from the frame number if needed */
2420 decoder->private_->next_fixed_block_size = 0;
2421 if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
2422 x = decoder->private_->frame.header.number.frame_number;
2423 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2424 if(decoder->private_->fixed_block_size)
2425 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
2426 else if(decoder->private_->has_stream_info) {
2427 if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
2428 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
2429 decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
2432 is_unparseable = true;
2435 decoder->private_->frame.header.number.sample_number = 0;
2436 decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
2439 /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
2440 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
2444 if(is_unparseable) {
2445 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2446 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2453 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2456 FLAC__bool wasted_bits;
2459 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
2460 return false; /* read_callback_ sets the state for us */
2462 wasted_bits = (x & 1);
2467 if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
2468 return false; /* read_callback_ sets the state for us */
2469 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
2470 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
2473 decoder->private_->frame.subframes[channel].wasted_bits = 0;
2476 * Lots of magic numbers here
2479 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2480 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2484 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2488 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2492 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2493 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2497 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2499 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2503 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2504 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2508 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2510 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2514 if(wasted_bits && do_full_decode) {
2515 x = decoder->private_->frame.subframes[channel].wasted_bits;
2516 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2517 decoder->private_->output[channel][i] <<= x;
2523 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2525 FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2528 FLAC__int32 *output = decoder->private_->output[channel];
2530 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2532 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2533 return false; /* read_callback_ sets the state for us */
2535 subframe->value = x;
2537 /* decode the subframe */
2538 if(do_full_decode) {
2539 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2546 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2548 FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2553 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2555 subframe->residual = decoder->private_->residual[channel];
2556 subframe->order = order;
2558 /* read warm-up samples */
2559 for(u = 0; u < order; u++) {
2560 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2561 return false; /* read_callback_ sets the state for us */
2562 subframe->warmup[u] = i32;
2565 /* read entropy coding method info */
2566 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2567 return false; /* read_callback_ sets the state for us */
2568 subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2569 switch(subframe->entropy_coding_method.type) {
2570 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2571 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2572 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2573 return false; /* read_callback_ sets the state for us */
2574 subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2575 subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2578 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2579 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2584 switch(subframe->entropy_coding_method.type) {
2585 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2586 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2587 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))
2594 /* decode the subframe */
2595 if(do_full_decode) {
2596 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2597 FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
2603 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2605 FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2610 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2612 subframe->residual = decoder->private_->residual[channel];
2613 subframe->order = order;
2615 /* read warm-up samples */
2616 for(u = 0; u < order; u++) {
2617 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2618 return false; /* read_callback_ sets the state for us */
2619 subframe->warmup[u] = i32;
2622 /* read qlp coeff precision */
2623 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
2624 return false; /* read_callback_ sets the state for us */
2625 if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
2626 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2627 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2630 subframe->qlp_coeff_precision = u32+1;
2632 /* read qlp shift */
2633 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
2634 return false; /* read_callback_ sets the state for us */
2635 subframe->quantization_level = i32;
2637 /* read quantized lp coefficiencts */
2638 for(u = 0; u < order; u++) {
2639 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
2640 return false; /* read_callback_ sets the state for us */
2641 subframe->qlp_coeff[u] = i32;
2644 /* read entropy coding method info */
2645 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2646 return false; /* read_callback_ sets the state for us */
2647 subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2648 switch(subframe->entropy_coding_method.type) {
2649 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2650 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2651 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2652 return false; /* read_callback_ sets the state for us */
2653 subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2654 subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2657 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2658 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2663 switch(subframe->entropy_coding_method.type) {
2664 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2665 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2666 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))
2673 /* decode the subframe */
2674 if(do_full_decode) {
2675 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2676 /*@@@@@@ technically not pessimistic enough, should be more like
2677 if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
2679 if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2680 if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2682 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);
2684 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);
2687 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);
2689 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);
2695 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2697 FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2698 FLAC__int32 x, *residual = decoder->private_->residual[channel];
2701 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2703 subframe->data = residual;
2705 for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2706 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2707 return false; /* read_callback_ sets the state for us */
2711 /* decode the subframe */
2713 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2718 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)
2720 FLAC__uint32 rice_parameter;
2722 unsigned partition, sample, u;
2723 const unsigned partitions = 1u << partition_order;
2724 const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2725 const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
2726 const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
2729 if(partition_order == 0) {
2730 if(decoder->private_->frame.header.blocksize < predictor_order) {
2731 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2732 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2737 if(partition_samples < predictor_order) {
2738 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2739 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2744 if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2745 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2750 for(partition = 0; partition < partitions; partition++) {
2751 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
2752 return false; /* read_callback_ sets the state for us */
2753 partitioned_rice_contents->parameters[partition] = rice_parameter;
2754 if(rice_parameter < pesc) {
2755 partitioned_rice_contents->raw_bits[partition] = 0;
2756 u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2757 if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter))
2758 return false; /* read_callback_ sets the state for us */
2762 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
2763 return false; /* read_callback_ sets the state for us */
2764 partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2765 for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2766 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i, rice_parameter))
2767 return false; /* read_callback_ sets the state for us */
2768 residual[sample] = i;
2776 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2778 if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
2779 FLAC__uint32 zero = 0;
2780 if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
2781 return false; /* read_callback_ sets the state for us */
2783 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2784 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2790 FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
2792 FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2796 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2797 !decoder->private_->is_ogg &&
2799 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2802 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2805 else if(*bytes > 0) {
2806 /* While seeking, it is possible for our seek to land in the
2807 * middle of audio data that looks exactly like a frame header
2808 * from a future version of an encoder. When that happens, our
2809 * error callback will get an
2810 * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
2811 * unparseable_frame_count. But there is a remote possibility
2812 * that it is properly synced at such a "future-codec frame",
2813 * so to make sure, we wait to see many "unparseable" errors in
2814 * a row before bailing out.
2816 if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2817 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2821 const FLAC__StreamDecoderReadStatus status =
2823 decoder->private_->is_ogg?
2824 read_callback_ogg_aspect_(decoder, buffer, bytes) :
2826 decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
2828 if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
2829 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2832 else if(*bytes == 0) {
2834 status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
2837 /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2838 !decoder->private_->is_ogg &&
2840 decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2843 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2854 /* abort to avoid a deadlock */
2855 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2858 /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
2859 * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
2860 * and at the same time hit the end of the stream (for example, seeking
2861 * to a point that is after the beginning of the last Ogg page). There
2862 * is no way to report an Ogg sync loss through the callbacks (see note
2863 * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
2864 * So to keep the decoder from stopping at this point we gate the call
2865 * to the eof_callback and let the Ogg decoder aspect set the
2866 * end-of-stream state when it is needed.
2871 FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
2873 switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
2874 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
2875 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2876 /* we don't really have a way to handle lost sync via read
2877 * callback so we'll let it pass and let the underlying
2878 * FLAC decoder catch the error
2880 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
2881 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2882 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
2883 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2884 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
2885 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
2886 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
2887 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
2888 case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
2889 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2892 /* double protection */
2893 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2897 FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
2899 FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
2901 switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
2902 case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
2903 return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
2904 case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
2905 return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
2906 case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
2907 return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2909 /* double protection: */
2911 return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2916 FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2918 if(decoder->private_->is_seeking) {
2919 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
2920 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
2921 FLAC__uint64 target_sample = decoder->private_->target_sample;
2923 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2926 decoder->private_->got_a_frame = true;
2928 decoder->private_->last_frame = *frame; /* save the frame */
2929 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
2930 unsigned delta = (unsigned)(target_sample - this_frame_sample);
2931 /* kick out of seek mode */
2932 decoder->private_->is_seeking = false;
2933 /* shift out the samples before target_sample */
2936 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
2937 for(channel = 0; channel < frame->header.channels; channel++)
2938 newbuffer[channel] = buffer[channel] + delta;
2939 decoder->private_->last_frame.header.blocksize -= delta;
2940 decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
2941 /* write the relevant samples */
2942 return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
2945 /* write the relevant samples */
2946 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2950 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2955 * If we never got STREAMINFO, turn off MD5 checking to save
2956 * cycles since we don't have a sum to compare to anyway
2958 if(!decoder->private_->has_stream_info)
2959 decoder->private_->do_md5_checking = false;
2960 if(decoder->private_->do_md5_checking) {
2961 if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
2962 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2964 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2968 void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2970 if(!decoder->private_->is_seeking)
2971 decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
2972 else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
2973 decoder->private_->unparseable_frame_count++;
2976 FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2978 FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
2979 FLAC__int64 pos = -1;
2981 unsigned approx_bytes_per_frame;
2982 FLAC__bool first_seek = true;
2983 const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
2984 const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2985 const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
2986 const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
2987 const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
2988 /* take these from the current frame in case they've changed mid-stream */
2989 unsigned channels = FLAC__stream_decoder_get_channels(decoder);
2990 unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
2991 const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
2993 /* use values from stream info if we didn't decode a frame */
2995 channels = decoder->private_->stream_info.data.stream_info.channels;
2997 bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2999 /* we are just guessing here */
3000 if(max_framesize > 0)
3001 approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
3003 * Check if it's a known fixed-blocksize stream. Note that though
3004 * the spec doesn't allow zeroes in the STREAMINFO block, we may
3005 * never get a STREAMINFO block when decoding so the value of
3006 * min_blocksize might be zero.
3008 else if(min_blocksize == max_blocksize && min_blocksize > 0) {
3009 /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
3010 approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
3013 approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
3016 * First, we set an upper and lower bound on where in the
3017 * stream we will search. For now we assume the worst case
3018 * scenario, which is our best guess at the beginning of
3019 * the first frame and end of the stream.
3021 lower_bound = first_frame_offset;
3022 lower_bound_sample = 0;
3023 upper_bound = stream_length;
3024 upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
3027 * Now we refine the bounds if we have a seektable with
3028 * suitable points. Note that according to the spec they
3029 * must be ordered by ascending sample number.
3031 * Note: to protect against invalid seek tables we will ignore points
3032 * that have frame_samples==0 or sample_number>=total_samples
3035 FLAC__uint64 new_lower_bound = lower_bound;
3036 FLAC__uint64 new_upper_bound = upper_bound;
3037 FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
3038 FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
3040 /* find the closest seek point <= target_sample, if it exists */
3041 for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
3043 seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
3044 seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
3045 (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
3046 seek_table->points[i].sample_number <= target_sample
3050 if(i >= 0) { /* i.e. we found a suitable seek point... */
3051 new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
3052 new_lower_bound_sample = seek_table->points[i].sample_number;
3055 /* find the closest seek point > target_sample, if it exists */
3056 for(i = 0; i < (int)seek_table->num_points; i++) {
3058 seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
3059 seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
3060 (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
3061 seek_table->points[i].sample_number > target_sample
3065 if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
3066 new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
3067 new_upper_bound_sample = seek_table->points[i].sample_number;
3069 /* final protection against unsorted seek tables; keep original values if bogus */
3070 if(new_upper_bound >= new_lower_bound) {
3071 lower_bound = new_lower_bound;
3072 upper_bound = new_upper_bound;
3073 lower_bound_sample = new_lower_bound_sample;
3074 upper_bound_sample = new_upper_bound_sample;
3078 FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
3079 /* there are 2 insidious ways that the following equality occurs, which
3081 * 1) total_samples is 0 (unknown) and target_sample is 0
3082 * 2) total_samples is 0 (unknown) and target_sample happens to be
3083 * exactly equal to the last seek point in the seek table; this
3084 * means there is no seek point above it, and upper_bound_samples
3085 * remains equal to the estimate (of target_samples) we made above
3086 * in either case it does not hurt to move upper_bound_sample up by 1
3088 if(upper_bound_sample == lower_bound_sample)
3089 upper_bound_sample++;
3091 decoder->private_->target_sample = target_sample;
3093 /* check if the bounds are still ok */
3094 if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
3095 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3098 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3099 #if defined _MSC_VER || defined __MINGW32__
3100 /* with VC++ you have to spoon feed it the casting */
3101 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;
3103 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;
3106 /* a little less accurate: */
3107 if(upper_bound - lower_bound < 0xffffffff)
3108 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;
3109 else /* @@@ WATCHOUT, ~2TB limit */
3110 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;
3112 if(pos >= (FLAC__int64)upper_bound)
3113 pos = (FLAC__int64)upper_bound - 1;
3114 if(pos < (FLAC__int64)lower_bound)
3115 pos = (FLAC__int64)lower_bound;
3116 if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3117 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3120 if(!FLAC__stream_decoder_flush(decoder)) {
3121 /* above call sets the state for us */
3124 /* Now we need to get a frame. First we need to reset our
3125 * unparseable_frame_count; if we get too many unparseable
3126 * frames in a row, the read callback will return
3127 * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
3128 * FLAC__stream_decoder_process_single() to return false.
3130 decoder->private_->unparseable_frame_count = 0;
3131 if(!FLAC__stream_decoder_process_single(decoder)) {
3132 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3135 /* our write callback will change the state when it gets to the target frame */
3136 /* 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 */
3138 /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
3139 if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
3142 if(!decoder->private_->is_seeking)
3145 FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3146 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3148 if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
3149 if (pos == (FLAC__int64)lower_bound) {
3150 /* can't move back any more than the first frame, something is fatally wrong */
3151 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3154 /* our last move backwards wasn't big enough, try again */
3155 approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
3158 /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
3161 /* make sure we are not seeking in corrupted stream */
3162 if (this_frame_sample < lower_bound_sample) {
3163 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3167 /* we need to narrow the search */
3168 if(target_sample < this_frame_sample) {
3169 upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
3170 /*@@@@@@ what will decode position be if at end of stream? */
3171 if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
3172 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3175 approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
3177 else { /* target_sample >= this_frame_sample + this frame's blocksize */
3178 lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
3179 if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
3180 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3183 approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
3191 FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
3193 FLAC__uint64 left_pos = 0, right_pos = stream_length;
3194 FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
3195 FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
3196 FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
3197 FLAC__bool did_a_seek;
3198 unsigned iteration = 0;
3200 /* In the first iterations, we will calculate the target byte position
3201 * by the distance from the target sample to left_sample and
3202 * right_sample (let's call it "proportional search"). After that, we
3203 * will switch to binary search.
3205 unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
3207 /* We will switch to a linear search once our current sample is less
3208 * than this number of samples ahead of the target sample
3210 static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
3212 /* If the total number of samples is unknown, use a large value, and
3213 * force binary search immediately.
3215 if(right_sample == 0) {
3216 right_sample = (FLAC__uint64)(-1);
3217 BINARY_SEARCH_AFTER_ITERATION = 0;
3220 decoder->private_->target_sample = target_sample;
3221 for( ; ; iteration++) {
3222 if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
3223 if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
3224 pos = (right_pos + left_pos) / 2;
3227 #ifndef FLAC__INTEGER_ONLY_LIBRARY
3228 #if defined _MSC_VER || defined __MINGW32__
3229 /* with MSVC you have to spoon feed it the casting */
3230 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));
3232 pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
3235 /* a little less accurate: */
3236 if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
3237 pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
3238 else /* @@@ WATCHOUT, ~2TB limit */
3239 pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
3241 /* @@@ TODO: might want to limit pos to some distance
3242 * before EOF, to make sure we land before the last frame,
3243 * thereby getting a this_frame_sample and so having a better
3249 if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3250 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3253 if(!FLAC__stream_decoder_flush(decoder)) {
3254 /* above call sets the state for us */
3262 decoder->private_->got_a_frame = false;
3263 if(!FLAC__stream_decoder_process_single(decoder)) {
3264 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3267 if(!decoder->private_->got_a_frame) {
3269 /* this can happen if we seek to a point after the last frame; we drop
3270 * to binary search right away in this case to avoid any wasted
3271 * iterations of proportional search.
3274 BINARY_SEARCH_AFTER_ITERATION = 0;
3277 /* this can probably only happen if total_samples is unknown and the
3278 * target_sample is past the end of the stream
3280 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3284 /* our write callback will change the state when it gets to the target frame */
3285 else if(!decoder->private_->is_seeking) {
3289 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3290 FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3293 if (this_frame_sample <= target_sample) {
3294 /* The 'equal' case should not happen, since
3295 * FLAC__stream_decoder_process_single()
3296 * should recognize that it has hit the
3297 * target sample and we would exit through
3298 * the 'break' above.
3300 FLAC__ASSERT(this_frame_sample != target_sample);
3302 left_sample = this_frame_sample;
3303 /* sanity check to avoid infinite loop */
3304 if (left_pos == pos) {
3305 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3310 else if(this_frame_sample > target_sample) {
3311 right_sample = this_frame_sample;
3312 /* sanity check to avoid infinite loop */
3313 if (right_pos == pos) {
3314 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3327 FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
3332 *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
3333 if(ferror(decoder->private_->file))
3334 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
3335 else if(*bytes == 0)
3336 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
3338 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
3341 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
3344 FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
3348 if(decoder->private_->file == stdin)
3349 return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
3350 else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
3351 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
3353 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
3356 FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
3361 if(decoder->private_->file == stdin)
3362 return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
3363 else if((pos = ftello(decoder->private_->file)) < 0)
3364 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
3366 *absolute_byte_offset = (FLAC__uint64)pos;
3367 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
3371 FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
3373 struct stat filestats;
3376 if(decoder->private_->file == stdin)
3377 return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
3378 else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
3379 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
3381 *stream_length = (FLAC__uint64)filestats.st_size;
3382 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
3386 FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
3390 return feof(decoder->private_->file)? true : false;