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 #if _MSC_VER <= 1200 /* @@@ [2G limit] */
55 #include "FLAC/assert.h"
56 #include "protected/stream_decoder.h"
57 #include "private/bitbuffer.h"
58 #include "private/bitmath.h"
59 #include "private/cpu.h"
60 #include "private/crc.h"
61 #include "private/fixed.h"
62 #include "private/format.h"
63 #include "private/lpc.h"
64 #include "private/md5.h"
65 #include "private/memory.h"
70 #define max(a,b) ((a)>(b)?(a):(b))
72 /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
74 #define FLAC__U64L(x) x
76 #define FLAC__U64L(x) x##LLU
79 /***********************************************************************
83 ***********************************************************************/
85 static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
87 /***********************************************************************
89 * Private class method prototypes
91 ***********************************************************************/
93 static void set_defaults_(FLAC__StreamDecoder *decoder);
94 static FILE *get_binary_stdin_();
95 static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
96 static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
97 static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
98 static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
99 static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
100 static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
101 static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
102 static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
103 static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *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 */
150 FLAC__BitBuffer *input;
151 FLAC__int32 *output[FLAC__MAX_CHANNELS];
152 FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
153 FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
154 unsigned output_capacity, output_channels;
155 FLAC__uint32 last_frame_number;
156 FLAC__uint32 last_block_size;
157 FLAC__uint64 samples_decoded;
158 FLAC__bool has_stream_info, has_seek_table;
159 FLAC__StreamMetadata stream_info;
160 FLAC__StreamMetadata seek_table;
161 FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
162 FLAC__byte *metadata_filter_ids;
163 unsigned metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
165 FLAC__bool cached; /* true if there is a byte in lookahead */
166 FLAC__CPUInfo cpuinfo;
167 FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
168 FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
169 /* unaligned (original) pointers to allocated data */
170 FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
171 FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */
172 FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
173 FLAC__bool is_seeking;
174 struct FLAC__MD5Context md5context;
175 FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
176 /* (the rest of these are only used for seeking) */
177 FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
178 FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
179 FLAC__uint64 target_sample;
180 unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
181 } FLAC__StreamDecoderPrivate;
183 /***********************************************************************
185 * Public static class data
187 ***********************************************************************/
189 FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
190 "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
191 "FLAC__STREAM_DECODER_READ_METADATA",
192 "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
193 "FLAC__STREAM_DECODER_READ_FRAME",
194 "FLAC__STREAM_DECODER_END_OF_STREAM",
195 "FLAC__STREAM_DECODER_SEEK_ERROR",
196 "FLAC__STREAM_DECODER_ABORTED",
197 "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
198 "FLAC__STREAM_DECODER_UNINITIALIZED"
201 FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
202 "FLAC__STREAM_DECODER_INIT_STATUS_OK",
203 "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
204 "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
205 "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
206 "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
209 FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
210 "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
211 "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
212 "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
215 FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
216 "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
217 "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
218 "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
221 FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
222 "FLAC__STREAM_DECODER_TELL_STATUS_OK",
223 "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
224 "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
227 FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
228 "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
229 "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
230 "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
233 FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
234 "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
235 "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
238 FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
239 "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
240 "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
241 "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
242 "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
245 /***********************************************************************
247 * Class constructor/destructor
249 ***********************************************************************/
250 FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new()
252 FLAC__StreamDecoder *decoder;
255 FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
257 decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
262 decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
263 if(decoder->protected_ == 0) {
268 decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
269 if(decoder->private_ == 0) {
270 free(decoder->protected_);
275 decoder->private_->input = FLAC__bitbuffer_new();
276 if(decoder->private_->input == 0) {
277 free(decoder->private_);
278 free(decoder->protected_);
283 decoder->private_->metadata_filter_ids_capacity = 16;
284 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
285 FLAC__bitbuffer_delete(decoder->private_->input);
286 free(decoder->private_);
287 free(decoder->protected_);
292 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
293 decoder->private_->output[i] = 0;
294 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
297 decoder->private_->output_capacity = 0;
298 decoder->private_->output_channels = 0;
299 decoder->private_->has_seek_table = false;
301 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
302 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
304 decoder->private_->file = 0;
306 set_defaults_(decoder);
308 decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
313 FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
317 FLAC__ASSERT(0 != decoder);
318 FLAC__ASSERT(0 != decoder->protected_);
319 FLAC__ASSERT(0 != decoder->private_);
320 FLAC__ASSERT(0 != decoder->private_->input);
322 FLAC__stream_decoder_finish(decoder);
324 if(0 != decoder->private_->metadata_filter_ids)
325 free(decoder->private_->metadata_filter_ids);
327 FLAC__bitbuffer_delete(decoder->private_->input);
329 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
330 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
332 free(decoder->private_);
333 free(decoder->protected_);
337 /***********************************************************************
339 * Public class methods
341 ***********************************************************************/
343 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
344 FLAC__StreamDecoder *decoder,
345 FLAC__StreamDecoderReadCallback read_callback,
346 FLAC__StreamDecoderSeekCallback seek_callback,
347 FLAC__StreamDecoderTellCallback tell_callback,
348 FLAC__StreamDecoderLengthCallback length_callback,
349 FLAC__StreamDecoderEofCallback eof_callback,
350 FLAC__StreamDecoderWriteCallback write_callback,
351 FLAC__StreamDecoderMetadataCallback metadata_callback,
352 FLAC__StreamDecoderErrorCallback error_callback,
356 FLAC__ASSERT(0 != decoder);
358 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
359 return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
362 0 == read_callback ||
363 0 == write_callback ||
364 0 == error_callback ||
365 (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
367 return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
370 * get the CPU info and set the function pointers
372 FLAC__cpu_info(&decoder->private_->cpuinfo);
373 /* first default to the non-asm routines */
374 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
375 decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
376 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
377 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
378 /* now override with asm where appropriate */
380 if(decoder->private_->cpuinfo.use_asm) {
381 #ifdef FLAC__CPU_IA32
382 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
383 #ifdef FLAC__HAS_NASM
384 if(decoder->private_->cpuinfo.data.ia32.mmx) {
385 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
386 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
387 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
390 decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
391 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
392 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
395 #elif defined FLAC__CPU_PPC
396 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
397 if(decoder->private_->cpuinfo.data.ppc.altivec) {
398 decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
399 decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
405 /* from here on, errors are fatal */
407 if(!FLAC__bitbuffer_init(decoder->private_->input)) {
408 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
409 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
412 decoder->private_->read_callback = read_callback;
413 decoder->private_->seek_callback = seek_callback;
414 decoder->private_->tell_callback = tell_callback;
415 decoder->private_->length_callback = length_callback;
416 decoder->private_->eof_callback = eof_callback;
417 decoder->private_->write_callback = write_callback;
418 decoder->private_->metadata_callback = metadata_callback;
419 decoder->private_->error_callback = error_callback;
420 decoder->private_->client_data = client_data;
421 decoder->private_->last_frame_number = 0;
422 decoder->private_->last_block_size = 0;
423 decoder->private_->samples_decoded = 0;
424 decoder->private_->has_stream_info = false;
425 decoder->private_->cached = false;
427 decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
428 decoder->private_->is_seeking = false;
430 decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
431 if(!FLAC__stream_decoder_reset(decoder)) {
432 /* above call sets the state for us */
433 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
436 return FLAC__STREAM_DECODER_INIT_STATUS_OK;
439 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
440 FLAC__StreamDecoder *decoder,
442 FLAC__StreamDecoderWriteCallback write_callback,
443 FLAC__StreamDecoderMetadataCallback metadata_callback,
444 FLAC__StreamDecoderErrorCallback error_callback,
448 FLAC__ASSERT(0 != decoder);
449 FLAC__ASSERT(0 != file);
451 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
452 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
454 if(0 == write_callback || 0 == error_callback)
455 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
458 * To make sure that our file does not go unclosed after an error, we
459 * must assign the FILE pointer before any further error can occur in
463 file = get_binary_stdin_(); /* just to be safe */
465 decoder->private_->file = file;
467 return FLAC__stream_decoder_init_stream(
470 decoder->private_->file == stdin? 0: file_seek_callback_,
471 decoder->private_->file == stdin? 0: file_tell_callback_,/*@@@@@@ might work for stdin*/
472 decoder->private_->file == stdin? 0: file_length_callback_,
473 decoder->private_->file == stdin? 0: file_eof_callback_,/*@@@@@@ might work for stdin*/
481 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
482 FLAC__StreamDecoder *decoder,
483 const char *filename,
484 FLAC__StreamDecoderWriteCallback write_callback,
485 FLAC__StreamDecoderMetadataCallback metadata_callback,
486 FLAC__StreamDecoderErrorCallback error_callback,
492 FLAC__ASSERT(0 != decoder);
495 * To make sure that our file does not go unclosed after an error, we
496 * have to do the same entrance checks here that are later performed
497 * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
499 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
500 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
502 if(0 == write_callback || 0 == error_callback)
503 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
505 file = filename? fopen(filename, "rb") : stdin;
508 return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
510 return FLAC__stream_decoder_init_FILE(decoder, file, write_callback, metadata_callback, error_callback, client_data);
513 FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
515 FLAC__bool md5_failed = false;
518 FLAC__ASSERT(0 != decoder);
519 FLAC__ASSERT(0 != decoder->private_);
520 FLAC__ASSERT(0 != decoder->protected_);
522 if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
525 /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
526 * always call FLAC__MD5Final()
528 FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
530 if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
531 free(decoder->private_->seek_table.data.seek_table.points);
532 decoder->private_->seek_table.data.seek_table.points = 0;
533 decoder->private_->has_seek_table = false;
535 FLAC__bitbuffer_free(decoder->private_->input);
536 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
538 * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
539 * output arrays have a buffer of up to 3 zeroes in front
540 * (at negative indices) for alignment purposes; we use 4
541 * to keep the data well-aligned.
543 if(0 != decoder->private_->output[i]) {
544 free(decoder->private_->output[i]-4);
545 decoder->private_->output[i] = 0;
547 if(0 != decoder->private_->residual_unaligned[i]) {
548 free(decoder->private_->residual_unaligned[i]);
549 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
552 decoder->private_->output_capacity = 0;
553 decoder->private_->output_channels = 0;
555 if(0 != decoder->private_->file) {
556 if(decoder->private_->file != stdin)
557 fclose(decoder->private_->file);
558 decoder->private_->file = 0;
561 if(decoder->private_->do_md5_checking) {
562 if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
565 decoder->private_->is_seeking = false;
567 set_defaults_(decoder);
569 decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
574 FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
576 FLAC__ASSERT(0 != decoder);
577 FLAC__ASSERT(0 != decoder->protected_);
578 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
580 decoder->protected_->md5_checking = value;
584 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
586 FLAC__ASSERT(0 != decoder);
587 FLAC__ASSERT(0 != decoder->private_);
588 FLAC__ASSERT(0 != decoder->protected_);
589 FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
590 /* double protection */
591 if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
593 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
595 decoder->private_->metadata_filter[type] = true;
596 if(type == FLAC__METADATA_TYPE_APPLICATION)
597 decoder->private_->metadata_filter_ids_count = 0;
601 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
603 FLAC__ASSERT(0 != decoder);
604 FLAC__ASSERT(0 != decoder->private_);
605 FLAC__ASSERT(0 != decoder->protected_);
606 FLAC__ASSERT(0 != id);
607 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
610 if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
613 FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
615 if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
616 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2))) {
617 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
620 decoder->private_->metadata_filter_ids_capacity *= 2;
623 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));
624 decoder->private_->metadata_filter_ids_count++;
629 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
632 FLAC__ASSERT(0 != decoder);
633 FLAC__ASSERT(0 != decoder->private_);
634 FLAC__ASSERT(0 != decoder->protected_);
635 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
637 for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
638 decoder->private_->metadata_filter[i] = true;
639 decoder->private_->metadata_filter_ids_count = 0;
643 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
645 FLAC__ASSERT(0 != decoder);
646 FLAC__ASSERT(0 != decoder->private_);
647 FLAC__ASSERT(0 != decoder->protected_);
648 FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
649 /* double protection */
650 if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
652 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
654 decoder->private_->metadata_filter[type] = false;
655 if(type == FLAC__METADATA_TYPE_APPLICATION)
656 decoder->private_->metadata_filter_ids_count = 0;
660 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
662 FLAC__ASSERT(0 != decoder);
663 FLAC__ASSERT(0 != decoder->private_);
664 FLAC__ASSERT(0 != decoder->protected_);
665 FLAC__ASSERT(0 != id);
666 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
669 if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
672 FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
674 if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
675 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2))) {
676 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
679 decoder->private_->metadata_filter_ids_capacity *= 2;
682 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));
683 decoder->private_->metadata_filter_ids_count++;
688 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
690 FLAC__ASSERT(0 != decoder);
691 FLAC__ASSERT(0 != decoder->private_);
692 FLAC__ASSERT(0 != decoder->protected_);
693 if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
695 memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
696 decoder->private_->metadata_filter_ids_count = 0;
700 FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
702 FLAC__ASSERT(0 != decoder);
703 FLAC__ASSERT(0 != decoder->protected_);
704 return decoder->protected_->state;
707 FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
709 return FLAC__StreamDecoderStateString[decoder->protected_->state];
712 FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
714 FLAC__ASSERT(0 != decoder);
715 FLAC__ASSERT(0 != decoder->protected_);
716 return decoder->protected_->md5_checking;
719 FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
721 FLAC__ASSERT(0 != decoder);
722 FLAC__ASSERT(0 != decoder->protected_);
723 return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
726 FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
728 FLAC__ASSERT(0 != decoder);
729 FLAC__ASSERT(0 != decoder->protected_);
730 return decoder->protected_->channels;
733 FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
735 FLAC__ASSERT(0 != decoder);
736 FLAC__ASSERT(0 != decoder->protected_);
737 return decoder->protected_->channel_assignment;
740 FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
742 FLAC__ASSERT(0 != decoder);
743 FLAC__ASSERT(0 != decoder->protected_);
744 return decoder->protected_->bits_per_sample;
747 FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
749 FLAC__ASSERT(0 != decoder);
750 FLAC__ASSERT(0 != decoder->protected_);
751 return decoder->protected_->sample_rate;
754 FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
756 FLAC__ASSERT(0 != decoder);
757 FLAC__ASSERT(0 != decoder->protected_);
758 return decoder->protected_->blocksize;
761 FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
763 FLAC__ASSERT(0 != decoder);
764 FLAC__ASSERT(0 != decoder->private_);
765 FLAC__ASSERT(0 != position);
767 if(0 == decoder->private_->tell_callback)
769 if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
771 FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
772 *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
776 FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
778 FLAC__ASSERT(0 != decoder);
779 FLAC__ASSERT(0 != decoder->private_);
780 FLAC__ASSERT(0 != decoder->protected_);
782 decoder->private_->samples_decoded = 0;
783 decoder->private_->do_md5_checking = false;
785 if(!FLAC__bitbuffer_clear(decoder->private_->input)) {
786 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
789 decoder->private_->last_frame_number = 0;
790 decoder->private_->last_block_size = 0;
791 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
796 FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
798 FLAC__ASSERT(0 != decoder);
799 FLAC__ASSERT(0 != decoder->private_);
800 FLAC__ASSERT(0 != decoder->protected_);
802 if(!FLAC__stream_decoder_flush(decoder)) {
803 /* above call sets the state for us */
807 /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
808 * (internal_reset_hack) don't try to rewind since we are already at
809 * the beginning of the stream and don't want to fail if the input is
812 if(!decoder->private_->internal_reset_hack) {
813 if(decoder->private_->file == stdin)
814 return false; /* can't rewind stdin, reset fails */
815 if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
816 return false; /* seekable and seek fails, reset fails */
819 decoder->private_->internal_reset_hack = false;
821 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
823 decoder->private_->has_stream_info = false;
824 if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
825 free(decoder->private_->seek_table.data.seek_table.points);
826 decoder->private_->seek_table.data.seek_table.points = 0;
827 decoder->private_->has_seek_table = false;
829 decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
831 /* We initialize the FLAC__MD5Context even though we may never use it. This
832 * is because md5 checking may be turned on to start and then turned off if
833 * a seek occurs. So we init the context here and finalize it in
834 * FLAC__seekable_stream_decoder_finish() to make sure things are always
835 * cleaned up properly.
837 FLAC__MD5Init(&decoder->private_->md5context);
839 decoder->private_->first_frame_offset = 0;
840 decoder->private_->unparseable_frame_count = 0;
845 FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
847 FLAC__bool got_a_frame;
848 FLAC__ASSERT(0 != decoder);
849 FLAC__ASSERT(0 != decoder->protected_);
852 switch(decoder->protected_->state) {
853 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
854 if(!find_metadata_(decoder))
855 return false; /* above function sets the status for us */
857 case FLAC__STREAM_DECODER_READ_METADATA:
858 if(!read_metadata_(decoder))
859 return false; /* above function sets the status for us */
862 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
863 if(!frame_sync_(decoder))
864 return true; /* above function sets the status for us */
866 case FLAC__STREAM_DECODER_READ_FRAME:
867 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
868 return false; /* above function sets the status for us */
870 return true; /* above function sets the status for us */
872 case FLAC__STREAM_DECODER_END_OF_STREAM:
873 case FLAC__STREAM_DECODER_ABORTED:
882 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
884 FLAC__ASSERT(0 != decoder);
885 FLAC__ASSERT(0 != decoder->protected_);
888 switch(decoder->protected_->state) {
889 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
890 if(!find_metadata_(decoder))
891 return false; /* above function sets the status for us */
893 case FLAC__STREAM_DECODER_READ_METADATA:
894 if(!read_metadata_(decoder))
895 return false; /* above function sets the status for us */
897 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
898 case FLAC__STREAM_DECODER_READ_FRAME:
899 case FLAC__STREAM_DECODER_END_OF_STREAM:
900 case FLAC__STREAM_DECODER_ABORTED:
909 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
912 FLAC__ASSERT(0 != decoder);
913 FLAC__ASSERT(0 != decoder->protected_);
916 switch(decoder->protected_->state) {
917 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
918 if(!find_metadata_(decoder))
919 return false; /* above function sets the status for us */
921 case FLAC__STREAM_DECODER_READ_METADATA:
922 if(!read_metadata_(decoder))
923 return false; /* above function sets the status for us */
925 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
926 if(!frame_sync_(decoder))
927 return true; /* above function sets the status for us */
929 case FLAC__STREAM_DECODER_READ_FRAME:
930 if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
931 return false; /* above function sets the status for us */
933 case FLAC__STREAM_DECODER_END_OF_STREAM:
934 case FLAC__STREAM_DECODER_ABORTED:
943 FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
945 FLAC__bool got_a_frame;
946 FLAC__ASSERT(0 != decoder);
947 FLAC__ASSERT(0 != decoder->protected_);
950 switch(decoder->protected_->state) {
951 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
952 case FLAC__STREAM_DECODER_READ_METADATA:
953 return false; /* above function sets the status for us */
954 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
955 if(!frame_sync_(decoder))
956 return true; /* above function sets the status for us */
958 case FLAC__STREAM_DECODER_READ_FRAME:
959 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
960 return false; /* above function sets the status for us */
962 return true; /* above function sets the status for us */
964 case FLAC__STREAM_DECODER_END_OF_STREAM:
965 case FLAC__STREAM_DECODER_ABORTED:
974 FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
978 FLAC__ASSERT(0 != decoder);
981 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
982 decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
983 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
984 decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
985 decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
989 if(0 == decoder->private_->seek_callback)
992 FLAC__ASSERT(decoder->private_->seek_callback);
993 FLAC__ASSERT(decoder->private_->tell_callback);
994 FLAC__ASSERT(decoder->private_->length_callback);
995 FLAC__ASSERT(decoder->private_->eof_callback);
997 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
1000 decoder->private_->is_seeking = true;
1002 /* turn off md5 checking if a seek is attempted */
1003 decoder->private_->do_md5_checking = false;
1005 /* 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) */
1006 if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
1007 decoder->private_->is_seeking = false;
1010 /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
1012 decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
1013 decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
1015 if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
1016 /* above call sets the state for us */
1017 decoder->private_->is_seeking = false;
1020 /* check this again in case we didn't know total_samples the first time */
1021 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
1022 decoder->private_->is_seeking = false;
1028 FLAC__bool ok = seek_to_absolute_sample_(decoder, length, sample);
1029 decoder->private_->is_seeking = false;
1034 /***********************************************************************
1036 * Protected class methods
1038 ***********************************************************************/
1040 unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
1042 FLAC__ASSERT(0 != decoder);
1043 return FLAC__bitbuffer_get_input_bytes_unconsumed(decoder->private_->input);
1046 /***********************************************************************
1048 * Private class methods
1050 ***********************************************************************/
1052 void set_defaults_(FLAC__StreamDecoder *decoder)
1054 decoder->private_->read_callback = 0;
1055 decoder->private_->seek_callback = 0;
1056 decoder->private_->tell_callback = 0;
1057 decoder->private_->length_callback = 0;
1058 decoder->private_->eof_callback = 0;
1059 decoder->private_->write_callback = 0;
1060 decoder->private_->metadata_callback = 0;
1061 decoder->private_->error_callback = 0;
1062 decoder->private_->client_data = 0;
1064 memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
1065 decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
1066 decoder->private_->metadata_filter_ids_count = 0;
1068 decoder->protected_->md5_checking = false;
1072 * This will forcibly set stdin to binary mode (for OSes that require it)
1074 FILE *get_binary_stdin_()
1076 /* if something breaks here it is probably due to the presence or
1077 * absence of an underscore before the identifiers 'setmode',
1078 * 'fileno', and/or 'O_BINARY'; check your system header files.
1080 #if defined _MSC_VER || defined __MINGW32__
1081 _setmode(_fileno(stdin), _O_BINARY);
1082 #elif defined __CYGWIN__ || defined __EMX__
1083 /* almost certainly not needed for any modern Cygwin, but let's be safe... */
1084 setmode(_fileno(stdin), _O_BINARY);
1090 FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
1095 if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
1098 /* simply using realloc() is not practical because the number of channels may change mid-stream */
1100 for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
1101 if(0 != decoder->private_->output[i]) {
1102 free(decoder->private_->output[i]-4);
1103 decoder->private_->output[i] = 0;
1105 if(0 != decoder->private_->residual_unaligned[i]) {
1106 free(decoder->private_->residual_unaligned[i]);
1107 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
1111 for(i = 0; i < channels; i++) {
1113 * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
1114 * output arrays have a buffer of up to 3 zeroes in front
1115 * (at negative indices) for alignment purposes; we use 4
1116 * to keep the data well-aligned.
1118 tmp = (FLAC__int32*)malloc(sizeof(FLAC__int32)*(size+4));
1120 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1123 memset(tmp, 0, sizeof(FLAC__int32)*4);
1124 decoder->private_->output[i] = tmp + 4;
1127 * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
1129 if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
1130 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1135 decoder->private_->output_capacity = size;
1136 decoder->private_->output_channels = channels;
1141 FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
1145 FLAC__ASSERT(0 != decoder);
1146 FLAC__ASSERT(0 != decoder->private_);
1148 for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
1149 if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
1155 FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
1159 FLAC__bool first = true;
1161 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1163 for(i = id = 0; i < 4; ) {
1164 if(decoder->private_->cached) {
1165 x = (FLAC__uint32)decoder->private_->lookahead;
1166 decoder->private_->cached = false;
1169 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1170 return false; /* read_callback_ sets the state for us */
1172 if(x == FLAC__STREAM_SYNC_STRING[i]) {
1178 if(x == ID3V2_TAG_[id]) {
1182 if(!skip_id3v2_tag_(decoder))
1183 return false; /* skip_id3v2_tag_ sets the state for us */
1188 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1189 decoder->private_->header_warmup[0] = (FLAC__byte)x;
1190 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1191 return false; /* read_callback_ sets the state for us */
1193 /* 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 */
1194 /* else we have to check if the second byte is the end of a sync code */
1195 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1196 decoder->private_->lookahead = (FLAC__byte)x;
1197 decoder->private_->cached = true;
1199 else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1200 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1201 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1207 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1212 decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
1216 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
1219 FLAC__uint32 i, x, type, length;
1221 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1223 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN, read_callback_, decoder))
1224 return false; /* read_callback_ sets the state for us */
1225 is_last = x? true : false;
1227 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN, read_callback_, decoder))
1228 return false; /* read_callback_ sets the state for us */
1230 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN, read_callback_, decoder))
1231 return false; /* read_callback_ sets the state for us */
1233 if(type == FLAC__METADATA_TYPE_STREAMINFO) {
1234 if(!read_metadata_streaminfo_(decoder, is_last, length))
1237 decoder->private_->has_stream_info = true;
1238 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))
1239 decoder->private_->do_md5_checking = false;
1240 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
1241 decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
1243 else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
1244 if(!read_metadata_seektable_(decoder, is_last, length))
1247 decoder->private_->has_seek_table = true;
1248 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
1249 decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
1252 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
1253 unsigned real_length = length;
1254 FLAC__StreamMetadata block;
1256 block.is_last = is_last;
1257 block.type = (FLAC__MetadataType)type;
1258 block.length = length;
1260 if(type == FLAC__METADATA_TYPE_APPLICATION) {
1261 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))
1262 return false; /* read_callback_ sets the state for us */
1264 real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
1266 if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
1271 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
1272 return false; /* read_callback_ sets the state for us */
1276 case FLAC__METADATA_TYPE_PADDING:
1277 /* skip the padding bytes */
1278 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
1279 return false; /* read_callback_ sets the state for us */
1281 case FLAC__METADATA_TYPE_APPLICATION:
1282 /* remember, we read the ID already */
1283 if(real_length > 0) {
1284 if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
1285 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1288 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length, read_callback_, decoder))
1289 return false; /* read_callback_ sets the state for us */
1292 block.data.application.data = 0;
1294 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1295 if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
1298 case FLAC__METADATA_TYPE_CUESHEET:
1299 if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
1302 case FLAC__METADATA_TYPE_PICTURE:
1303 if(!read_metadata_picture_(decoder, &block.data.picture))
1306 case FLAC__METADATA_TYPE_STREAMINFO:
1307 case FLAC__METADATA_TYPE_SEEKTABLE:
1311 if(real_length > 0) {
1312 if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
1313 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1316 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length, read_callback_, decoder))
1317 return false; /* read_callback_ sets the state for us */
1320 block.data.unknown.data = 0;
1323 if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
1324 decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1326 /* now we have to free any malloc'ed data in the block */
1328 case FLAC__METADATA_TYPE_PADDING:
1330 case FLAC__METADATA_TYPE_APPLICATION:
1331 if(0 != block.data.application.data)
1332 free(block.data.application.data);
1334 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1335 if(0 != block.data.vorbis_comment.vendor_string.entry)
1336 free(block.data.vorbis_comment.vendor_string.entry);
1337 if(block.data.vorbis_comment.num_comments > 0)
1338 for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
1339 if(0 != block.data.vorbis_comment.comments[i].entry)
1340 free(block.data.vorbis_comment.comments[i].entry);
1341 if(0 != block.data.vorbis_comment.comments)
1342 free(block.data.vorbis_comment.comments);
1344 case FLAC__METADATA_TYPE_CUESHEET:
1345 if(block.data.cue_sheet.num_tracks > 0)
1346 for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
1347 if(0 != block.data.cue_sheet.tracks[i].indices)
1348 free(block.data.cue_sheet.tracks[i].indices);
1349 if(0 != block.data.cue_sheet.tracks)
1350 free(block.data.cue_sheet.tracks);
1352 case FLAC__METADATA_TYPE_PICTURE:
1353 if(0 != block.data.picture.mime_type)
1354 free(block.data.picture.mime_type);
1355 if(0 != block.data.picture.description)
1356 free(block.data.picture.description);
1357 if(0 != block.data.picture.data)
1358 free(block.data.picture.data);
1360 case FLAC__METADATA_TYPE_STREAMINFO:
1361 case FLAC__METADATA_TYPE_SEEKTABLE:
1364 if(0 != block.data.unknown.data)
1365 free(block.data.unknown.data);
1372 /* if this fails, it's OK, it's just a hint for the seek routine */
1373 if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
1374 decoder->private_->first_frame_offset = 0;
1375 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1381 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1384 unsigned bits, used_bits = 0;
1386 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1388 decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
1389 decoder->private_->stream_info.is_last = is_last;
1390 decoder->private_->stream_info.length = length;
1392 bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1393 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, bits, read_callback_, decoder))
1394 return false; /* read_callback_ sets the state for us */
1395 decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1398 bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1399 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN, read_callback_, decoder))
1400 return false; /* read_callback_ sets the state for us */
1401 decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1404 bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1405 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN, read_callback_, decoder))
1406 return false; /* read_callback_ sets the state for us */
1407 decoder->private_->stream_info.data.stream_info.min_framesize = x;
1410 bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1411 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN, read_callback_, decoder))
1412 return false; /* read_callback_ sets the state for us */
1413 decoder->private_->stream_info.data.stream_info.max_framesize = x;
1416 bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1417 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN, read_callback_, decoder))
1418 return false; /* read_callback_ sets the state for us */
1419 decoder->private_->stream_info.data.stream_info.sample_rate = x;
1422 bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1423 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN, read_callback_, decoder))
1424 return false; /* read_callback_ sets the state for us */
1425 decoder->private_->stream_info.data.stream_info.channels = x+1;
1428 bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1429 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN, read_callback_, decoder))
1430 return false; /* read_callback_ sets the state for us */
1431 decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1434 bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1435 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))
1436 return false; /* read_callback_ sets the state for us */
1439 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16, read_callback_, decoder))
1440 return false; /* read_callback_ sets the state for us */
1443 /* skip the rest of the block */
1444 FLAC__ASSERT(used_bits % 8 == 0);
1445 length -= (used_bits / 8);
1446 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1447 return false; /* read_callback_ sets the state for us */
1452 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1457 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1459 decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1460 decoder->private_->seek_table.is_last = is_last;
1461 decoder->private_->seek_table.length = length;
1463 decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1465 /* use realloc since we may pass through here several times (e.g. after seeking) */
1466 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)))) {
1467 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1470 for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1471 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN, read_callback_, decoder))
1472 return false; /* read_callback_ sets the state for us */
1473 decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1475 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN, read_callback_, decoder))
1476 return false; /* read_callback_ sets the state for us */
1477 decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1479 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN, read_callback_, decoder))
1480 return false; /* read_callback_ sets the state for us */
1481 decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1483 length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1484 /* if there is a partial point left, skip over it */
1486 /*@@@ do an error_callback() here? there's an argument for either way */
1487 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1488 return false; /* read_callback_ sets the state for us */
1494 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1498 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1500 /* read vendor string */
1501 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1502 if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length, read_callback_, decoder))
1503 return false; /* read_callback_ sets the state for us */
1504 if(obj->vendor_string.length > 0) {
1505 if(0 == (obj->vendor_string.entry = (FLAC__byte*)malloc(obj->vendor_string.length+1))) {
1506 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1509 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length, read_callback_, decoder))
1510 return false; /* read_callback_ sets the state for us */
1511 obj->vendor_string.entry[obj->vendor_string.length] = '\0';
1514 obj->vendor_string.entry = 0;
1516 /* read num comments */
1517 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1518 if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->num_comments, read_callback_, decoder))
1519 return false; /* read_callback_ sets the state for us */
1522 if(obj->num_comments > 0) {
1523 if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)malloc(obj->num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1524 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1527 for(i = 0; i < obj->num_comments; i++) {
1528 FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1529 if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->comments[i].length, read_callback_, decoder))
1530 return false; /* read_callback_ sets the state for us */
1531 if(obj->comments[i].length > 0) {
1532 if(0 == (obj->comments[i].entry = (FLAC__byte*)malloc(obj->comments[i].length+1))) {
1533 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1536 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length, read_callback_, decoder))
1537 return false; /* read_callback_ sets the state for us */
1538 obj->comments[i].entry[obj->comments[i].length] = '\0';
1541 obj->comments[i].entry = 0;
1551 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1553 FLAC__uint32 i, j, x;
1555 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1557 memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1559 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1560 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))
1561 return false; /* read_callback_ sets the state for us */
1563 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN, read_callback_, decoder))
1564 return false; /* read_callback_ sets the state for us */
1566 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN, read_callback_, decoder))
1567 return false; /* read_callback_ sets the state for us */
1568 obj->is_cd = x? true : false;
1570 if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN, read_callback_, decoder))
1571 return false; /* read_callback_ sets the state for us */
1573 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN, read_callback_, decoder))
1574 return false; /* read_callback_ sets the state for us */
1575 obj->num_tracks = x;
1577 if(obj->num_tracks > 0) {
1578 if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1579 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1582 for(i = 0; i < obj->num_tracks; i++) {
1583 FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1584 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN, read_callback_, decoder))
1585 return false; /* read_callback_ sets the state for us */
1587 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN, read_callback_, decoder))
1588 return false; /* read_callback_ sets the state for us */
1589 track->number = (FLAC__byte)x;
1591 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1592 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))
1593 return false; /* read_callback_ sets the state for us */
1595 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN, read_callback_, decoder))
1596 return false; /* read_callback_ sets the state for us */
1599 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN, read_callback_, decoder))
1600 return false; /* read_callback_ sets the state for us */
1601 track->pre_emphasis = x;
1603 if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN, read_callback_, decoder))
1604 return false; /* read_callback_ sets the state for us */
1606 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN, read_callback_, decoder))
1607 return false; /* read_callback_ sets the state for us */
1608 track->num_indices = (FLAC__byte)x;
1610 if(track->num_indices > 0) {
1611 if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1612 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1615 for(j = 0; j < track->num_indices; j++) {
1616 FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1617 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN, 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_INDEX_NUMBER_LEN, read_callback_, decoder))
1621 return false; /* read_callback_ sets the state for us */
1622 index->number = (FLAC__byte)x;
1624 if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN, read_callback_, decoder))
1625 return false; /* read_callback_ sets the state for us */
1634 FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
1638 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1641 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN, read_callback_, decoder))
1642 return false; /* read_callback_ sets the state for us */
1644 /* read MIME type */
1645 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN, read_callback_, decoder))
1646 return false; /* read_callback_ sets the state for us */
1647 if(0 == (obj->mime_type = (char*)malloc(len+1))) {
1648 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1652 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, len, read_callback_, decoder))
1653 return false; /* read_callback_ sets the state for us */
1655 obj->mime_type[len] = '\0';
1657 /* read description */
1658 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN, read_callback_, decoder))
1659 return false; /* read_callback_ sets the state for us */
1660 if(0 == (obj->description = (FLAC__byte*)malloc(len+1))) {
1661 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1665 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, len, read_callback_, decoder))
1666 return false; /* read_callback_ sets the state for us */
1668 obj->description[len] = '\0';
1671 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN, read_callback_, decoder))
1672 return false; /* read_callback_ sets the state for us */
1675 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN, read_callback_, decoder))
1676 return false; /* read_callback_ sets the state for us */
1679 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN, read_callback_, decoder))
1680 return false; /* read_callback_ sets the state for us */
1683 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN, read_callback_, decoder))
1684 return false; /* read_callback_ sets the state for us */
1687 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN, read_callback_, decoder))
1688 return false; /* read_callback_ sets the state for us */
1689 if(0 == (obj->data = (FLAC__byte*)malloc(obj->data_length))) {
1690 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1693 if(obj->data_length > 0) {
1694 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length, read_callback_, decoder))
1695 return false; /* read_callback_ sets the state for us */
1701 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1706 /* skip the version and flags bytes */
1707 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 24, read_callback_, decoder))
1708 return false; /* read_callback_ sets the state for us */
1709 /* get the size (in bytes) to skip */
1711 for(i = 0; i < 4; i++) {
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 */
1717 /* skip the rest of the tag */
1718 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, skip, read_callback_, decoder))
1719 return false; /* read_callback_ sets the state for us */
1723 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1726 FLAC__bool first = true;
1728 /* If we know the total number of samples in the stream, stop if we've read that many. */
1729 /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1730 if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
1731 if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
1732 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1737 /* make sure we're byte aligned */
1738 if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
1739 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
1740 return false; /* read_callback_ sets the state for us */
1744 if(decoder->private_->cached) {
1745 x = (FLAC__uint32)decoder->private_->lookahead;
1746 decoder->private_->cached = false;
1749 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1750 return false; /* read_callback_ sets the state for us */
1752 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1753 decoder->private_->header_warmup[0] = (FLAC__byte)x;
1754 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1755 return false; /* read_callback_ sets the state for us */
1757 /* 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 */
1758 /* else we have to check if the second byte is the end of a sync code */
1759 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1760 decoder->private_->lookahead = (FLAC__byte)x;
1761 decoder->private_->cached = true;
1763 else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1764 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1765 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1770 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1778 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
1782 FLAC__int32 mid, side, left, right;
1783 FLAC__uint16 frame_crc; /* the one we calculate from the input stream */
1786 *got_a_frame = false;
1790 FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
1791 FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
1792 FLAC__bitbuffer_reset_read_crc16(decoder->private_->input, frame_crc);
1794 if(!read_frame_header_(decoder))
1796 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
1798 if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
1800 for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1802 * first figure the correct bits-per-sample of the subframe
1804 unsigned bps = decoder->private_->frame.header.bits_per_sample;
1805 switch(decoder->private_->frame.header.channel_assignment) {
1806 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1807 /* no adjustment needed */
1809 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1810 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1814 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1815 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1819 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1820 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1830 if(!read_subframe_(decoder, channel, bps, do_full_decode))
1832 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
1835 if(!read_zero_padding_(decoder))
1839 * Read the frame CRC-16 from the footer and check
1841 frame_crc = FLAC__bitbuffer_get_read_crc16(decoder->private_->input);
1842 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN, read_callback_, decoder))
1843 return false; /* read_callback_ sets the state for us */
1844 if(frame_crc == (FLAC__uint16)x) {
1845 if(do_full_decode) {
1846 /* Undo any special channel coding */
1847 switch(decoder->private_->frame.header.channel_assignment) {
1848 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1851 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1852 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1853 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1854 decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
1856 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1857 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1858 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1859 decoder->private_->output[0][i] += decoder->private_->output[1][i];
1861 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1862 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1863 for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
1864 mid = decoder->private_->output[0][i];
1865 side = decoder->private_->output[1][i];
1867 if(side & 1) /* i.e. if 'side' is odd... */
1871 decoder->private_->output[0][i] = left >> 1;
1872 decoder->private_->output[1][i] = right >> 1;
1882 /* Bad frame, emit error and zero the output signal */
1883 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
1884 if(do_full_decode) {
1885 for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1886 memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
1891 *got_a_frame = true;
1893 /* put the latest values into the public section of the decoder instance */
1894 decoder->protected_->channels = decoder->private_->frame.header.channels;
1895 decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
1896 decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
1897 decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
1898 decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
1900 FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1901 decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
1904 if(do_full_decode) {
1905 if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
1909 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1913 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
1917 unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
1918 FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
1919 unsigned raw_header_len;
1920 FLAC__bool is_unparseable = false;
1921 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);
1922 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);
1924 FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1926 /* init the raw header with the saved bits from synchronization */
1927 raw_header[0] = decoder->private_->header_warmup[0];
1928 raw_header[1] = decoder->private_->header_warmup[1];
1932 * check to make sure that the reserved bits are 0
1934 if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
1935 is_unparseable = true;
1939 * Note that along the way as we read the header, we look for a sync
1940 * code inside. If we find one it would indicate that our original
1941 * sync was bad since there cannot be a sync code in a valid header.
1945 * read in the raw header as bytes so we can CRC it, and parse it on the way
1947 for(i = 0; i < 2; i++) {
1948 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1949 return false; /* read_callback_ sets the state for us */
1950 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1951 /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
1952 decoder->private_->lookahead = (FLAC__byte)x;
1953 decoder->private_->cached = true;
1954 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
1955 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1958 raw_header[raw_header_len++] = (FLAC__byte)x;
1961 switch(x = raw_header[2] >> 4) {
1963 if(is_known_fixed_blocksize_stream)
1964 decoder->private_->frame.header.blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
1966 is_unparseable = true;
1969 decoder->private_->frame.header.blocksize = 192;
1975 decoder->private_->frame.header.blocksize = 576 << (x-2);
1989 decoder->private_->frame.header.blocksize = 256 << (x-8);
1996 switch(x = raw_header[2] & 0x0f) {
1998 if(decoder->private_->has_stream_info)
1999 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
2001 is_unparseable = true;
2006 is_unparseable = true;
2009 decoder->private_->frame.header.sample_rate = 8000;
2012 decoder->private_->frame.header.sample_rate = 16000;
2015 decoder->private_->frame.header.sample_rate = 22050;
2018 decoder->private_->frame.header.sample_rate = 24000;
2021 decoder->private_->frame.header.sample_rate = 32000;
2024 decoder->private_->frame.header.sample_rate = 44100;
2027 decoder->private_->frame.header.sample_rate = 48000;
2030 decoder->private_->frame.header.sample_rate = 96000;
2035 sample_rate_hint = x;
2038 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2039 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2045 x = (unsigned)(raw_header[3] >> 4);
2047 decoder->private_->frame.header.channels = 2;
2050 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2053 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2056 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2059 is_unparseable = true;
2064 decoder->private_->frame.header.channels = (unsigned)x + 1;
2065 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2068 switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2070 if(decoder->private_->has_stream_info)
2071 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2073 is_unparseable = true;
2076 decoder->private_->frame.header.bits_per_sample = 8;
2079 decoder->private_->frame.header.bits_per_sample = 12;
2082 decoder->private_->frame.header.bits_per_sample = 16;
2085 decoder->private_->frame.header.bits_per_sample = 20;
2088 decoder->private_->frame.header.bits_per_sample = 24;
2092 is_unparseable = true;
2099 if(raw_header[3] & 0x01) { /* this should be a zero padding bit */
2100 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2101 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2106 * Now we get to the regrettable consequences of not knowing for sure
2107 * whether we got a frame number or a sample number. There are no
2108 * encoders that do variable-blocksize encoding so unless we know from
2109 * the STREAMINFO that it is variable-blocksize we will assume it is
2110 * fixed-blocksize. The trouble comes when we have no STREAMINFO; again
2111 * we will guess that is fixed-blocksize. Where this can go wrong: 1) a
2112 * variable-blocksize stream with no STREAMINFO; 2) a fixed-blocksize
2113 * stream that was edited such that one or more frames before or
2114 * including this one do not have the same number of samples as the
2115 * STREAMINFO's min and max blocksize.
2117 if(is_known_variable_blocksize_stream) {
2118 if(blocksize_hint) {
2119 if(!FLAC__bitbuffer_read_utf8_uint64(decoder->private_->input, &xx, read_callback_, decoder, raw_header, &raw_header_len))
2120 return false; /* read_callback_ sets the state for us */
2121 if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
2122 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2123 decoder->private_->cached = true;
2124 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2125 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2128 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2129 decoder->private_->frame.header.number.sample_number = xx;
2132 is_unparseable = true;
2135 if(!FLAC__bitbuffer_read_utf8_uint32(decoder->private_->input, &x, read_callback_, decoder, raw_header, &raw_header_len))
2136 return false; /* read_callback_ sets the state for us */
2137 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
2138 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2139 decoder->private_->cached = true;
2140 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2141 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2144 decoder->private_->last_frame_number = x;
2145 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2146 if(decoder->private_->has_stream_info) {
2147 FLAC__ASSERT(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize);
2148 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
2149 decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2151 else if(blocksize_hint) {
2152 if(decoder->private_->last_block_size)
2153 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->last_block_size * (FLAC__uint64)x;
2155 is_unparseable = true;
2158 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
2159 decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2163 if(blocksize_hint) {
2164 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2165 return false; /* read_callback_ sets the state for us */
2166 raw_header[raw_header_len++] = (FLAC__byte)x;
2167 if(blocksize_hint == 7) {
2169 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
2170 return false; /* read_callback_ sets the state for us */
2171 raw_header[raw_header_len++] = (FLAC__byte)_x;
2174 decoder->private_->frame.header.blocksize = x+1;
2177 if(sample_rate_hint) {
2178 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2179 return false; /* read_callback_ sets the state for us */
2180 raw_header[raw_header_len++] = (FLAC__byte)x;
2181 if(sample_rate_hint != 12) {
2183 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
2184 return false; /* read_callback_ sets the state for us */
2185 raw_header[raw_header_len++] = (FLAC__byte)_x;
2188 if(sample_rate_hint == 12)
2189 decoder->private_->frame.header.sample_rate = x*1000;
2190 else if(sample_rate_hint == 13)
2191 decoder->private_->frame.header.sample_rate = x;
2193 decoder->private_->frame.header.sample_rate = x*10;
2196 /* read the CRC-8 byte */
2197 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2198 return false; /* read_callback_ sets the state for us */
2199 crc8 = (FLAC__byte)x;
2201 if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
2202 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2203 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2207 if(is_unparseable) {
2208 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2209 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2216 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2219 FLAC__bool wasted_bits;
2222 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder)) /* MAGIC NUMBER */
2223 return false; /* read_callback_ sets the state for us */
2225 wasted_bits = (x & 1);
2230 if(!FLAC__bitbuffer_read_unary_unsigned(decoder->private_->input, &u, read_callback_, decoder))
2231 return false; /* read_callback_ sets the state for us */
2232 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
2233 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
2236 decoder->private_->frame.subframes[channel].wasted_bits = 0;
2239 * Lots of magic numbers here
2242 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2243 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2247 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2251 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2255 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2256 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2260 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2262 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2266 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2267 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2271 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2273 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2277 if(wasted_bits && do_full_decode) {
2278 x = decoder->private_->frame.subframes[channel].wasted_bits;
2279 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2280 decoder->private_->output[channel][i] <<= x;
2286 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2288 FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2291 FLAC__int32 *output = decoder->private_->output[channel];
2293 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2295 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
2296 return false; /* read_callback_ sets the state for us */
2298 subframe->value = x;
2300 /* decode the subframe */
2301 if(do_full_decode) {
2302 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2309 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2311 FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2316 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2318 subframe->residual = decoder->private_->residual[channel];
2319 subframe->order = order;
2321 /* read warm-up samples */
2322 for(u = 0; u < order; u++) {
2323 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
2324 return false; /* read_callback_ sets the state for us */
2325 subframe->warmup[u] = i32;
2328 /* read entropy coding method info */
2329 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
2330 return false; /* read_callback_ sets the state for us */
2331 subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2332 switch(subframe->entropy_coding_method.type) {
2333 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2334 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
2335 return false; /* read_callback_ sets the state for us */
2336 subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2337 subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2340 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2341 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2346 switch(subframe->entropy_coding_method.type) {
2347 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2348 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]))
2355 /* decode the subframe */
2356 if(do_full_decode) {
2357 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2358 FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
2364 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2366 FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2371 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2373 subframe->residual = decoder->private_->residual[channel];
2374 subframe->order = order;
2376 /* read warm-up samples */
2377 for(u = 0; u < order; u++) {
2378 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
2379 return false; /* read_callback_ sets the state for us */
2380 subframe->warmup[u] = i32;
2383 /* read qlp coeff precision */
2384 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN, read_callback_, decoder))
2385 return false; /* read_callback_ sets the state for us */
2386 if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
2387 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2388 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2391 subframe->qlp_coeff_precision = u32+1;
2393 /* read qlp shift */
2394 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN, read_callback_, decoder))
2395 return false; /* read_callback_ sets the state for us */
2396 subframe->quantization_level = i32;
2398 /* read quantized lp coefficiencts */
2399 for(u = 0; u < order; u++) {
2400 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision, read_callback_, decoder))
2401 return false; /* read_callback_ sets the state for us */
2402 subframe->qlp_coeff[u] = i32;
2405 /* read entropy coding method info */
2406 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
2407 return false; /* read_callback_ sets the state for us */
2408 subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2409 switch(subframe->entropy_coding_method.type) {
2410 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2411 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
2412 return false; /* read_callback_ sets the state for us */
2413 subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2414 subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2417 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2418 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2423 switch(subframe->entropy_coding_method.type) {
2424 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2425 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]))
2432 /* decode the subframe */
2433 if(do_full_decode) {
2434 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2435 if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2436 if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2438 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);
2440 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);
2443 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);
2445 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);
2451 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2453 FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2454 FLAC__int32 x, *residual = decoder->private_->residual[channel];
2457 decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2459 subframe->data = residual;
2461 for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2462 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
2463 return false; /* read_callback_ sets the state for us */
2467 /* decode the subframe */
2469 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2474 FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual)
2476 FLAC__uint32 rice_parameter;
2478 unsigned partition, sample, u;
2479 const unsigned partitions = 1u << partition_order;
2480 const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2483 if(partition_order == 0) {
2484 if(decoder->private_->frame.header.blocksize < predictor_order) {
2485 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2486 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2491 if(partition_samples < predictor_order) {
2492 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2493 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2498 if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2499 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2504 for(partition = 0; partition < partitions; partition++) {
2505 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN, read_callback_, decoder))
2506 return false; /* read_callback_ sets the state for us */
2507 partitioned_rice_contents->parameters[partition] = rice_parameter;
2508 if(rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2509 u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2510 if(!FLAC__bitbuffer_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter, read_callback_, decoder))
2511 return false; /* read_callback_ sets the state for us */
2515 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN, read_callback_, decoder))
2516 return false; /* read_callback_ sets the state for us */
2517 partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2518 for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2519 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i, rice_parameter, read_callback_, decoder))
2520 return false; /* read_callback_ sets the state for us */
2521 residual[sample] = i;
2529 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2531 if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
2532 FLAC__uint32 zero = 0;
2533 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
2534 return false; /* read_callback_ sets the state for us */
2536 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2537 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2543 FLAC__bool read_callback_(FLAC__byte buffer[], unsigned *bytes, void *client_data)
2545 FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2547 if(decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)) {
2549 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2552 else if(*bytes > 0) {
2553 /* While seeking, it is possible for our seek to land in the
2554 * middle of audio data that looks exactly like a frame header
2555 * from a future version of an encoder. When that happens, our
2556 * error callback will get an
2557 * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
2558 * unparseable_frame_count. But there is a remote possibility
2559 * that it is properly synced at such a "future-codec frame",
2560 * so to make sure, we wait to see many "unparseable" errors in
2561 * a row before bailing out.
2563 if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2564 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2568 const FLAC__StreamDecoderReadStatus status = decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data);
2569 if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
2570 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2573 else if(*bytes == 0) {
2574 if(status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM || (decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data))) {
2575 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2586 /* abort to avoid a deadlock */
2587 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2592 FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2594 if(decoder->private_->is_seeking) {
2595 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
2596 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
2597 FLAC__uint64 target_sample = decoder->private_->target_sample;
2599 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2601 decoder->private_->last_frame = *frame; /* save the frame */
2602 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
2603 unsigned delta = (unsigned)(target_sample - this_frame_sample);
2604 /* kick out of seek mode */
2605 decoder->private_->is_seeking = false;
2606 /* shift out the samples before target_sample */
2609 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
2610 for(channel = 0; channel < frame->header.channels; channel++)
2611 newbuffer[channel] = buffer[channel] + delta;
2612 decoder->private_->last_frame.header.blocksize -= delta;
2613 decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
2614 /* write the relevant samples */
2615 return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
2618 /* write the relevant samples */
2619 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2623 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2628 * If we never got STREAMINFO, turn off MD5 checking to save
2629 * cycles since we don't have a sum to compare to anyway
2631 if(!decoder->private_->has_stream_info)
2632 decoder->private_->do_md5_checking = false;
2633 if(decoder->private_->do_md5_checking) {
2634 if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
2635 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2637 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2641 void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2643 if(!decoder->private_->is_seeking)
2644 decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
2645 else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
2646 decoder->private_->unparseable_frame_count++;
2649 FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2651 FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound;
2652 FLAC__int64 pos = -1, last_pos = -1;
2653 int i, lower_seek_point = -1, upper_seek_point = -1;
2654 unsigned approx_bytes_per_frame;
2655 FLAC__uint64 last_frame_sample = FLAC__U64L(0xffffffffffffffff);
2656 FLAC__bool needs_seek;
2657 const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
2658 const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2659 const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
2660 const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
2661 const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
2662 const unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
2663 const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
2665 /* we are just guessing here, but we want to guess high, not low */
2666 if(max_framesize > 0)
2667 approx_bytes_per_frame = max_framesize;
2670 * Check if it's a known fixed-blocksize stream. Note that though
2671 * the spec doesn't allow zeroes in the STREAMINFO block, we may
2672 * never get a STREAMINFO block when decoding so the value of
2673 * min_blocksize might be zero.
2675 else if(min_blocksize == max_blocksize && min_blocksize > 0) {
2676 /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
2677 approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
2680 approx_bytes_per_frame = 4608 * channels * bps/8 + 64;
2683 * First, we set an upper and lower bound on where in the
2684 * stream we will search. For now we assume the worst case
2685 * scenario, which is our best guess at the beginning of
2686 * the first and last frames.
2688 lower_bound = first_frame_offset;
2690 /* calc the upper_bound, beyond which we never want to seek */
2691 if(max_framesize > 0)
2692 upper_bound = stream_length - (max_framesize + 128 + 2); /* 128 for a possible ID3V1 tag, 2 for indexing differences */
2694 upper_bound = stream_length - ((channels * bps * FLAC__MAX_BLOCK_SIZE) / 8 + 128 + 2);
2697 * Now we refine the bounds if we have a seektable with
2698 * suitable points. Note that according to the spec they
2699 * must be ordered by ascending sample number.
2702 /* find the closest seek point <= target_sample, if it exists */
2703 for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
2704 if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number <= target_sample)
2707 if(i >= 0) { /* i.e. we found a suitable seek point... */
2708 lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
2709 lower_seek_point = i;
2712 /* find the closest seek point > target_sample, if it exists */
2713 for(i = 0; i < (int)seek_table->num_points; i++) {
2714 if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number > target_sample)
2717 if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
2718 upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
2719 upper_seek_point = i;
2724 * Now guess at where within those bounds our target
2727 if(seek_table && lower_seek_point >= 0) {
2728 /* first see if our sample is within a few frames of the lower seekpoint */
2729 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)) {
2730 pos = (FLAC__int64)lower_bound;
2732 else if(upper_seek_point >= 0) {
2733 const FLAC__uint64 target_offset = target_sample - seek_table->points[lower_seek_point].sample_number;
2734 const FLAC__uint64 range_samples = seek_table->points[upper_seek_point].sample_number - seek_table->points[lower_seek_point].sample_number;
2735 const FLAC__uint64 range_bytes = (upper_bound>lower_bound? upper_bound - lower_bound - 1 : 0);
2736 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2737 #if defined _MSC_VER || defined __MINGW32__
2738 /* with MSVC you have to spoon feed it the casting */
2739 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;
2741 pos = (FLAC__int64)lower_bound + (FLAC__int64)(((FLAC__double)target_offset / (FLAC__double)range_samples) * (FLAC__double)range_bytes) - approx_bytes_per_frame;
2744 /* a little less accurate: */
2745 if (range_bytes <= 0xffffffff)
2746 pos = (FLAC__int64)lower_bound + (FLAC__int64)((target_offset * range_bytes) / range_samples) - approx_bytes_per_frame;
2747 else /* @@@ WATCHOUT, ~2TB limit */
2748 pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_offset>>8) * (range_bytes>>8)) / (range_samples>>16)) - approx_bytes_per_frame;
2754 * If there's no seek table, we need to use the metadata (if we
2755 * have it) and the filelength to estimate the position of the
2756 * frame with the correct sample.
2758 if(pos < 0 && total_samples > 0) {
2760 * For max accuracy we should be using
2761 * (stream_length-first_frame_offset-1) in the divisor, but the
2762 * difference is trivial and (stream_length-first_frame_offset)
2763 * has no chance of underflow.
2765 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2766 #if defined _MSC_VER || defined __MINGW32__
2767 /* with VC++ you have to spoon feed it the casting */
2768 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;
2770 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;
2773 /* a little less accurate: */
2774 if (stream_length < 0xffffffff)
2775 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)((target_sample * (stream_length-first_frame_offset)) / total_samples) - approx_bytes_per_frame;
2776 else /* @@@ WATCHOUT, ~2TB limit */
2777 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)(((target_sample>>8) * ((stream_length-first_frame_offset)>>8)) / (total_samples>>16)) - approx_bytes_per_frame;
2782 * If there's no seek table and total_samples is unknown, we
2783 * don't even bother trying to figure out a target, we just use
2784 * our current position.
2788 if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK) {
2789 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2792 pos = (FLAC__int64)upos;
2798 /* clip the position to the bounds, lower bound takes precedence */
2799 if(pos >= (FLAC__int64)upper_bound) {
2800 pos = (FLAC__int64)upper_bound-1;
2803 if(pos < (FLAC__int64)lower_bound) {
2804 pos = (FLAC__int64)lower_bound;
2808 decoder->private_->target_sample = target_sample;
2811 if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
2812 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2815 if(!FLAC__stream_decoder_flush(decoder)) {
2816 /* above call sets the state for us */
2820 /* Now we need to get a frame. First we need to reset our
2821 * unparseable_frame_count; if we get too many unparseable
2822 * frames in a row, the read callback will return
2823 * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
2824 * FLAC__stream_decoder_process_single() to return false.
2826 decoder->private_->unparseable_frame_count = 0;
2827 if(!FLAC__stream_decoder_process_single(decoder)) {
2828 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2831 /* our write callback will change the state when it gets to the target frame */
2832 /* 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 */
2834 /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
2835 if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
2838 if(!decoder->private_->is_seeking) {
2841 else { /* we need to narrow the search */
2842 const FLAC__uint64 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
2843 FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2844 if(this_frame_sample == last_frame_sample && pos < last_pos) {
2845 /* our last move backwards wasn't big enough, double it */
2846 pos -= (last_pos - pos);
2850 if(target_sample < this_frame_sample) {
2852 approx_bytes_per_frame = decoder->private_->last_frame.header.blocksize * channels * bps/8 + 64;
2853 pos -= approx_bytes_per_frame;
2856 else { /* target_sample >= this_frame_sample + this frame's blocksize */
2858 if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK) {
2859 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2863 pos = (FLAC__int64)upos;
2864 pos -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
2867 * if we haven't hit the target frame yet and our position hasn't changed,
2868 * it means we're at the end of the stream and the seek target does not exist.
2870 if(last_pos == pos) {
2871 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2876 if(pos < (FLAC__int64)lower_bound)
2877 pos = (FLAC__int64)lower_bound;
2878 last_frame_sample = this_frame_sample;
2885 FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
2890 *bytes = (unsigned)fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
2891 if(ferror(decoder->private_->file))
2892 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2893 else if(*bytes == 0)
2894 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2896 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2899 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
2902 FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2906 if(decoder->private_->file == stdin)
2907 return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
2908 else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
2909 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
2911 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2914 FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2919 if(decoder->private_->file == stdin) /*@@@@@@ may work for stdin */
2920 return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
2921 else if((pos = ftello(decoder->private_->file)) < 0)
2922 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
2924 *absolute_byte_offset = (FLAC__uint64)pos;
2925 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2929 FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2931 struct stat filestats;
2934 if(decoder->private_->file == stdin)
2935 return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
2936 else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
2937 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
2939 *stream_length = (FLAC__uint64)filestats.st_size;
2940 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2944 FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
2948 if(decoder->private_->file == stdin) /*@@@@@@ feof() may work for stdin */
2950 return feof(decoder->private_->file)? true : false;