1 /* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006 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 __MINGW32__
50 /*@@@ [2G limit] hacks for MSVC6 */
54 #include "FLAC/assert.h"
55 #include "protected/stream_decoder.h"
56 #include "private/bitbuffer.h"
57 #include "private/bitmath.h"
58 #include "private/cpu.h"
59 #include "private/crc.h"
60 #include "private/fixed.h"
61 #include "private/format.h"
62 #include "private/lpc.h"
63 #include "private/md5.h"
64 #include "private/memory.h"
66 #undef OLD_STAT_WAY /*@@@@@@ old way of keeping the filename and using stat(); remove remnants once we know this works */
71 #define max(a,b) ((a)>(b)?(a):(b))
73 /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
75 #define FLAC__U64L(x) x
77 #define FLAC__U64L(x) x##LLU
80 /***********************************************************************
84 ***********************************************************************/
86 static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
88 /***********************************************************************
90 * Private class method prototypes
92 ***********************************************************************/
94 static void set_defaults_(FLAC__StreamDecoder *decoder);
95 static FILE *get_binary_stdin_();
96 static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
97 static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
98 static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
99 static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
100 static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
101 static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
102 static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
103 static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
104 static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
105 static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
106 static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
107 static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
108 static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
109 static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
110 static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
111 static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
112 static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
113 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);
114 static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
115 static FLAC__bool read_callback_(FLAC__byte buffer[], unsigned *bytes, void *client_data);
116 static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
117 static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
118 static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
119 static FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
120 static FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
121 static FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
122 static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
123 static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
125 /***********************************************************************
129 ***********************************************************************/
131 typedef struct FLAC__StreamDecoderPrivate {
132 FLAC__StreamDecoderReadCallback read_callback;
133 FLAC__StreamDecoderSeekCallback seek_callback;
134 FLAC__StreamDecoderTellCallback tell_callback;
135 FLAC__StreamDecoderLengthCallback length_callback;
136 FLAC__StreamDecoderEofCallback eof_callback;
137 FLAC__StreamDecoderWriteCallback write_callback;
138 FLAC__StreamDecoderMetadataCallback metadata_callback;
139 FLAC__StreamDecoderErrorCallback error_callback;
140 /* generic 32-bit datapath: */
141 void (*local_lpc_restore_signal)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
142 /* generic 64-bit datapath: */
143 void (*local_lpc_restore_signal_64bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
144 /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
145 void (*local_lpc_restore_signal_16bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
146 /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit), AND order <= 8: */
147 void (*local_lpc_restore_signal_16bit_order8)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
149 FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
151 char *filename; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
153 FLAC__BitBuffer *input;
154 FLAC__int32 *output[FLAC__MAX_CHANNELS];
155 FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
156 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
157 unsigned output_capacity, output_channels;
158 FLAC__uint32 last_frame_number;
159 FLAC__uint32 last_block_size;
160 FLAC__uint64 samples_decoded;
161 FLAC__bool has_stream_info, has_seek_table;
162 FLAC__StreamMetadata stream_info;
163 FLAC__StreamMetadata seek_table;
164 FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
165 FLAC__byte *metadata_filter_ids;
166 unsigned metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
168 FLAC__bool cached; /* true if there is a byte in lookahead */
169 FLAC__CPUInfo cpuinfo;
170 FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
171 FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
172 /* unaligned (original) pointers to allocated data */
173 FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
174 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 */
175 FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
176 FLAC__bool is_seeking;
177 struct FLAC__MD5Context md5context;
178 FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
179 /* (the rest of these are only used for seeking) */
180 FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
181 FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
182 FLAC__uint64 target_sample;
183 unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
184 } FLAC__StreamDecoderPrivate;
186 /***********************************************************************
188 * Public static class data
190 ***********************************************************************/
192 FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
193 "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
194 "FLAC__STREAM_DECODER_READ_METADATA",
195 "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
196 "FLAC__STREAM_DECODER_READ_FRAME",
197 "FLAC__STREAM_DECODER_END_OF_STREAM",
198 "FLAC__STREAM_DECODER_SEEK_ERROR",
199 "FLAC__STREAM_DECODER_ABORTED",
200 "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
201 "FLAC__STREAM_DECODER_UNINITIALIZED"
204 FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
205 "FLAC__STREAM_DECODER_INIT_STATUS_OK",
206 "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
207 "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
208 "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
209 "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
212 FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
213 "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
214 "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
215 "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
218 FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
219 "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
220 "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
221 "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
224 FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
225 "FLAC__STREAM_DECODER_TELL_STATUS_OK",
226 "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
227 "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
230 FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
231 "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
232 "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
233 "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
236 FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
237 "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
238 "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
241 FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
242 "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
243 "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
244 "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
245 "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
248 /***********************************************************************
250 * Class constructor/destructor
252 ***********************************************************************/
253 FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new()
255 FLAC__StreamDecoder *decoder;
258 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
260 decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
265 decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
266 if(decoder->protected_ == 0) {
271 decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
272 if(decoder->private_ == 0) {
273 free(decoder->protected_);
278 decoder->private_->input = FLAC__bitbuffer_new();
279 if(decoder->private_->input == 0) {
280 free(decoder->private_);
281 free(decoder->protected_);
286 decoder->private_->metadata_filter_ids_capacity = 16;
287 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
288 FLAC__bitbuffer_delete(decoder->private_->input);
289 free(decoder->private_);
290 free(decoder->protected_);
295 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
296 decoder->private_->output[i] = 0;
297 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
300 decoder->private_->output_capacity = 0;
301 decoder->private_->output_channels = 0;
302 decoder->private_->has_seek_table = false;
304 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
305 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
307 decoder->private_->file = 0;
309 set_defaults_(decoder);
311 decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
316 FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
320 FLAC__ASSERT(0 != decoder);
321 FLAC__ASSERT(0 != decoder->protected_);
322 FLAC__ASSERT(0 != decoder->private_);
323 FLAC__ASSERT(0 != decoder->private_->input);
325 FLAC__stream_decoder_finish(decoder);
327 if(0 != decoder->private_->metadata_filter_ids)
328 free(decoder->private_->metadata_filter_ids);
330 FLAC__bitbuffer_delete(decoder->private_->input);
332 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
333 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
335 free(decoder->private_);
336 free(decoder->protected_);
340 /***********************************************************************
342 * Public class methods
344 ***********************************************************************/
346 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
347 FLAC__StreamDecoder *decoder,
348 FLAC__StreamDecoderReadCallback read_callback,
349 FLAC__StreamDecoderSeekCallback seek_callback,
350 FLAC__StreamDecoderTellCallback tell_callback,
351 FLAC__StreamDecoderLengthCallback length_callback,
352 FLAC__StreamDecoderEofCallback eof_callback,
353 FLAC__StreamDecoderWriteCallback write_callback,
354 FLAC__StreamDecoderMetadataCallback metadata_callback,
355 FLAC__StreamDecoderErrorCallback error_callback,
359 FLAC__ASSERT(0 != decoder);
361 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
362 return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
365 0 == read_callback ||
366 0 == write_callback ||
367 0 == error_callback ||
368 (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
370 return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
373 * get the CPU info and set the function pointers
375 FLAC__cpu_info(&decoder->private_->cpuinfo);
376 /* first default to the non-asm routines */
377 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
378 decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
379 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
380 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
381 /* now override with asm where appropriate */
383 if(decoder->private_->cpuinfo.use_asm) {
384 #ifdef FLAC__CPU_IA32
385 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
386 #ifdef FLAC__HAS_NASM
387 if(decoder->private_->cpuinfo.data.ia32.mmx) {
388 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
389 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
390 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
393 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
394 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
395 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
398 #elif defined FLAC__CPU_PPC
399 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
400 if(decoder->private_->cpuinfo.data.ppc.altivec) {
401 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
402 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
408 /* from here on, errors are fatal */
410 if(!FLAC__bitbuffer_init(decoder->private_->input)) {
411 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
412 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
415 decoder->private_->read_callback = read_callback;
416 decoder->private_->seek_callback = seek_callback;
417 decoder->private_->tell_callback = tell_callback;
418 decoder->private_->length_callback = length_callback;
419 decoder->private_->eof_callback = eof_callback;
420 decoder->private_->write_callback = write_callback;
421 decoder->private_->metadata_callback = metadata_callback;
422 decoder->private_->error_callback = error_callback;
423 decoder->private_->client_data = client_data;
424 decoder->private_->last_frame_number = 0;
425 decoder->private_->last_block_size = 0;
426 decoder->private_->samples_decoded = 0;
427 decoder->private_->has_stream_info = false;
428 decoder->private_->cached = false;
430 decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
431 decoder->private_->is_seeking = false;
433 decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
434 if(!FLAC__stream_decoder_reset(decoder)) {
435 /* above call sets the state for us */
436 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
439 return FLAC__STREAM_DECODER_INIT_STATUS_OK;
442 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
443 FLAC__StreamDecoder *decoder,
445 FLAC__StreamDecoderWriteCallback write_callback,
446 FLAC__StreamDecoderMetadataCallback metadata_callback,
447 FLAC__StreamDecoderErrorCallback error_callback,
451 FLAC__ASSERT(0 != decoder);
452 FLAC__ASSERT(0 != file);
454 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
455 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
457 if(0 == write_callback || 0 == error_callback)
458 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
461 * To make sure that our file does not go unclosed after an error, we
462 * must assign the FILE pointer before any further error can occur in
466 file = get_binary_stdin_(); /* just to be safe */
468 decoder->private_->file = file;
471 if(0 != decoder->private_->filename) {
472 free(decoder->private_->filename);
473 decoder->private_->filename = 0;
476 if(0 == (decoder->private_->filename = strdup(filename))) {
477 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
478 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
483 return FLAC__stream_decoder_init_stream(
486 decoder->private_->file == stdin? 0: file_seek_callback_,
487 decoder->private_->file == stdin? 0: file_tell_callback_,/*@@@@@@ might work for stdin*/
488 decoder->private_->file == stdin? 0: file_length_callback_,
489 decoder->private_->file == stdin? 0: file_eof_callback_,/*@@@@@@ might work for stdin*/
497 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
498 FLAC__StreamDecoder *decoder,
499 const char *filename,
500 FLAC__StreamDecoderWriteCallback write_callback,
501 FLAC__StreamDecoderMetadataCallback metadata_callback,
502 FLAC__StreamDecoderErrorCallback error_callback,
508 FLAC__ASSERT(0 != decoder);
511 * To make sure that our file does not go unclosed after an error, we
512 * have to do the same entrance checks here that are later performed
513 * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
515 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
516 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
518 if(0 == write_callback || 0 == error_callback)
519 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
521 file = filename? fopen(filename, "rb") : stdin;
524 return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
527 if(0 != decoder->private_->filename) {
528 free(decoder->private_->filename);
529 decoder->private_->filename = 0;
532 if(0 == (decoder->private_->filename = strdup(filename))) {
533 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
534 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
539 return FLAC__stream_decoder_init_FILE(decoder, file, write_callback, metadata_callback, error_callback, client_data);
542 FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
544 FLAC__bool md5_failed = false;
547 FLAC__ASSERT(0 != decoder);
548 FLAC__ASSERT(0 != decoder->private_);
549 FLAC__ASSERT(0 != decoder->protected_);
551 if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
554 /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
555 * always call FLAC__MD5Final()
557 FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
559 if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
560 free(decoder->private_->seek_table.data.seek_table.points);
561 decoder->private_->seek_table.data.seek_table.points = 0;
562 decoder->private_->has_seek_table = false;
564 FLAC__bitbuffer_free(decoder->private_->input);
565 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
567 * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
568 * output arrays have a buffer of up to 3 zeroes in front
569 * (at negative indices) for alignment purposes; we use 4
570 * to keep the data well-aligned.
572 if(0 != decoder->private_->output[i]) {
573 free(decoder->private_->output[i]-4);
574 decoder->private_->output[i] = 0;
576 if(0 != decoder->private_->residual_unaligned[i]) {
577 free(decoder->private_->residual_unaligned[i]);
578 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
581 decoder->private_->output_capacity = 0;
582 decoder->private_->output_channels = 0;
584 if(0 != decoder->private_->file && decoder->private_->file != stdin) {
585 fclose(decoder->private_->file);
586 decoder->private_->file = 0;
590 if(0 != decoder->private_->filename) {
591 free(decoder->private_->filename);
592 decoder->private_->filename = 0;
596 if(decoder->private_->do_md5_checking) {
597 if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
600 decoder->private_->is_seeking = false;
602 set_defaults_(decoder);
604 decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
609 FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
611 FLAC__ASSERT(0 != decoder);
612 FLAC__ASSERT(0 != decoder->protected_);
613 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
615 decoder->protected_->md5_checking = value;
619 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
621 FLAC__ASSERT(0 != decoder);
622 FLAC__ASSERT(0 != decoder->private_);
623 FLAC__ASSERT(0 != decoder->protected_);
624 FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
625 /* double protection */
626 if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
628 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
630 decoder->private_->metadata_filter[type] = true;
631 if(type == FLAC__METADATA_TYPE_APPLICATION)
632 decoder->private_->metadata_filter_ids_count = 0;
636 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
638 FLAC__ASSERT(0 != decoder);
639 FLAC__ASSERT(0 != decoder->private_);
640 FLAC__ASSERT(0 != decoder->protected_);
641 FLAC__ASSERT(0 != id);
642 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
645 if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
648 FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
650 if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
651 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2))) {
652 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
655 decoder->private_->metadata_filter_ids_capacity *= 2;
658 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));
659 decoder->private_->metadata_filter_ids_count++;
664 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
667 FLAC__ASSERT(0 != decoder);
668 FLAC__ASSERT(0 != decoder->private_);
669 FLAC__ASSERT(0 != decoder->protected_);
670 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
672 for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
673 decoder->private_->metadata_filter[i] = true;
674 decoder->private_->metadata_filter_ids_count = 0;
678 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
680 FLAC__ASSERT(0 != decoder);
681 FLAC__ASSERT(0 != decoder->private_);
682 FLAC__ASSERT(0 != decoder->protected_);
683 FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
684 /* double protection */
685 if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
687 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
689 decoder->private_->metadata_filter[type] = false;
690 if(type == FLAC__METADATA_TYPE_APPLICATION)
691 decoder->private_->metadata_filter_ids_count = 0;
695 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
697 FLAC__ASSERT(0 != decoder);
698 FLAC__ASSERT(0 != decoder->private_);
699 FLAC__ASSERT(0 != decoder->protected_);
700 FLAC__ASSERT(0 != id);
701 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
704 if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
707 FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
709 if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
710 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2))) {
711 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
714 decoder->private_->metadata_filter_ids_capacity *= 2;
717 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));
718 decoder->private_->metadata_filter_ids_count++;
723 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
725 FLAC__ASSERT(0 != decoder);
726 FLAC__ASSERT(0 != decoder->private_);
727 FLAC__ASSERT(0 != decoder->protected_);
728 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
730 memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
731 decoder->private_->metadata_filter_ids_count = 0;
735 FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
737 FLAC__ASSERT(0 != decoder);
738 FLAC__ASSERT(0 != decoder->protected_);
739 return decoder->protected_->state;
742 FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
744 return FLAC__StreamDecoderStateString[decoder->protected_->state];
747 FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
749 FLAC__ASSERT(0 != decoder);
750 FLAC__ASSERT(0 != decoder->protected_);
751 return decoder->protected_->md5_checking;
754 FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
756 FLAC__ASSERT(0 != decoder);
757 FLAC__ASSERT(0 != decoder->protected_);
758 return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
761 FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
763 FLAC__ASSERT(0 != decoder);
764 FLAC__ASSERT(0 != decoder->protected_);
765 return decoder->protected_->channels;
768 FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
770 FLAC__ASSERT(0 != decoder);
771 FLAC__ASSERT(0 != decoder->protected_);
772 return decoder->protected_->channel_assignment;
775 FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
777 FLAC__ASSERT(0 != decoder);
778 FLAC__ASSERT(0 != decoder->protected_);
779 return decoder->protected_->bits_per_sample;
782 FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
784 FLAC__ASSERT(0 != decoder);
785 FLAC__ASSERT(0 != decoder->protected_);
786 return decoder->protected_->sample_rate;
789 FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
791 FLAC__ASSERT(0 != decoder);
792 FLAC__ASSERT(0 != decoder->protected_);
793 return decoder->protected_->blocksize;
796 FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
798 FLAC__ASSERT(0 != decoder);
799 FLAC__ASSERT(0 != decoder->private_);
800 FLAC__ASSERT(0 != position);
802 if(0 == decoder->private_->tell_callback)
804 if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
806 FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
807 *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
811 FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
813 FLAC__ASSERT(0 != decoder);
814 FLAC__ASSERT(0 != decoder->private_);
815 FLAC__ASSERT(0 != decoder->protected_);
817 decoder->private_->samples_decoded = 0;
818 decoder->private_->do_md5_checking = false;
820 if(!FLAC__bitbuffer_clear(decoder->private_->input)) {
821 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
824 decoder->private_->last_frame_number = 0;
825 decoder->private_->last_block_size = 0;
826 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
831 FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
833 FLAC__ASSERT(0 != decoder);
834 FLAC__ASSERT(0 != decoder->private_);
835 FLAC__ASSERT(0 != decoder->protected_);
837 if(!FLAC__stream_decoder_flush(decoder)) {
838 /* above call sets the state for us */
842 /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
843 * (internal_reset_hack) don't try to rewind since we are already at
844 * the beginning of the stream and don't want to fail if the input is
847 if(!decoder->private_->internal_reset_hack) {
848 if(decoder->private_->file == stdin)
849 return false; /* can't rewind stdin, reset fails */
850 if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
851 return false; /* seekable and seek fails, reset fails */
854 decoder->private_->internal_reset_hack = false;
856 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
858 decoder->private_->has_stream_info = false;
859 if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
860 free(decoder->private_->seek_table.data.seek_table.points);
861 decoder->private_->seek_table.data.seek_table.points = 0;
862 decoder->private_->has_seek_table = false;
864 decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
866 /* We initialize the FLAC__MD5Context even though we may never use it. This
867 * is because md5 checking may be turned on to start and then turned off if
868 * a seek occurs. So we init the context here and finalize it in
869 * FLAC__seekable_stream_decoder_finish() to make sure things are always
870 * cleaned up properly.
872 FLAC__MD5Init(&decoder->private_->md5context);
874 decoder->private_->first_frame_offset = 0;
875 decoder->private_->unparseable_frame_count = 0;
880 FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
882 FLAC__bool got_a_frame;
883 FLAC__ASSERT(0 != decoder);
884 FLAC__ASSERT(0 != decoder->protected_);
887 switch(decoder->protected_->state) {
888 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
889 if(!find_metadata_(decoder))
890 return false; /* above function sets the status for us */
892 case FLAC__STREAM_DECODER_READ_METADATA:
893 if(!read_metadata_(decoder))
894 return false; /* above function sets the status for us */
897 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
898 if(!frame_sync_(decoder))
899 return true; /* above function sets the status for us */
901 case FLAC__STREAM_DECODER_READ_FRAME:
902 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
903 return false; /* above function sets the status for us */
905 return true; /* above function sets the status for us */
907 case FLAC__STREAM_DECODER_END_OF_STREAM:
908 case FLAC__STREAM_DECODER_ABORTED:
917 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
919 FLAC__ASSERT(0 != decoder);
920 FLAC__ASSERT(0 != decoder->protected_);
923 switch(decoder->protected_->state) {
924 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
925 if(!find_metadata_(decoder))
926 return false; /* above function sets the status for us */
928 case FLAC__STREAM_DECODER_READ_METADATA:
929 if(!read_metadata_(decoder))
930 return false; /* above function sets the status for us */
932 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
933 case FLAC__STREAM_DECODER_READ_FRAME:
934 case FLAC__STREAM_DECODER_END_OF_STREAM:
935 case FLAC__STREAM_DECODER_ABORTED:
944 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
947 FLAC__ASSERT(0 != decoder);
948 FLAC__ASSERT(0 != decoder->protected_);
951 switch(decoder->protected_->state) {
952 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
953 if(!find_metadata_(decoder))
954 return false; /* above function sets the status for us */
956 case FLAC__STREAM_DECODER_READ_METADATA:
957 if(!read_metadata_(decoder))
958 return false; /* above function sets the status for us */
960 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
961 if(!frame_sync_(decoder))
962 return true; /* above function sets the status for us */
964 case FLAC__STREAM_DECODER_READ_FRAME:
965 if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
966 return false; /* above function sets the status for us */
968 case FLAC__STREAM_DECODER_END_OF_STREAM:
969 case FLAC__STREAM_DECODER_ABORTED:
978 FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
980 FLAC__bool got_a_frame;
981 FLAC__ASSERT(0 != decoder);
982 FLAC__ASSERT(0 != decoder->protected_);
985 switch(decoder->protected_->state) {
986 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
987 case FLAC__STREAM_DECODER_READ_METADATA:
988 return false; /* above function sets the status for us */
989 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
990 if(!frame_sync_(decoder))
991 return true; /* above function sets the status for us */
993 case FLAC__STREAM_DECODER_READ_FRAME:
994 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
995 return false; /* above function sets the status for us */
997 return true; /* above function sets the status for us */
999 case FLAC__STREAM_DECODER_END_OF_STREAM:
1000 case FLAC__STREAM_DECODER_ABORTED:
1009 FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
1011 FLAC__uint64 length;
1013 FLAC__ASSERT(0 != decoder);
1016 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
1017 decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
1018 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
1019 decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
1020 decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
1024 if(0 == decoder->private_->seek_callback)
1027 FLAC__ASSERT(decoder->private_->seek_callback);
1028 FLAC__ASSERT(decoder->private_->tell_callback);
1029 FLAC__ASSERT(decoder->private_->length_callback);
1030 FLAC__ASSERT(decoder->private_->eof_callback);
1032 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
1035 decoder->private_->is_seeking = true;
1037 /* turn off md5 checking if a seek is attempted */
1038 decoder->private_->do_md5_checking = false;
1040 /* 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) */
1041 if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
1042 decoder->private_->is_seeking = false;
1045 /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
1047 decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
1048 decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
1050 if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
1051 /* above call sets the state for us */
1052 decoder->private_->is_seeking = false;
1055 /* check this again in case we didn't know total_samples the first time */
1056 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
1057 decoder->private_->is_seeking = false;
1063 FLAC__bool ok = seek_to_absolute_sample_(decoder, length, sample);
1064 decoder->private_->is_seeking = false;
1069 /***********************************************************************
1071 * Protected class methods
1073 ***********************************************************************/
1075 unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
1077 FLAC__ASSERT(0 != decoder);
1078 return FLAC__bitbuffer_get_input_bytes_unconsumed(decoder->private_->input);
1081 /***********************************************************************
1083 * Private class methods
1085 ***********************************************************************/
1087 void set_defaults_(FLAC__StreamDecoder *decoder)
1089 decoder->private_->read_callback = 0;
1090 decoder->private_->seek_callback = 0;
1091 decoder->private_->tell_callback = 0;
1092 decoder->private_->length_callback = 0;
1093 decoder->private_->eof_callback = 0;
1094 decoder->private_->write_callback = 0;
1095 decoder->private_->metadata_callback = 0;
1096 decoder->private_->error_callback = 0;
1097 decoder->private_->client_data = 0;
1099 decoder->private_->filename = 0;
1102 memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
1103 decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
1104 decoder->private_->metadata_filter_ids_count = 0;
1106 decoder->protected_->md5_checking = false;
1110 * This will forcibly set stdin to binary mode (for OSes that require it)
1112 FILE *get_binary_stdin_()
1114 /* if something breaks here it is probably due to the presence or
1115 * absence of an underscore before the identifiers 'setmode',
1116 * 'fileno', and/or 'O_BINARY'; check your system header files.
1118 #if defined _MSC_VER || defined __MINGW32__
1119 _setmode(_fileno(stdin), _O_BINARY);
1120 #elif defined __CYGWIN__ || defined __EMX__
1121 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
1122 setmode(_fileno(stdin), _O_BINARY);
1128 FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
1133 if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
1136 /* simply using realloc() is not practical because the number of channels may change mid-stream */
1138 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
1139 if(0 != decoder->private_->output[i]) {
1140 free(decoder->private_->output[i]-4);
1141 decoder->private_->output[i] = 0;
1143 if(0 != decoder->private_->residual_unaligned[i]) {
1144 free(decoder->private_->residual_unaligned[i]);
1145 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
1149 for(i = 0; i < channels; i++) {
1151 * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
1152 * output arrays have a buffer of up to 3 zeroes in front
1153 * (at negative indices) for alignment purposes; we use 4
1154 * to keep the data well-aligned.
1156 tmp = (FLAC__int32*)malloc(sizeof(FLAC__int32)*(size+4));
1158 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1161 memset(tmp, 0, sizeof(FLAC__int32)*4);
1162 decoder->private_->output[i] = tmp + 4;
1165 * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
1167 if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
1168 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1173 decoder->private_->output_capacity = size;
1174 decoder->private_->output_channels = channels;
1179 FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
1183 FLAC__ASSERT(0 != decoder);
1184 FLAC__ASSERT(0 != decoder->private_);
1186 for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
1187 if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
1193 FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
1197 FLAC__bool first = true;
1199 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1201 for(i = id = 0; i < 4; ) {
1202 if(decoder->private_->cached) {
1203 x = (FLAC__uint32)decoder->private_->lookahead;
1204 decoder->private_->cached = false;
1207 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1208 return false; /* read_callback_ sets the state for us */
1210 if(x == FLAC__STREAM_SYNC_STRING[i]) {
1216 if(x == ID3V2_TAG_[id]) {
1220 if(!skip_id3v2_tag_(decoder))
1221 return false; /* skip_id3v2_tag_ sets the state for us */
1225 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1226 decoder->private_->header_warmup[0] = (FLAC__byte)x;
1227 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1228 return false; /* read_callback_ sets the state for us */
1230 /* 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 */
1231 /* else we have to check if the second byte is the end of a sync code */
1232 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1233 decoder->private_->lookahead = (FLAC__byte)x;
1234 decoder->private_->cached = true;
1236 else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1237 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1238 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1244 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1249 decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
1253 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
1256 FLAC__uint32 i, x, type, length;
1258 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1260 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN, read_callback_, decoder))
1261 return false; /* read_callback_ sets the state for us */
1262 is_last = x? true : false;
1264 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN, read_callback_, decoder))
1265 return false; /* read_callback_ sets the state for us */
1267 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN, read_callback_, decoder))
1268 return false; /* read_callback_ sets the state for us */
1270 if(type == FLAC__METADATA_TYPE_STREAMINFO) {
1271 if(!read_metadata_streaminfo_(decoder, is_last, length))
1274 decoder->private_->has_stream_info = true;
1275 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))
1276 decoder->private_->do_md5_checking = false;
1277 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
1278 decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
1280 else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
1281 if(!read_metadata_seektable_(decoder, is_last, length))
1284 decoder->private_->has_seek_table = true;
1285 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
1286 decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
1289 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
1290 unsigned real_length = length;
1291 FLAC__StreamMetadata block;
1293 block.is_last = is_last;
1294 block.type = (FLAC__MetadataType)type;
1295 block.length = length;
1297 if(type == FLAC__METADATA_TYPE_APPLICATION) {
1298 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8, read_callback_, decoder))
1299 return false; /* read_callback_ sets the state for us */
1301 real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
1303 if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
1308 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
1309 return false; /* read_callback_ sets the state for us */
1313 case FLAC__METADATA_TYPE_PADDING:
1314 /* skip the padding bytes */
1315 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
1316 return false; /* read_callback_ sets the state for us */
1318 case FLAC__METADATA_TYPE_APPLICATION:
1319 /* remember, we read the ID already */
1320 if(real_length > 0) {
1321 if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
1322 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1325 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length, read_callback_, decoder))
1326 return false; /* read_callback_ sets the state for us */
1329 block.data.application.data = 0;
1331 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1332 if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
1335 case FLAC__METADATA_TYPE_CUESHEET:
1336 if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
1339 case FLAC__METADATA_TYPE_STREAMINFO:
1340 case FLAC__METADATA_TYPE_SEEKTABLE:
1344 if(real_length > 0) {
1345 if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
1346 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1349 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length, read_callback_, decoder))
1350 return false; /* read_callback_ sets the state for us */
1353 block.data.unknown.data = 0;
1356 if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
1357 decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1359 /* now we have to free any malloc'ed data in the block */
1361 case FLAC__METADATA_TYPE_PADDING:
1363 case FLAC__METADATA_TYPE_APPLICATION:
1364 if(0 != block.data.application.data)
1365 free(block.data.application.data);
1367 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1368 if(0 != block.data.vorbis_comment.vendor_string.entry)
1369 free(block.data.vorbis_comment.vendor_string.entry);
1370 if(block.data.vorbis_comment.num_comments > 0)
1371 for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
1372 if(0 != block.data.vorbis_comment.comments[i].entry)
1373 free(block.data.vorbis_comment.comments[i].entry);
1374 if(0 != block.data.vorbis_comment.comments)
1375 free(block.data.vorbis_comment.comments);
1377 case FLAC__METADATA_TYPE_CUESHEET:
1378 if(block.data.cue_sheet.num_tracks > 0)
1379 for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
1380 if(0 != block.data.cue_sheet.tracks[i].indices)
1381 free(block.data.cue_sheet.tracks[i].indices);
1382 if(0 != block.data.cue_sheet.tracks)
1383 free(block.data.cue_sheet.tracks);
1385 case FLAC__METADATA_TYPE_STREAMINFO:
1386 case FLAC__METADATA_TYPE_SEEKTABLE:
1389 if(0 != block.data.unknown.data)
1390 free(block.data.unknown.data);
1397 /* if this fails, it's OK, it's just a hint for the seek routine */
1398 if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
1399 decoder->private_->first_frame_offset = 0;
1400 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1406 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1409 unsigned bits, used_bits = 0;
1411 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1413 decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
1414 decoder->private_->stream_info.is_last = is_last;
1415 decoder->private_->stream_info.length = length;
1417 bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1418 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, bits, read_callback_, decoder))
1419 return false; /* read_callback_ sets the state for us */
1420 decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1423 bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1424 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN, read_callback_, decoder))
1425 return false; /* read_callback_ sets the state for us */
1426 decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1429 bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1430 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN, read_callback_, decoder))
1431 return false; /* read_callback_ sets the state for us */
1432 decoder->private_->stream_info.data.stream_info.min_framesize = x;
1435 bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1436 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN, read_callback_, decoder))
1437 return false; /* read_callback_ sets the state for us */
1438 decoder->private_->stream_info.data.stream_info.max_framesize = x;
1441 bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1442 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN, read_callback_, decoder))
1443 return false; /* read_callback_ sets the state for us */
1444 decoder->private_->stream_info.data.stream_info.sample_rate = x;
1447 bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1448 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN, read_callback_, decoder))
1449 return false; /* read_callback_ sets the state for us */
1450 decoder->private_->stream_info.data.stream_info.channels = x+1;
1453 bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1454 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN, read_callback_, decoder))
1455 return false; /* read_callback_ sets the state for us */
1456 decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1459 bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1460 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN, read_callback_, decoder))
1461 return false; /* read_callback_ sets the state for us */
1464 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16, read_callback_, decoder))
1465 return false; /* read_callback_ sets the state for us */
1468 /* skip the rest of the block */
1469 FLAC__ASSERT(used_bits % 8 == 0);
1470 length -= (used_bits / 8);
1471 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1472 return false; /* read_callback_ sets the state for us */
1477 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1482 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1484 decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1485 decoder->private_->seek_table.is_last = is_last;
1486 decoder->private_->seek_table.length = length;
1488 decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1490 /* use realloc since we may pass through here several times (e.g. after seeking) */
1491 if(0 == (decoder->private_->seek_table.data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)realloc(decoder->private_->seek_table.data.seek_table.points, decoder->private_->seek_table.data.seek_table.num_points * sizeof(FLAC__StreamMetadata_SeekPoint)))) {
1492 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1495 for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1496 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN, read_callback_, decoder))
1497 return false; /* read_callback_ sets the state for us */
1498 decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1500 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN, read_callback_, decoder))
1501 return false; /* read_callback_ sets the state for us */
1502 decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1504 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN, read_callback_, decoder))
1505 return false; /* read_callback_ sets the state for us */
1506 decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1508 length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1509 /* if there is a partial point left, skip over it */
1511 /*@@@ do an error_callback() here? there's an argument for either way */
1512 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1513 return false; /* read_callback_ sets the state for us */
1519 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1523 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1525 /* read vendor string */
1526 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1527 if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length, read_callback_, decoder))
1528 return false; /* read_callback_ sets the state for us */
1529 if(obj->vendor_string.length > 0) {
1530 if(0 == (obj->vendor_string.entry = (FLAC__byte*)malloc(obj->vendor_string.length+1))) {
1531 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1534 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length, read_callback_, decoder))
1535 return false; /* read_callback_ sets the state for us */
1536 obj->vendor_string.entry[obj->vendor_string.length] = '\0';
1539 obj->vendor_string.entry = 0;
1541 /* read num comments */
1542 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1543 if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->num_comments, read_callback_, decoder))
1544 return false; /* read_callback_ sets the state for us */
1547 if(obj->num_comments > 0) {
1548 if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)malloc(obj->num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1549 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1552 for(i = 0; i < obj->num_comments; i++) {
1553 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1554 if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->comments[i].length, read_callback_, decoder))
1555 return false; /* read_callback_ sets the state for us */
1556 if(obj->comments[i].length > 0) {
1557 if(0 == (obj->comments[i].entry = (FLAC__byte*)malloc(obj->comments[i].length+1))) {
1558 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1561 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length, read_callback_, decoder))
1562 return false; /* read_callback_ sets the state for us */
1563 obj->comments[i].entry[obj->comments[i].length] = '\0';
1566 obj->comments[i].entry = 0;
1576 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1578 FLAC__uint32 i, j, x;
1580 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1582 memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1584 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1585 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8, read_callback_, decoder))
1586 return false; /* read_callback_ sets the state for us */
1588 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN, read_callback_, decoder))
1589 return false; /* read_callback_ sets the state for us */
1591 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN, read_callback_, decoder))
1592 return false; /* read_callback_ sets the state for us */
1593 obj->is_cd = x? true : false;
1595 if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN, read_callback_, decoder))
1596 return false; /* read_callback_ sets the state for us */
1598 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN, read_callback_, decoder))
1599 return false; /* read_callback_ sets the state for us */
1600 obj->num_tracks = x;
1602 if(obj->num_tracks > 0) {
1603 if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1604 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1607 for(i = 0; i < obj->num_tracks; i++) {
1608 FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1609 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN, read_callback_, decoder))
1610 return false; /* read_callback_ sets the state for us */
1612 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN, read_callback_, decoder))
1613 return false; /* read_callback_ sets the state for us */
1614 track->number = (FLAC__byte)x;
1616 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1617 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8, read_callback_, decoder))
1618 return false; /* read_callback_ sets the state for us */
1620 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN, read_callback_, decoder))
1621 return false; /* read_callback_ sets the state for us */
1624 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN, read_callback_, decoder))
1625 return false; /* read_callback_ sets the state for us */
1626 track->pre_emphasis = x;
1628 if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN, read_callback_, decoder))
1629 return false; /* read_callback_ sets the state for us */
1631 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN, read_callback_, decoder))
1632 return false; /* read_callback_ sets the state for us */
1633 track->num_indices = (FLAC__byte)x;
1635 if(track->num_indices > 0) {
1636 if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1637 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1640 for(j = 0; j < track->num_indices; j++) {
1641 FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1642 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN, read_callback_, decoder))
1643 return false; /* read_callback_ sets the state for us */
1645 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN, read_callback_, decoder))
1646 return false; /* read_callback_ sets the state for us */
1647 index->number = (FLAC__byte)x;
1649 if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN, read_callback_, decoder))
1650 return false; /* read_callback_ sets the state for us */
1659 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1664 /* skip the version and flags bytes */
1665 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 24, read_callback_, decoder))
1666 return false; /* read_callback_ sets the state for us */
1667 /* get the size (in bytes) to skip */
1669 for(i = 0; i < 4; i++) {
1670 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1671 return false; /* read_callback_ sets the state for us */
1675 /* skip the rest of the tag */
1676 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, skip, read_callback_, decoder))
1677 return false; /* read_callback_ sets the state for us */
1681 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1684 FLAC__bool first = true;
1686 /* If we know the total number of samples in the stream, stop if we've read that many. */
1687 /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1688 if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
1689 if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
1690 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1695 /* make sure we're byte aligned */
1696 if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
1697 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
1698 return false; /* read_callback_ sets the state for us */
1702 if(decoder->private_->cached) {
1703 x = (FLAC__uint32)decoder->private_->lookahead;
1704 decoder->private_->cached = false;
1707 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1708 return false; /* read_callback_ sets the state for us */
1710 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1711 decoder->private_->header_warmup[0] = (FLAC__byte)x;
1712 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1713 return false; /* read_callback_ sets the state for us */
1715 /* 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 */
1716 /* else we have to check if the second byte is the end of a sync code */
1717 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1718 decoder->private_->lookahead = (FLAC__byte)x;
1719 decoder->private_->cached = true;
1721 else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1722 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1723 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1728 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1736 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
1740 FLAC__int32 mid, side, left, right;
1741 FLAC__uint16 frame_crc; /* the one we calculate from the input stream */
1744 *got_a_frame = false;
1748 FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
1749 FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
1750 FLAC__bitbuffer_reset_read_crc16(decoder->private_->input, frame_crc);
1752 if(!read_frame_header_(decoder))
1754 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
1756 if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
1758 for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1760 * first figure the correct bits-per-sample of the subframe
1762 unsigned bps = decoder->private_->frame.header.bits_per_sample;
1763 switch(decoder->private_->frame.header.channel_assignment) {
1764 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1765 /* no adjustment needed */
1767 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1768 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1772 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1773 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1777 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1778 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1788 if(!read_subframe_(decoder, channel, bps, do_full_decode))
1790 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
1793 if(!read_zero_padding_(decoder))
1797 * Read the frame CRC-16 from the footer and check
1799 frame_crc = FLAC__bitbuffer_get_read_crc16(decoder->private_->input);
1800 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN, read_callback_, decoder))
1801 return false; /* read_callback_ sets the state for us */
1802 if(frame_crc == (FLAC__uint16)x) {
1803 if(do_full_decode) {
1804 /* Undo any special channel coding */
1805 switch(decoder->private_->frame.header.channel_assignment) {
1806 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1809 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1810 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1811 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1812 decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
1814 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1815 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1816 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1817 decoder->private_->output[0][i] += decoder->private_->output[1][i];
1819 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1820 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1821 for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
1822 mid = decoder->private_->output[0][i];
1823 side = decoder->private_->output[1][i];
1825 if(side & 1) /* i.e. if 'side' is odd... */
1829 decoder->private_->output[0][i] = left >> 1;
1830 decoder->private_->output[1][i] = right >> 1;
1840 /* Bad frame, emit error and zero the output signal */
1841 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
1842 if(do_full_decode) {
1843 for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1844 memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
1849 *got_a_frame = true;
1851 /* put the latest values into the public section of the decoder instance */
1852 decoder->protected_->channels = decoder->private_->frame.header.channels;
1853 decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
1854 decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
1855 decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
1856 decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
1858 FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1859 decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
1862 if(do_full_decode) {
1863 if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
1867 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1871 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
1875 unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
1876 FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
1877 unsigned raw_header_len;
1878 FLAC__bool is_unparseable = false;
1879 const FLAC__bool is_known_variable_blocksize_stream = (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize);
1880 const FLAC__bool is_known_fixed_blocksize_stream = (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize);
1882 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1884 /* init the raw header with the saved bits from synchronization */
1885 raw_header[0] = decoder->private_->header_warmup[0];
1886 raw_header[1] = decoder->private_->header_warmup[1];
1890 * check to make sure that the reserved bits are 0
1892 if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
1893 is_unparseable = true;
1897 * Note that along the way as we read the header, we look for a sync
1898 * code inside. If we find one it would indicate that our original
1899 * sync was bad since there cannot be a sync code in a valid header.
1903 * read in the raw header as bytes so we can CRC it, and parse it on the way
1905 for(i = 0; i < 2; i++) {
1906 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1907 return false; /* read_callback_ sets the state for us */
1908 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1909 /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
1910 decoder->private_->lookahead = (FLAC__byte)x;
1911 decoder->private_->cached = true;
1912 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
1913 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1916 raw_header[raw_header_len++] = (FLAC__byte)x;
1919 switch(x = raw_header[2] >> 4) {
1921 if(is_known_fixed_blocksize_stream)
1922 decoder->private_->frame.header.blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
1924 is_unparseable = true;
1927 decoder->private_->frame.header.blocksize = 192;
1933 decoder->private_->frame.header.blocksize = 576 << (x-2);
1947 decoder->private_->frame.header.blocksize = 256 << (x-8);
1954 switch(x = raw_header[2] & 0x0f) {
1956 if(decoder->private_->has_stream_info)
1957 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
1959 is_unparseable = true;
1964 is_unparseable = true;
1967 decoder->private_->frame.header.sample_rate = 8000;
1970 decoder->private_->frame.header.sample_rate = 16000;
1973 decoder->private_->frame.header.sample_rate = 22050;
1976 decoder->private_->frame.header.sample_rate = 24000;
1979 decoder->private_->frame.header.sample_rate = 32000;
1982 decoder->private_->frame.header.sample_rate = 44100;
1985 decoder->private_->frame.header.sample_rate = 48000;
1988 decoder->private_->frame.header.sample_rate = 96000;
1993 sample_rate_hint = x;
1996 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
1997 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2003 x = (unsigned)(raw_header[3] >> 4);
2005 decoder->private_->frame.header.channels = 2;
2008 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2011 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2014 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2017 is_unparseable = true;
2022 decoder->private_->frame.header.channels = (unsigned)x + 1;
2023 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2026 switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2028 if(decoder->private_->has_stream_info)
2029 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2031 is_unparseable = true;
2034 decoder->private_->frame.header.bits_per_sample = 8;
2037 decoder->private_->frame.header.bits_per_sample = 12;
2040 decoder->private_->frame.header.bits_per_sample = 16;
2043 decoder->private_->frame.header.bits_per_sample = 20;
2046 decoder->private_->frame.header.bits_per_sample = 24;
2050 is_unparseable = true;
2057 if(raw_header[3] & 0x01) { /* this should be a zero padding bit */
2058 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2059 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2064 * Now we get to the regrettable consequences of not knowing for sure
2065 * whether we got a frame number or a sample number. There are no
2066 * encoders that do variable-blocksize encoding so unless we know from
2067 * the STREAMINFO that it is variable-blocksize we will assume it is
2068 * fixed-blocksize. The trouble comes when we have no STREAMINFO; again
2069 * we will guess that is fixed-blocksize. Where this can go wrong: 1) a
2070 * variable-blocksize stream with no STREAMINFO; 2) a fixed-blocksize
2071 * stream that was edited such that one or more frames before or
2072 * including this one do not have the same number of samples as the
2073 * STREAMINFO's min and max blocksize.
2075 if(is_known_variable_blocksize_stream) {
2076 if(blocksize_hint) {
2077 if(!FLAC__bitbuffer_read_utf8_uint64(decoder->private_->input, &xx, read_callback_, decoder, raw_header, &raw_header_len))
2078 return false; /* read_callback_ sets the state for us */
2079 if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
2080 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2081 decoder->private_->cached = true;
2082 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2083 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2086 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2087 decoder->private_->frame.header.number.sample_number = xx;
2090 is_unparseable = true;
2093 if(!FLAC__bitbuffer_read_utf8_uint32(decoder->private_->input, &x, read_callback_, decoder, raw_header, &raw_header_len))
2094 return false; /* read_callback_ sets the state for us */
2095 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
2096 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2097 decoder->private_->cached = true;
2098 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2099 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2102 decoder->private_->last_frame_number = x;
2103 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2104 if(decoder->private_->has_stream_info) {
2105 FLAC__ASSERT(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize);
2106 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
2107 decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2109 else if(blocksize_hint) {
2110 if(decoder->private_->last_block_size)
2111 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->last_block_size * (FLAC__uint64)x;
2113 is_unparseable = true;
2116 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
2117 decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2121 if(blocksize_hint) {
2122 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2123 return false; /* read_callback_ sets the state for us */
2124 raw_header[raw_header_len++] = (FLAC__byte)x;
2125 if(blocksize_hint == 7) {
2127 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
2128 return false; /* read_callback_ sets the state for us */
2129 raw_header[raw_header_len++] = (FLAC__byte)_x;
2132 decoder->private_->frame.header.blocksize = x+1;
2135 if(sample_rate_hint) {
2136 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2137 return false; /* read_callback_ sets the state for us */
2138 raw_header[raw_header_len++] = (FLAC__byte)x;
2139 if(sample_rate_hint != 12) {
2141 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
2142 return false; /* read_callback_ sets the state for us */
2143 raw_header[raw_header_len++] = (FLAC__byte)_x;
2146 if(sample_rate_hint == 12)
2147 decoder->private_->frame.header.sample_rate = x*1000;
2148 else if(sample_rate_hint == 13)
2149 decoder->private_->frame.header.sample_rate = x;
2151 decoder->private_->frame.header.sample_rate = x*10;
2154 /* read the CRC-8 byte */
2155 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2156 return false; /* read_callback_ sets the state for us */
2157 crc8 = (FLAC__byte)x;
2159 if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
2160 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2161 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2165 if(is_unparseable) {
2166 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2167 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2174 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2177 FLAC__bool wasted_bits;
2180 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder)) /* MAGIC NUMBER */
2181 return false; /* read_callback_ sets the state for us */
2183 wasted_bits = (x & 1);
2188 if(!FLAC__bitbuffer_read_unary_unsigned(decoder->private_->input, &u, read_callback_, decoder))
2189 return false; /* read_callback_ sets the state for us */
2190 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
2191 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
2194 decoder->private_->frame.subframes[channel].wasted_bits = 0;
2197 * Lots of magic numbers here
2200 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2201 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2205 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2209 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2213 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2214 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2218 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2220 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2224 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2225 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2229 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2231 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2235 if(wasted_bits && do_full_decode) {
2236 x = decoder->private_->frame.subframes[channel].wasted_bits;
2237 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2238 decoder->private_->output[channel][i] <<= x;
2244 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2246 FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2249 FLAC__int32 *output = decoder->private_->output[channel];
2251 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2253 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
2254 return false; /* read_callback_ sets the state for us */
2256 subframe->value = x;
2258 /* decode the subframe */
2259 if(do_full_decode) {
2260 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2267 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2269 FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2274 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2276 subframe->residual = decoder->private_->residual[channel];
2277 subframe->order = order;
2279 /* read warm-up samples */
2280 for(u = 0; u < order; u++) {
2281 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
2282 return false; /* read_callback_ sets the state for us */
2283 subframe->warmup[u] = i32;
2286 /* read entropy coding method info */
2287 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
2288 return false; /* read_callback_ sets the state for us */
2289 subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2290 switch(subframe->entropy_coding_method.type) {
2291 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2292 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
2293 return false; /* read_callback_ sets the state for us */
2294 subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2295 subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2298 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2299 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2304 switch(subframe->entropy_coding_method.type) {
2305 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2306 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]))
2313 /* decode the subframe */
2314 if(do_full_decode) {
2315 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2316 FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
2322 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2324 FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2329 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2331 subframe->residual = decoder->private_->residual[channel];
2332 subframe->order = order;
2334 /* read warm-up samples */
2335 for(u = 0; u < order; u++) {
2336 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
2337 return false; /* read_callback_ sets the state for us */
2338 subframe->warmup[u] = i32;
2341 /* read qlp coeff precision */
2342 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN, read_callback_, decoder))
2343 return false; /* read_callback_ sets the state for us */
2344 if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
2345 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2346 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2349 subframe->qlp_coeff_precision = u32+1;
2351 /* read qlp shift */
2352 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN, read_callback_, decoder))
2353 return false; /* read_callback_ sets the state for us */
2354 subframe->quantization_level = i32;
2356 /* read quantized lp coefficiencts */
2357 for(u = 0; u < order; u++) {
2358 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision, read_callback_, decoder))
2359 return false; /* read_callback_ sets the state for us */
2360 subframe->qlp_coeff[u] = i32;
2363 /* read entropy coding method info */
2364 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
2365 return false; /* read_callback_ sets the state for us */
2366 subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2367 switch(subframe->entropy_coding_method.type) {
2368 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2369 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
2370 return false; /* read_callback_ sets the state for us */
2371 subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2372 subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2375 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2376 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2381 switch(subframe->entropy_coding_method.type) {
2382 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2383 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]))
2390 /* decode the subframe */
2391 if(do_full_decode) {
2392 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2393 if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2394 if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2396 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);
2398 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);
2401 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);
2403 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);
2409 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2411 FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2412 FLAC__int32 x, *residual = decoder->private_->residual[channel];
2415 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2417 subframe->data = residual;
2419 for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2420 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
2421 return false; /* read_callback_ sets the state for us */
2425 /* decode the subframe */
2427 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2432 FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual)
2434 FLAC__uint32 rice_parameter;
2436 unsigned partition, sample, u;
2437 const unsigned partitions = 1u << partition_order;
2438 const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2441 if(partition_order == 0) {
2442 if(decoder->private_->frame.header.blocksize < predictor_order) {
2443 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2444 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2449 if(partition_samples < predictor_order) {
2450 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2451 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2456 if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2457 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2462 for(partition = 0; partition < partitions; partition++) {
2463 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN, read_callback_, decoder))
2464 return false; /* read_callback_ sets the state for us */
2465 partitioned_rice_contents->parameters[partition] = rice_parameter;
2466 if(rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2467 u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2468 if(!FLAC__bitbuffer_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter, read_callback_, decoder))
2469 return false; /* read_callback_ sets the state for us */
2473 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN, read_callback_, decoder))
2474 return false; /* read_callback_ sets the state for us */
2475 partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2476 for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2477 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i, rice_parameter, read_callback_, decoder))
2478 return false; /* read_callback_ sets the state for us */
2479 residual[sample] = i;
2487 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2489 if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
2490 FLAC__uint32 zero = 0;
2491 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
2492 return false; /* read_callback_ sets the state for us */
2494 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2495 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2501 FLAC__bool read_callback_(FLAC__byte buffer[], unsigned *bytes, void *client_data)
2503 FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2505 if(decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)) {
2507 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2510 else if(*bytes > 0) {
2511 /* While seeking, it is possible for our seek to land in the
2512 * middle of audio data that looks exactly like a frame header
2513 * from a future version of an encoder. When that happens, our
2514 * error callback will get an
2515 * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
2516 * unparseable_frame_count. But there is a remote possibility
2517 * that it is properly synced at such a "future-codec frame",
2518 * so to make sure, we wait to see many "unparseable" errors in
2519 * a row before bailing out.
2521 if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2522 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2526 const FLAC__StreamDecoderReadStatus status = decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data);
2527 if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
2528 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2531 else if(*bytes == 0) {
2532 if(status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM || (decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data))) {
2533 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2544 /* abort to avoid a deadlock */
2545 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2550 FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2552 if(decoder->private_->is_seeking) {
2553 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
2554 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
2555 FLAC__uint64 target_sample = decoder->private_->target_sample;
2557 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2559 decoder->private_->last_frame = *frame; /* save the frame */
2560 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
2561 unsigned delta = (unsigned)(target_sample - this_frame_sample);
2562 /* kick out of seek mode */
2563 decoder->private_->is_seeking = false;
2564 /* shift out the samples before target_sample */
2567 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
2568 for(channel = 0; channel < frame->header.channels; channel++)
2569 newbuffer[channel] = buffer[channel] + delta;
2570 decoder->private_->last_frame.header.blocksize -= delta;
2571 decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
2572 /* write the relevant samples */
2573 return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
2576 /* write the relevant samples */
2577 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2581 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2586 * If we never got STREAMINFO, turn off MD5 checking to save
2587 * cycles since we don't have a sum to compare to anyway
2589 if(!decoder->private_->has_stream_info)
2590 decoder->private_->do_md5_checking = false;
2591 if(decoder->private_->do_md5_checking) {
2592 if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
2593 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2595 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2599 void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2601 if(!decoder->private_->is_seeking)
2602 decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
2603 else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
2604 decoder->private_->unparseable_frame_count++;
2607 FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2609 FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound;
2610 FLAC__int64 pos = -1, last_pos = -1;
2611 int i, lower_seek_point = -1, upper_seek_point = -1;
2612 unsigned approx_bytes_per_frame;
2613 FLAC__uint64 last_frame_sample = FLAC__U64L(0xffffffffffffffff);
2614 FLAC__bool needs_seek;
2615 const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
2616 const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2617 const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
2618 const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
2619 const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
2620 const unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
2621 const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
2623 /* we are just guessing here, but we want to guess high, not low */
2624 if(max_framesize > 0)
2625 approx_bytes_per_frame = max_framesize;
2628 * Check if it's a known fixed-blocksize stream. Note that though
2629 * the spec doesn't allow zeroes in the STREAMINFO block, we may
2630 * never get a STREAMINFO block when decoding so the value of
2631 * min_blocksize might be zero.
2633 else if(min_blocksize == max_blocksize && min_blocksize > 0) {
2634 /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
2635 approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
2638 approx_bytes_per_frame = 4608 * channels * bps/8 + 64;
2641 * First, we set an upper and lower bound on where in the
2642 * stream we will search. For now we assume the worst case
2643 * scenario, which is our best guess at the beginning of
2644 * the first and last frames.
2646 lower_bound = first_frame_offset;
2648 /* calc the upper_bound, beyond which we never want to seek */
2649 if(max_framesize > 0)
2650 upper_bound = stream_length - (max_framesize + 128 + 2); /* 128 for a possible ID3V1 tag, 2 for indexing differences */
2652 upper_bound = stream_length - ((channels * bps * FLAC__MAX_BLOCK_SIZE) / 8 + 128 + 2);
2655 * Now we refine the bounds if we have a seektable with
2656 * suitable points. Note that according to the spec they
2657 * must be ordered by ascending sample number.
2660 /* find the closest seek point <= target_sample, if it exists */
2661 for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
2662 if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number <= target_sample)
2665 if(i >= 0) { /* i.e. we found a suitable seek point... */
2666 lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
2667 lower_seek_point = i;
2670 /* find the closest seek point > target_sample, if it exists */
2671 for(i = 0; i < (int)seek_table->num_points; i++) {
2672 if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number > target_sample)
2675 if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
2676 upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
2677 upper_seek_point = i;
2682 * Now guess at where within those bounds our target
2685 if(seek_table && lower_seek_point >= 0) {
2686 /* first see if our sample is within a few frames of the lower seekpoint */
2687 if(seek_table->points[lower_seek_point].sample_number <= target_sample && target_sample < seek_table->points[lower_seek_point].sample_number + (seek_table->points[lower_seek_point].frame_samples * 4)) {
2688 pos = (FLAC__int64)lower_bound;
2690 else if(upper_seek_point >= 0) {
2691 const FLAC__uint64 target_offset = target_sample - seek_table->points[lower_seek_point].sample_number;
2692 const FLAC__uint64 range_samples = seek_table->points[upper_seek_point].sample_number - seek_table->points[lower_seek_point].sample_number;
2693 const FLAC__uint64 range_bytes = (upper_bound>lower_bound? upper_bound - lower_bound - 1 : 0);
2694 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2695 #if defined _MSC_VER || defined __MINGW32__
2696 /* with MSVC you have to spoon feed it the casting */
2697 pos = (FLAC__int64)lower_bound + (FLAC__int64)(((FLAC__double)(FLAC__int64)target_offset / (FLAC__double)(FLAC__int64)range_samples) * (FLAC__double)(FLAC__int64)(range_bytes-1)) - approx_bytes_per_frame;
2699 pos = (FLAC__int64)lower_bound + (FLAC__int64)(((FLAC__double)target_offset / (FLAC__double)range_samples) * (FLAC__double)range_bytes) - approx_bytes_per_frame;
2702 /* a little less accurate: */
2703 if (range_bytes <= 0xffffffff)
2704 pos = (FLAC__int64)lower_bound + (FLAC__int64)((target_offset * range_bytes) / range_samples) - approx_bytes_per_frame;
2705 else /* @@@ WATCHOUT, ~2TB limit */
2706 pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_offset>>8) * (range_bytes>>8)) / (range_samples>>16)) - approx_bytes_per_frame;
2712 * If there's no seek table, we need to use the metadata (if we
2713 * have it) and the filelength to estimate the position of the
2714 * frame with the correct sample.
2716 if(pos < 0 && total_samples > 0) {
2718 * For max accuracy we should be using
2719 * (stream_length-first_frame_offset-1) in the divisor, but the
2720 * difference is trivial and (stream_length-first_frame_offset)
2721 * has no chance of underflow.
2723 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2724 #if defined _MSC_VER || defined __MINGW32__
2725 /* with VC++ you have to spoon feed it the casting */
2726 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)(((FLAC__double)(FLAC__int64)target_sample / (FLAC__double)(FLAC__int64)total_samples) * (FLAC__double)(FLAC__int64)(stream_length-first_frame_offset)) - approx_bytes_per_frame;
2728 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)(((FLAC__double)target_sample / (FLAC__double)total_samples) * (FLAC__double)(stream_length-first_frame_offset)) - approx_bytes_per_frame;
2731 /* a little less accurate: */
2732 if (stream_length < 0xffffffff)
2733 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)((target_sample * (stream_length-first_frame_offset)) / total_samples) - approx_bytes_per_frame;
2734 else /* @@@ WATCHOUT, ~2TB limit */
2735 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)(((target_sample>>8) * ((stream_length-first_frame_offset)>>8)) / (total_samples>>16)) - approx_bytes_per_frame;
2740 * If there's no seek table and total_samples is unknown, we
2741 * don't even bother trying to figure out a target, we just use
2742 * our current position.
2746 if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK) {
2747 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2750 pos = (FLAC__int64)upos;
2756 /* clip the position to the bounds, lower bound takes precedence */
2757 if(pos >= (FLAC__int64)upper_bound) {
2758 pos = (FLAC__int64)upper_bound-1;
2761 if(pos < (FLAC__int64)lower_bound) {
2762 pos = (FLAC__int64)lower_bound;
2766 decoder->private_->target_sample = target_sample;
2769 if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
2770 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2773 if(!FLAC__stream_decoder_flush(decoder)) {
2774 /* above call sets the state for us */
2778 /* Now we need to get a frame. First we need to reset our
2779 * unparseable_frame_count; if we get too many unparseable
2780 * frames in a row, the read callback will return
2781 * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
2782 * FLAC__stream_decoder_process_single() to return false.
2784 decoder->private_->unparseable_frame_count = 0;
2785 if(!FLAC__stream_decoder_process_single(decoder)) {
2786 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2789 /* our write callback will change the state when it gets to the target frame */
2790 /* 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 */
2792 /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
2793 if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
2796 if(!decoder->private_->is_seeking) {
2799 else { /* we need to narrow the search */
2800 const FLAC__uint64 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
2801 FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2802 if(this_frame_sample == last_frame_sample && pos < last_pos) {
2803 /* our last move backwards wasn't big enough, double it */
2804 pos -= (last_pos - pos);
2808 if(target_sample < this_frame_sample) {
2810 approx_bytes_per_frame = decoder->private_->last_frame.header.blocksize * channels * bps/8 + 64;
2811 pos -= approx_bytes_per_frame;
2814 else { /* target_sample >= this_frame_sample + this frame's blocksize */
2816 if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK) {
2817 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2821 pos = (FLAC__int64)upos;
2822 pos -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
2825 * if we haven't hit the target frame yet and our position hasn't changed,
2826 * it means we're at the end of the stream and the seek target does not exist.
2828 if(last_pos == pos) {
2829 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2834 if(pos < (FLAC__int64)lower_bound)
2835 pos = (FLAC__int64)lower_bound;
2836 last_frame_sample = this_frame_sample;
2843 FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
2848 *bytes = (unsigned)fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
2849 if(ferror(decoder->private_->file))
2850 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2851 else if(*bytes == 0)
2852 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2854 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2857 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
2860 FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2864 if(decoder->private_->file == stdin)
2865 return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
2866 else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
2867 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
2869 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2872 FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2877 if(decoder->private_->file == stdin) /*@@@@@@ may work for stdin */
2878 return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
2879 else if((pos = ftello(decoder->private_->file)) < 0)
2880 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
2882 *absolute_byte_offset = (FLAC__uint64)pos;
2883 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2887 FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2889 struct stat filestats;
2892 if(decoder->private_->file == stdin)
2893 return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
2895 else if(0 == decoder->private_->filename || fstat(fileno(decoder->private_->file), &filestats) != 0)
2897 else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
2898 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
2900 *stream_length = (FLAC__uint64)filestats.st_size;
2901 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2905 FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
2909 if(decoder->private_->file == stdin) /*@@@@@@ feof() may work for stdin */
2911 return feof(decoder->private_->file)? true : false;