fix bug in code that skips id3v2 tags at the front of a file; false positives could...
[platform/upstream/flac.git] / src / libFLAC / stream_decoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006  Josh Coalson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * - Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
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.
14  *
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.
18  *
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.
30  */
31
32 #if HAVE_CONFIG_H
33 #  include <config.h>
34 #endif
35
36 #if defined _MSC_VER || defined __MINGW32__
37 #include <io.h> /* for _setmode() */
38 #include <fcntl.h> /* for _O_BINARY */
39 #endif
40 #if defined __CYGWIN__ || defined __EMX__
41 #include <io.h> /* for setmode(), O_BINARY */
42 #include <fcntl.h> /* for _O_BINARY */
43 #endif
44 #include <stdio.h>
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] */
51 #define fseeko fseek
52 #define ftello ftell
53 #endif
54 #endif
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"
66
67 #ifdef max
68 #undef max
69 #endif
70 #define max(a,b) ((a)>(b)?(a):(b))
71
72 /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
73 #ifdef _MSC_VER
74 #define FLAC__U64L(x) x
75 #else
76 #define FLAC__U64L(x) x##LLU
77 #endif
78
79 /***********************************************************************
80  *
81  * Private static data
82  *
83  ***********************************************************************/
84
85 static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
86
87 /***********************************************************************
88  *
89  * Private class method prototypes
90  *
91  ***********************************************************************/
92
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);
124
125 /***********************************************************************
126  *
127  * Private class data
128  *
129  ***********************************************************************/
130
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[]);
148         void *client_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 */
164         FLAC__Frame frame;
165         FLAC__bool cached; /* true if there is a byte in lookahead */
166         FLAC__CPUInfo cpuinfo;
167         FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
168         FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
169         /* unaligned (original) pointers to allocated data */
170         FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
171         FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */
172         FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
173         FLAC__bool is_seeking;
174         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;
182
183 /***********************************************************************
184  *
185  * Public static class data
186  *
187  ***********************************************************************/
188
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"
199 };
200
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"
207 };
208
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"
213 };
214
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"
219 };
220
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"
225 };
226
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"
231 };
232
233 FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
234         "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
235         "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
236 };
237
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"
243 };
244
245 /***********************************************************************
246  *
247  * Class constructor/destructor
248  *
249  ***********************************************************************/
250 FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new()
251 {
252         FLAC__StreamDecoder *decoder;
253         unsigned i;
254
255         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
256
257         decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
258         if(decoder == 0) {
259                 return 0;
260         }
261
262         decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
263         if(decoder->protected_ == 0) {
264                 free(decoder);
265                 return 0;
266         }
267
268         decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
269         if(decoder->private_ == 0) {
270                 free(decoder->protected_);
271                 free(decoder);
272                 return 0;
273         }
274
275         decoder->private_->input = FLAC__bitbuffer_new();
276         if(decoder->private_->input == 0) {
277                 free(decoder->private_);
278                 free(decoder->protected_);
279                 free(decoder);
280                 return 0;
281         }
282
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_);
288                 free(decoder);
289                 return 0;
290         }
291
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;
295         }
296
297         decoder->private_->output_capacity = 0;
298         decoder->private_->output_channels = 0;
299         decoder->private_->has_seek_table = false;
300
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]);
303
304         decoder->private_->file = 0;
305
306         set_defaults_(decoder);
307
308         decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
309
310         return decoder;
311 }
312
313 FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
314 {
315         unsigned i;
316
317         FLAC__ASSERT(0 != decoder);
318         FLAC__ASSERT(0 != decoder->protected_);
319         FLAC__ASSERT(0 != decoder->private_);
320         FLAC__ASSERT(0 != decoder->private_->input);
321
322         FLAC__stream_decoder_finish(decoder);
323
324         if(0 != decoder->private_->metadata_filter_ids)
325                 free(decoder->private_->metadata_filter_ids);
326
327         FLAC__bitbuffer_delete(decoder->private_->input);
328
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]);
331
332         free(decoder->private_);
333         free(decoder->protected_);
334         free(decoder);
335 }
336
337 /***********************************************************************
338  *
339  * Public class methods
340  *
341  ***********************************************************************/
342
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,
353         void *client_data
354 )
355 {
356         FLAC__ASSERT(0 != decoder);
357
358         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
359                 return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
360
361         if(
362                 0 == read_callback ||
363                 0 == write_callback ||
364                 0 == error_callback ||
365                 (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
366         )
367                 return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
368
369         /*
370          * get the CPU info and set the function pointers
371          */
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 */
379 #ifndef FLAC__NO_ASM
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;
388                 }
389                 else {
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;
393                 }
394 #endif
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;
400                 }
401 #endif
402         }
403 #endif
404
405         /* from here on, errors are fatal */
406
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;
410         }
411
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;
426
427         decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
428         decoder->private_->is_seeking = false;
429
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;
434         }
435
436         return FLAC__STREAM_DECODER_INIT_STATUS_OK;
437 }
438
439 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
440         FLAC__StreamDecoder *decoder,
441         FILE *file,
442         FLAC__StreamDecoderWriteCallback write_callback,
443         FLAC__StreamDecoderMetadataCallback metadata_callback,
444         FLAC__StreamDecoderErrorCallback error_callback,
445         void *client_data
446 )
447 {
448         FLAC__ASSERT(0 != decoder);
449         FLAC__ASSERT(0 != file);
450
451         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
452                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
453
454         if(0 == write_callback || 0 == error_callback)
455                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
456
457         /*
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
460          * this routine.
461          */
462         if(file == stdin)
463                 file = get_binary_stdin_(); /* just to be safe */
464
465         decoder->private_->file = file;
466
467         return FLAC__stream_decoder_init_stream(
468                 decoder,
469                 file_read_callback_,
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*/
474                 write_callback,
475                 metadata_callback,
476                 error_callback,
477                 client_data
478         );
479 }
480
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,
487         void *client_data
488 )
489 {
490         FILE *file;
491
492         FLAC__ASSERT(0 != decoder);
493
494         /*
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.
498          */
499         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
500                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
501
502         if(0 == write_callback || 0 == error_callback)
503                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
504
505         file = filename? fopen(filename, "rb") : stdin;
506
507         if(0 == file)
508                 return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
509
510         return FLAC__stream_decoder_init_FILE(decoder, file, write_callback, metadata_callback, error_callback, client_data);
511 }
512
513 FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
514 {
515         FLAC__bool md5_failed = false;
516         unsigned i;
517
518         FLAC__ASSERT(0 != decoder);
519         FLAC__ASSERT(0 != decoder->private_);
520         FLAC__ASSERT(0 != decoder->protected_);
521
522         if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
523                 return true;
524
525         /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
526          * always call FLAC__MD5Final()
527          */
528         FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
529
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;
534         }
535         FLAC__bitbuffer_free(decoder->private_->input);
536         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
537                 /* WATCHOUT:
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.
542                  */
543                 if(0 != decoder->private_->output[i]) {
544                         free(decoder->private_->output[i]-4);
545                         decoder->private_->output[i] = 0;
546                 }
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;
550                 }
551         }
552         decoder->private_->output_capacity = 0;
553         decoder->private_->output_channels = 0;
554
555         if(0 != decoder->private_->file) {
556                 if(decoder->private_->file != stdin)
557                         fclose(decoder->private_->file);
558                 decoder->private_->file = 0;
559         }
560
561         if(decoder->private_->do_md5_checking) {
562                 if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
563                         md5_failed = true;
564         }
565         decoder->private_->is_seeking = false;
566
567         set_defaults_(decoder);
568
569         decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
570
571         return !md5_failed;
572 }
573
574 FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
575 {
576         FLAC__ASSERT(0 != decoder);
577         FLAC__ASSERT(0 != decoder->protected_);
578         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
579                 return false;
580         decoder->protected_->md5_checking = value;
581         return true;
582 }
583
584 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
585 {
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)
592                 return false;
593         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
594                 return false;
595         decoder->private_->metadata_filter[type] = true;
596         if(type == FLAC__METADATA_TYPE_APPLICATION)
597                 decoder->private_->metadata_filter_ids_count = 0;
598         return true;
599 }
600
601 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
602 {
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)
608                 return false;
609
610         if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
611                 return true;
612
613         FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
614
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;
618                         return false;
619                 }
620                 decoder->private_->metadata_filter_ids_capacity *= 2;
621         }
622
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++;
625
626         return true;
627 }
628
629 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
630 {
631         unsigned i;
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)
636                 return false;
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;
640         return true;
641 }
642
643 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
644 {
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)
651                 return false;
652         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
653                 return false;
654         decoder->private_->metadata_filter[type] = false;
655         if(type == FLAC__METADATA_TYPE_APPLICATION)
656                 decoder->private_->metadata_filter_ids_count = 0;
657         return true;
658 }
659
660 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
661 {
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)
667                 return false;
668
669         if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
670                 return true;
671
672         FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
673
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;
677                         return false;
678                 }
679                 decoder->private_->metadata_filter_ids_capacity *= 2;
680         }
681
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++;
684
685         return true;
686 }
687
688 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
689 {
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)
694                 return false;
695         memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
696         decoder->private_->metadata_filter_ids_count = 0;
697         return true;
698 }
699
700 FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
701 {
702         FLAC__ASSERT(0 != decoder);
703         FLAC__ASSERT(0 != decoder->protected_);
704         return decoder->protected_->state;
705 }
706
707 FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
708 {
709         return FLAC__StreamDecoderStateString[decoder->protected_->state];
710 }
711
712 FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
713 {
714         FLAC__ASSERT(0 != decoder);
715         FLAC__ASSERT(0 != decoder->protected_);
716         return decoder->protected_->md5_checking;
717 }
718
719 FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
720 {
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;
724 }
725
726 FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
727 {
728         FLAC__ASSERT(0 != decoder);
729         FLAC__ASSERT(0 != decoder->protected_);
730         return decoder->protected_->channels;
731 }
732
733 FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
734 {
735         FLAC__ASSERT(0 != decoder);
736         FLAC__ASSERT(0 != decoder->protected_);
737         return decoder->protected_->channel_assignment;
738 }
739
740 FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
741 {
742         FLAC__ASSERT(0 != decoder);
743         FLAC__ASSERT(0 != decoder->protected_);
744         return decoder->protected_->bits_per_sample;
745 }
746
747 FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
748 {
749         FLAC__ASSERT(0 != decoder);
750         FLAC__ASSERT(0 != decoder->protected_);
751         return decoder->protected_->sample_rate;
752 }
753
754 FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
755 {
756         FLAC__ASSERT(0 != decoder);
757         FLAC__ASSERT(0 != decoder->protected_);
758         return decoder->protected_->blocksize;
759 }
760
761 FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
762 {
763         FLAC__ASSERT(0 != decoder);
764         FLAC__ASSERT(0 != decoder->private_);
765         FLAC__ASSERT(0 != position);
766
767         if(0 == decoder->private_->tell_callback)
768                 return false;
769         if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
770                 return false;
771         FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
772         *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
773         return true;
774 }
775
776 FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
777 {
778         FLAC__ASSERT(0 != decoder);
779         FLAC__ASSERT(0 != decoder->private_);
780         FLAC__ASSERT(0 != decoder->protected_);
781
782         decoder->private_->samples_decoded = 0;
783         decoder->private_->do_md5_checking = false;
784
785         if(!FLAC__bitbuffer_clear(decoder->private_->input)) {
786                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
787                 return false;
788         }
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;
792
793         return true;
794 }
795
796 FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
797 {
798         FLAC__ASSERT(0 != decoder);
799         FLAC__ASSERT(0 != decoder->private_);
800         FLAC__ASSERT(0 != decoder->protected_);
801
802         if(!FLAC__stream_decoder_flush(decoder)) {
803                 /* above call sets the state for us */
804                 return false;
805         }
806
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
810          * not seekable.
811          */
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 */
817         }
818         else
819                 decoder->private_->internal_reset_hack = false;
820
821         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
822
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;
828         }
829         decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
830
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.
836          */
837         FLAC__MD5Init(&decoder->private_->md5context);
838
839         decoder->private_->first_frame_offset = 0;
840         decoder->private_->unparseable_frame_count = 0;
841
842         return true;
843 }
844
845 FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
846 {
847         FLAC__bool got_a_frame;
848         FLAC__ASSERT(0 != decoder);
849         FLAC__ASSERT(0 != decoder->protected_);
850
851         while(1) {
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 */
856                                 break;
857                         case FLAC__STREAM_DECODER_READ_METADATA:
858                                 if(!read_metadata_(decoder))
859                                         return false; /* above function sets the status for us */
860                                 else
861                                         return true;
862                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
863                                 if(!frame_sync_(decoder))
864                                         return true; /* above function sets the status for us */
865                                 break;
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 */
869                                 if(got_a_frame)
870                                         return true; /* above function sets the status for us */
871                                 break;
872                         case FLAC__STREAM_DECODER_END_OF_STREAM:
873                         case FLAC__STREAM_DECODER_ABORTED:
874                                 return true;
875                         default:
876                                 FLAC__ASSERT(0);
877                                 return false;
878                 }
879         }
880 }
881
882 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
883 {
884         FLAC__ASSERT(0 != decoder);
885         FLAC__ASSERT(0 != decoder->protected_);
886
887         while(1) {
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 */
892                                 break;
893                         case FLAC__STREAM_DECODER_READ_METADATA:
894                                 if(!read_metadata_(decoder))
895                                         return false; /* above function sets the status for us */
896                                 break;
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:
901                                 return true;
902                         default:
903                                 FLAC__ASSERT(0);
904                                 return false;
905                 }
906         }
907 }
908
909 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
910 {
911         FLAC__bool dummy;
912         FLAC__ASSERT(0 != decoder);
913         FLAC__ASSERT(0 != decoder->protected_);
914
915         while(1) {
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 */
920                                 break;
921                         case FLAC__STREAM_DECODER_READ_METADATA:
922                                 if(!read_metadata_(decoder))
923                                         return false; /* above function sets the status for us */
924                                 break;
925                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
926                                 if(!frame_sync_(decoder))
927                                         return true; /* above function sets the status for us */
928                                 break;
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 */
932                                 break;
933                         case FLAC__STREAM_DECODER_END_OF_STREAM:
934                         case FLAC__STREAM_DECODER_ABORTED:
935                                 return true;
936                         default:
937                                 FLAC__ASSERT(0);
938                                 return false;
939                 }
940         }
941 }
942
943 FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
944 {
945         FLAC__bool got_a_frame;
946         FLAC__ASSERT(0 != decoder);
947         FLAC__ASSERT(0 != decoder->protected_);
948
949         while(1) {
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 */
957                                 break;
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 */
961                                 if(got_a_frame)
962                                         return true; /* above function sets the status for us */
963                                 break;
964                         case FLAC__STREAM_DECODER_END_OF_STREAM:
965                         case FLAC__STREAM_DECODER_ABORTED:
966                                 return true;
967                         default:
968                                 FLAC__ASSERT(0);
969                                 return false;
970                 }
971         }
972 }
973
974 FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
975 {
976         FLAC__uint64 length;
977
978         FLAC__ASSERT(0 != decoder);
979
980         if(
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
986         )
987                 return false;
988
989         if(0 == decoder->private_->seek_callback)
990                 return false;
991
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);
996
997         if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
998                 return false;
999
1000         decoder->private_->is_seeking = true;
1001
1002         /* turn off md5 checking if a seek is attempted */
1003         decoder->private_->do_md5_checking = false;
1004
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;
1008                 return false;
1009         }
1010         /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
1011         if(
1012                 decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
1013                 decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
1014         ) {
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;
1018                         return false;
1019                 }
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;
1023                         return false;
1024                 }
1025         }
1026
1027         {
1028                 FLAC__bool ok = seek_to_absolute_sample_(decoder, length, sample);
1029                 decoder->private_->is_seeking = false;
1030                 return ok;
1031         }
1032 }
1033
1034 /***********************************************************************
1035  *
1036  * Protected class methods
1037  *
1038  ***********************************************************************/
1039
1040 unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
1041 {
1042         FLAC__ASSERT(0 != decoder);
1043         return FLAC__bitbuffer_get_input_bytes_unconsumed(decoder->private_->input);
1044 }
1045
1046 /***********************************************************************
1047  *
1048  * Private class methods
1049  *
1050  ***********************************************************************/
1051
1052 void set_defaults_(FLAC__StreamDecoder *decoder)
1053 {
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;
1063
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;
1067
1068         decoder->protected_->md5_checking = false;
1069 }
1070
1071 /*
1072  * This will forcibly set stdin to binary mode (for OSes that require it)
1073  */
1074 FILE *get_binary_stdin_()
1075 {
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.
1079          */
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);
1085 #endif
1086
1087         return stdin;
1088 }
1089
1090 FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
1091 {
1092         unsigned i;
1093         FLAC__int32 *tmp;
1094
1095         if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
1096                 return true;
1097
1098         /* simply using realloc() is not practical because the number of channels may change mid-stream */
1099
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;
1104                 }
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;
1108                 }
1109         }
1110
1111         for(i = 0; i < channels; i++) {
1112                 /* WATCHOUT:
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.
1117                  */
1118                 tmp = (FLAC__int32*)malloc(sizeof(FLAC__int32)*(size+4));
1119                 if(tmp == 0) {
1120                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1121                         return false;
1122                 }
1123                 memset(tmp, 0, sizeof(FLAC__int32)*4);
1124                 decoder->private_->output[i] = tmp + 4;
1125
1126                 /* WATCHOUT:
1127                  * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
1128                  */
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;
1131                         return false;
1132                 }
1133         }
1134
1135         decoder->private_->output_capacity = size;
1136         decoder->private_->output_channels = channels;
1137
1138         return true;
1139 }
1140
1141 FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
1142 {
1143         unsigned i;
1144
1145         FLAC__ASSERT(0 != decoder);
1146         FLAC__ASSERT(0 != decoder->private_);
1147
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)))
1150                         return true;
1151
1152         return false;
1153 }
1154
1155 FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
1156 {
1157         FLAC__uint32 x;
1158         unsigned i, id;
1159         FLAC__bool first = true;
1160
1161         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1162
1163         for(i = id = 0; i < 4; ) {
1164                 if(decoder->private_->cached) {
1165                         x = (FLAC__uint32)decoder->private_->lookahead;
1166                         decoder->private_->cached = false;
1167                 }
1168                 else {
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 */
1171                 }
1172                 if(x == FLAC__STREAM_SYNC_STRING[i]) {
1173                         first = true;
1174                         i++;
1175                         id = 0;
1176                         continue;
1177                 }
1178                 if(x == ID3V2_TAG_[id]) {
1179                         id++;
1180                         i = 0;
1181                         if(id == 3) {
1182                                 if(!skip_id3v2_tag_(decoder))
1183                                         return false; /* skip_id3v2_tag_ sets the state for us */
1184                         }
1185                         continue;
1186                 }
1187                 id = 0;
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 */
1192
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;
1198                         }
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;
1202                                 return true;
1203                         }
1204                 }
1205                 i = 0;
1206                 if(first) {
1207                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1208                         first = false;
1209                 }
1210         }
1211
1212         decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
1213         return true;
1214 }
1215
1216 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
1217 {
1218         FLAC__bool is_last;
1219         FLAC__uint32 i, x, type, length;
1220
1221         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1222
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;
1226
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 */
1229
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 */
1232
1233         if(type == FLAC__METADATA_TYPE_STREAMINFO) {
1234                 if(!read_metadata_streaminfo_(decoder, is_last, length))
1235                         return false;
1236
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);
1242         }
1243         else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
1244                 if(!read_metadata_seektable_(decoder, is_last, length))
1245                         return false;
1246
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);
1250         }
1251         else {
1252                 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
1253                 unsigned real_length = length;
1254                 FLAC__StreamMetadata block;
1255
1256                 block.is_last = is_last;
1257                 block.type = (FLAC__MetadataType)type;
1258                 block.length = length;
1259
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 */
1263
1264                         real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
1265
1266                         if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
1267                                 skip_it = !skip_it;
1268                 }
1269
1270                 if(skip_it) {
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 */
1273                 }
1274                 else {
1275                         switch(type) {
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 */
1280                                         break;
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;
1286                                                         return false;
1287                                                 }
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 */
1290                                         }
1291                                         else
1292                                                 block.data.application.data = 0;
1293                                         break;
1294                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1295                                         if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
1296                                                 return false;
1297                                         break;
1298                                 case FLAC__METADATA_TYPE_CUESHEET:
1299                                         if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
1300                                                 return false;
1301                                         break;
1302                                 case FLAC__METADATA_TYPE_PICTURE:
1303                                         if(!read_metadata_picture_(decoder, &block.data.picture))
1304                                                 return false;
1305                                         break;
1306                                 case FLAC__METADATA_TYPE_STREAMINFO:
1307                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1308                                         FLAC__ASSERT(0);
1309                                         break;
1310                                 default:
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;
1314                                                         return false;
1315                                                 }
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 */
1318                                         }
1319                                         else
1320                                                 block.data.unknown.data = 0;
1321                                         break;
1322                         }
1323                         if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
1324                                 decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1325
1326                         /* now we have to free any malloc'ed data in the block */
1327                         switch(type) {
1328                                 case FLAC__METADATA_TYPE_PADDING:
1329                                         break;
1330                                 case FLAC__METADATA_TYPE_APPLICATION:
1331                                         if(0 != block.data.application.data)
1332                                                 free(block.data.application.data);
1333                                         break;
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);
1343                                         break;
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);
1351                                         break;
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);
1359                                         break;
1360                                 case FLAC__METADATA_TYPE_STREAMINFO:
1361                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1362                                         FLAC__ASSERT(0);
1363                                 default:
1364                                         if(0 != block.data.unknown.data)
1365                                                 free(block.data.unknown.data);
1366                                         break;
1367                         }
1368                 }
1369         }
1370
1371         if(is_last) {
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;
1376         }
1377
1378         return true;
1379 }
1380
1381 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1382 {
1383         FLAC__uint32 x;
1384         unsigned bits, used_bits = 0;
1385
1386         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1387
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;
1391
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;
1396         used_bits += bits;
1397
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;
1402         used_bits += bits;
1403
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;
1408         used_bits += bits;
1409
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;
1414         used_bits += bits;
1415
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;
1420         used_bits += bits;
1421
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;
1426         used_bits += bits;
1427
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;
1432         used_bits += bits;
1433
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 */
1437         used_bits += bits;
1438
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 */
1441         used_bits += 16*8;
1442
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 */
1448
1449         return true;
1450 }
1451
1452 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1453 {
1454         FLAC__uint32 i, x;
1455         FLAC__uint64 xx;
1456
1457         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1458
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;
1462
1463         decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1464
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;
1468                 return false;
1469         }
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;
1474
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;
1478
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;
1482         }
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 */
1485         if(length > 0) {
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 */
1489         }
1490
1491         return true;
1492 }
1493
1494 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1495 {
1496         FLAC__uint32 i;
1497
1498         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1499
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;
1507                         return false;
1508                 }
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';
1512         }
1513         else
1514                 obj->vendor_string.entry = 0;
1515
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 */
1520
1521         /* read comments */
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;
1525                         return false;
1526                 }
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;
1534                                         return false;
1535                                 }
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';
1539                         }
1540                         else
1541                                 obj->comments[i].entry = 0;
1542                 }
1543         }
1544         else {
1545                 obj->comments = 0;
1546         }
1547
1548         return true;
1549 }
1550
1551 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1552 {
1553         FLAC__uint32 i, j, x;
1554
1555         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1556
1557         memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1558
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 */
1562
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 */
1565
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;
1569
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 */
1572
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;
1576
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;
1580                         return false;
1581                 }
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 */
1586
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;
1590
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 */
1594
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 */
1597                         track->type = x;
1598
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;
1602
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 */
1605
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;
1609
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;
1613                                         return false;
1614                                 }
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 */
1619
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;
1623
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 */
1626                                 }
1627                         }
1628                 }
1629         }
1630
1631         return true;
1632 }
1633
1634 FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
1635 {
1636         FLAC__uint32 len;
1637
1638         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1639
1640         /* read type */
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 */
1643
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;
1649                 return false;
1650         }
1651         if(len > 0) {
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 */
1654         }
1655         obj->mime_type[len] = '\0';
1656
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;
1662                 return false;
1663         }
1664         if(len > 0) {
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 */
1667         }
1668         obj->description[len] = '\0';
1669
1670         /* read width */
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 */
1673
1674         /* read height */
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 */
1677
1678         /* read depth */
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 */
1681
1682         /* read colors */
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 */
1685
1686         /* read data */
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;
1691                 return false;
1692         }
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 */
1696         }
1697
1698         return true;
1699 }
1700
1701 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1702 {
1703         FLAC__uint32 x;
1704         unsigned i, skip;
1705
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 */
1710         skip = 0;
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 */
1714                 skip <<= 7;
1715                 skip |= (x & 0x7f);
1716         }
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 */
1720         return true;
1721 }
1722
1723 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1724 {
1725         FLAC__uint32 x;
1726         FLAC__bool first = true;
1727
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;
1733                         return true;
1734                 }
1735         }
1736
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 */
1741         }
1742
1743         while(1) {
1744                 if(decoder->private_->cached) {
1745                         x = (FLAC__uint32)decoder->private_->lookahead;
1746                         decoder->private_->cached = false;
1747                 }
1748                 else {
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 */
1751                 }
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 */
1756
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;
1762                         }
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;
1766                                 return true;
1767                         }
1768                 }
1769                 if(first) {
1770                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1771                         first = false;
1772                 }
1773         }
1774
1775         return true;
1776 }
1777
1778 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
1779 {
1780         unsigned channel;
1781         unsigned i;
1782         FLAC__int32 mid, side, left, right;
1783         FLAC__uint16 frame_crc; /* the one we calculate from the input stream */
1784         FLAC__uint32 x;
1785
1786         *got_a_frame = false;
1787
1788         /* init the CRC */
1789         frame_crc = 0;
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);
1793
1794         if(!read_frame_header_(decoder))
1795                 return false;
1796         if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
1797                 return true;
1798         if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
1799                 return false;
1800         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1801                 /*
1802                  * first figure the correct bits-per-sample of the subframe
1803                  */
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 */
1808                                 break;
1809                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1810                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1811                                 if(channel == 1)
1812                                         bps++;
1813                                 break;
1814                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1815                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1816                                 if(channel == 0)
1817                                         bps++;
1818                                 break;
1819                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1820                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1821                                 if(channel == 1)
1822                                         bps++;
1823                                 break;
1824                         default:
1825                                 FLAC__ASSERT(0);
1826                 }
1827                 /*
1828                  * now read it
1829                  */
1830                 if(!read_subframe_(decoder, channel, bps, do_full_decode))
1831                         return false;
1832                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
1833                         return true;
1834         }
1835         if(!read_zero_padding_(decoder))
1836                 return false;
1837
1838         /*
1839          * Read the frame CRC-16 from the footer and check
1840          */
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:
1849                                         /* do nothing */
1850                                         break;
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];
1855                                         break;
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];
1860                                         break;
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];
1866                                                 mid <<= 1;
1867                                                 if(side & 1) /* i.e. if 'side' is odd... */
1868                                                         mid++;
1869                                                 left = mid + side;
1870                                                 right = mid - side;
1871                                                 decoder->private_->output[0][i] = left >> 1;
1872                                                 decoder->private_->output[1][i] = right >> 1;
1873                                         }
1874                                         break;
1875                                 default:
1876                                         FLAC__ASSERT(0);
1877                                         break;
1878                         }
1879                 }
1880         }
1881         else {
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);
1887                         }
1888                 }
1889         }
1890
1891         *got_a_frame = true;
1892
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;
1899
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;
1902
1903         /* write it */
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)
1906                         return false;
1907         }
1908
1909         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1910         return true;
1911 }
1912
1913 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
1914 {
1915         FLAC__uint32 x;
1916         FLAC__uint64 xx;
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);
1923
1924         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1925
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];
1929         raw_header_len = 2;
1930
1931         /*
1932          * check to make sure that the reserved bits are 0
1933          */
1934         if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
1935                 is_unparseable = true;
1936         }
1937
1938         /*
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.
1942          */
1943
1944         /*
1945          * read in the raw header as bytes so we can CRC it, and parse it on the way
1946          */
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;
1956                         return true;
1957                 }
1958                 raw_header[raw_header_len++] = (FLAC__byte)x;
1959         }
1960
1961         switch(x = raw_header[2] >> 4) {
1962                 case 0:
1963                         if(is_known_fixed_blocksize_stream)
1964                                 decoder->private_->frame.header.blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
1965                         else
1966                                 is_unparseable = true;
1967                         break;
1968                 case 1:
1969                         decoder->private_->frame.header.blocksize = 192;
1970                         break;
1971                 case 2:
1972                 case 3:
1973                 case 4:
1974                 case 5:
1975                         decoder->private_->frame.header.blocksize = 576 << (x-2);
1976                         break;
1977                 case 6:
1978                 case 7:
1979                         blocksize_hint = x;
1980                         break;
1981                 case 8:
1982                 case 9:
1983                 case 10:
1984                 case 11:
1985                 case 12:
1986                 case 13:
1987                 case 14:
1988                 case 15:
1989                         decoder->private_->frame.header.blocksize = 256 << (x-8);
1990                         break;
1991                 default:
1992                         FLAC__ASSERT(0);
1993                         break;
1994         }
1995
1996         switch(x = raw_header[2] & 0x0f) {
1997                 case 0:
1998                         if(decoder->private_->has_stream_info)
1999                                 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
2000                         else
2001                                 is_unparseable = true;
2002                         break;
2003                 case 1:
2004                 case 2:
2005                 case 3:
2006                         is_unparseable = true;
2007                         break;
2008                 case 4:
2009                         decoder->private_->frame.header.sample_rate = 8000;
2010                         break;
2011                 case 5:
2012                         decoder->private_->frame.header.sample_rate = 16000;
2013                         break;
2014                 case 6:
2015                         decoder->private_->frame.header.sample_rate = 22050;
2016                         break;
2017                 case 7:
2018                         decoder->private_->frame.header.sample_rate = 24000;
2019                         break;
2020                 case 8:
2021                         decoder->private_->frame.header.sample_rate = 32000;
2022                         break;
2023                 case 9:
2024                         decoder->private_->frame.header.sample_rate = 44100;
2025                         break;
2026                 case 10:
2027                         decoder->private_->frame.header.sample_rate = 48000;
2028                         break;
2029                 case 11:
2030                         decoder->private_->frame.header.sample_rate = 96000;
2031                         break;
2032                 case 12:
2033                 case 13:
2034                 case 14:
2035                         sample_rate_hint = x;
2036                         break;
2037                 case 15:
2038                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2039                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2040                         return true;
2041                 default:
2042                         FLAC__ASSERT(0);
2043         }
2044
2045         x = (unsigned)(raw_header[3] >> 4);
2046         if(x & 8) {
2047                 decoder->private_->frame.header.channels = 2;
2048                 switch(x & 7) {
2049                         case 0:
2050                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2051                                 break;
2052                         case 1:
2053                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2054                                 break;
2055                         case 2:
2056                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2057                                 break;
2058                         default:
2059                                 is_unparseable = true;
2060                                 break;
2061                 }
2062         }
2063         else {
2064                 decoder->private_->frame.header.channels = (unsigned)x + 1;
2065                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2066         }
2067
2068         switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2069                 case 0:
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;
2072                         else
2073                                 is_unparseable = true;
2074                         break;
2075                 case 1:
2076                         decoder->private_->frame.header.bits_per_sample = 8;
2077                         break;
2078                 case 2:
2079                         decoder->private_->frame.header.bits_per_sample = 12;
2080                         break;
2081                 case 4:
2082                         decoder->private_->frame.header.bits_per_sample = 16;
2083                         break;
2084                 case 5:
2085                         decoder->private_->frame.header.bits_per_sample = 20;
2086                         break;
2087                 case 6:
2088                         decoder->private_->frame.header.bits_per_sample = 24;
2089                         break;
2090                 case 3:
2091                 case 7:
2092                         is_unparseable = true;
2093                         break;
2094                 default:
2095                         FLAC__ASSERT(0);
2096                         break;
2097         }
2098
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;
2102                 return true;
2103         }
2104
2105         /*
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.
2116          */
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;
2126                                 return true;
2127                         }
2128                         decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2129                         decoder->private_->frame.header.number.sample_number = xx;
2130                 }
2131                 else
2132                         is_unparseable = true;
2133         }
2134         else {
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;
2142                         return true;
2143                 }
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;
2150                 }
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;
2154                         else
2155                                 is_unparseable = true;
2156                 }
2157                 else {
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;
2160                 }
2161         }
2162
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) {
2168                         FLAC__uint32 _x;
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;
2172                         x = (x << 8) | _x;
2173                 }
2174                 decoder->private_->frame.header.blocksize = x+1;
2175         }
2176
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) {
2182                         FLAC__uint32 _x;
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;
2186                         x = (x << 8) | _x;
2187                 }
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;
2192                 else
2193                         decoder->private_->frame.header.sample_rate = x*10;
2194         }
2195
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;
2200
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;
2204                 return true;
2205         }
2206
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;
2210                 return true;
2211         }
2212
2213         return true;
2214 }
2215
2216 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2217 {
2218         FLAC__uint32 x;
2219         FLAC__bool wasted_bits;
2220         unsigned i;
2221
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 */
2224
2225         wasted_bits = (x & 1);
2226         x &= 0xfe;
2227
2228         if(wasted_bits) {
2229                 unsigned u;
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;
2234         }
2235         else
2236                 decoder->private_->frame.subframes[channel].wasted_bits = 0;
2237
2238         /*
2239          * Lots of magic numbers here
2240          */
2241         if(x & 0x80) {
2242                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2243                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2244                 return true;
2245         }
2246         else if(x == 0) {
2247                 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2248                         return false;
2249         }
2250         else if(x == 2) {
2251                 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2252                         return false;
2253         }
2254         else if(x < 16) {
2255                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2256                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2257                 return true;
2258         }
2259         else if(x <= 24) {
2260                 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2261                         return false;
2262                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2263                         return true;
2264         }
2265         else if(x < 64) {
2266                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2267                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2268                 return true;
2269         }
2270         else {
2271                 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2272                         return false;
2273                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2274                         return true;
2275         }
2276
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;
2281         }
2282
2283         return true;
2284 }
2285
2286 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2287 {
2288         FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2289         FLAC__int32 x;
2290         unsigned i;
2291         FLAC__int32 *output = decoder->private_->output[channel];
2292
2293         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2294
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 */
2297
2298         subframe->value = x;
2299
2300         /* decode the subframe */
2301         if(do_full_decode) {
2302                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2303                         output[i] = x;
2304         }
2305
2306         return true;
2307 }
2308
2309 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2310 {
2311         FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2312         FLAC__int32 i32;
2313         FLAC__uint32 u32;
2314         unsigned u;
2315
2316         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2317
2318         subframe->residual = decoder->private_->residual[channel];
2319         subframe->order = order;
2320
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;
2326         }
2327
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];
2338                         break;
2339                 default:
2340                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2341                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2342                         return true;
2343         }
2344
2345         /* read residual */
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]))
2349                                 return false;
2350                         break;
2351                 default:
2352                         FLAC__ASSERT(0);
2353         }
2354
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);
2359         }
2360
2361         return true;
2362 }
2363
2364 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2365 {
2366         FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2367         FLAC__int32 i32;
2368         FLAC__uint32 u32;
2369         unsigned u;
2370
2371         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2372
2373         subframe->residual = decoder->private_->residual[channel];
2374         subframe->order = order;
2375
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;
2381         }
2382
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;
2389                 return true;
2390         }
2391         subframe->qlp_coeff_precision = u32+1;
2392
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;
2397
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;
2403         }
2404
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];
2415                         break;
2416                 default:
2417                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2418                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2419                         return true;
2420         }
2421
2422         /* read residual */
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]))
2426                                 return false;
2427                         break;
2428                 default:
2429                         FLAC__ASSERT(0);
2430         }
2431
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) {
2437                                 if(order <= 8)
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);
2439                                 else
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);
2441                         }
2442                         else
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);
2444                 else
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);
2446         }
2447
2448         return true;
2449 }
2450
2451 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2452 {
2453         FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2454         FLAC__int32 x, *residual = decoder->private_->residual[channel];
2455         unsigned i;
2456
2457         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2458
2459         subframe->data = residual;
2460
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 */
2464                 residual[i] = x;
2465         }
2466
2467         /* decode the subframe */
2468         if(do_full_decode)
2469                 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2470
2471         return true;
2472 }
2473
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)
2475 {
2476         FLAC__uint32 rice_parameter;
2477         int i;
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;
2481
2482         /* sanity checks */
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;
2487                         return true;
2488                 }
2489         }
2490         else {
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;
2494                         return true;
2495                 }
2496         }
2497
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;
2500                 return false;
2501         }
2502
2503         sample = 0;
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 */
2512                         sample += u;
2513                 }
2514                 else {
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;
2522                         }
2523                 }
2524         }
2525
2526         return true;
2527 }
2528
2529 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2530 {
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 */
2535                 if(zero != 0) {
2536                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2537                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2538                 }
2539         }
2540         return true;
2541 }
2542
2543 FLAC__bool read_callback_(FLAC__byte buffer[], unsigned *bytes, void *client_data)
2544 {
2545         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2546
2547         if(decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)) {
2548                 *bytes = 0;
2549                 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2550                 return false;
2551         }
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.
2562                  */
2563                 if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2564                         decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2565                         return false;
2566                 }
2567                 else {
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;
2571                                 return false;
2572                         }
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;
2576                                         return false;
2577                                 }
2578                                 else
2579                                         return true;
2580                         }
2581                         else
2582                                 return true;
2583                 }
2584         }
2585         else {
2586                 /* abort to avoid a deadlock */
2587                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2588                 return false;
2589         }
2590 }
2591
2592 FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2593 {
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;
2598
2599                 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2600
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 */
2607                         if(delta > 0) {
2608                                 unsigned channel;
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);
2616                         }
2617                         else {
2618                                 /* write the relevant samples */
2619                                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2620                         }
2621                 }
2622                 else {
2623                         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2624                 }
2625         }
2626         else {
2627                 /*
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
2630                  */
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;
2636                 }
2637                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2638         }
2639 }
2640
2641 void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2642 {
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++;
2647 }
2648
2649 FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2650 {
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;
2664
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;
2668
2669         /*
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.
2674          */
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;
2678         }
2679         else
2680                 approx_bytes_per_frame = 4608 * channels * bps/8 + 64;
2681
2682         /*
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.
2687          */
2688         lower_bound = first_frame_offset;
2689
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 */
2693         else
2694                 upper_bound = stream_length - ((channels * bps * FLAC__MAX_BLOCK_SIZE) / 8 + 128 + 2);
2695
2696         /*
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.
2700          */
2701         if(seek_table) {
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)
2705                                 break;
2706                 }
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;
2710                 }
2711
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)
2715                                 break;
2716                 }
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;
2720                 }
2721         }
2722
2723         /*
2724          * Now guess at where within those bounds our target
2725          * sample will be.
2726          */
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;
2731                 }
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;
2740 #else
2741                         pos = (FLAC__int64)lower_bound + (FLAC__int64)(((FLAC__double)target_offset / (FLAC__double)range_samples) * (FLAC__double)range_bytes) - approx_bytes_per_frame;
2742 #endif
2743 #else
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;
2749 #endif
2750                 }
2751         }
2752
2753         /*
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.
2757          */
2758         if(pos < 0 && total_samples > 0) {
2759                 /*
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.
2764                  */
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;
2769 #else
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;
2771 #endif
2772 #else
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;
2778 #endif
2779         }
2780
2781         /*
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.
2785          */
2786         if(pos < 0) {
2787                 FLAC__uint64 upos;
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;
2790                         return false;
2791                 }
2792                 pos = (FLAC__int64)upos;
2793                 needs_seek = false;
2794         }
2795         else
2796                 needs_seek = true;
2797
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;
2801                 needs_seek = true;
2802         }
2803         if(pos < (FLAC__int64)lower_bound) {
2804                 pos = (FLAC__int64)lower_bound;
2805                 needs_seek = true;
2806         }
2807
2808         decoder->private_->target_sample = target_sample;
2809         while(1) {
2810                 if(needs_seek) {
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;
2813                                 return false;
2814                         }
2815                         if(!FLAC__stream_decoder_flush(decoder)) {
2816                                 /* above call sets the state for us */
2817                                 return false;
2818                         }
2819                 }
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.
2825                  */
2826                 decoder->private_->unparseable_frame_count = 0;
2827                 if(!FLAC__stream_decoder_process_single(decoder)) {
2828                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2829                         return false;
2830                 }
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 */
2833 #if 0
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)
2836                         break;
2837 #endif
2838                 if(!decoder->private_->is_seeking) {
2839                         break;
2840                 }
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);
2847                                 needs_seek = true;
2848                         }
2849                         else {
2850                                 if(target_sample < this_frame_sample) {
2851                                         last_pos = pos;
2852                                         approx_bytes_per_frame = decoder->private_->last_frame.header.blocksize * channels * bps/8 + 64;
2853                                         pos -= approx_bytes_per_frame;
2854                                         needs_seek = true;
2855                                 }
2856                                 else { /* target_sample >= this_frame_sample + this frame's blocksize */
2857                                         FLAC__uint64 upos;
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;
2860                                                 return false;
2861                                         }
2862                                         last_pos = pos;
2863                                         pos = (FLAC__int64)upos;
2864                                         pos -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
2865                                         needs_seek = false;
2866                                         /*
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.
2869                                          */
2870                                         if(last_pos == pos) {
2871                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2872                                                 return false;
2873                                         }
2874                                 }
2875                         }
2876                         if(pos < (FLAC__int64)lower_bound)
2877                                 pos = (FLAC__int64)lower_bound;
2878                         last_frame_sample = this_frame_sample;
2879                 }
2880         }
2881
2882         return true;
2883 }
2884
2885 FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
2886 {
2887         (void)client_data;
2888
2889         if(*bytes > 0) {
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;
2895                 else
2896                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2897         }
2898         else
2899                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
2900 }
2901
2902 FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2903 {
2904         (void)client_data;
2905
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;
2910         else
2911                 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2912 }
2913
2914 FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2915 {
2916         off_t pos;
2917         (void)client_data;
2918
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;
2923         else {
2924                 *absolute_byte_offset = (FLAC__uint64)pos;
2925                 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2926         }
2927 }
2928
2929 FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2930 {
2931         struct stat filestats;
2932         (void)client_data;
2933
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;
2938         else {
2939                 *stream_length = (FLAC__uint64)filestats.st_size;
2940                 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2941         }
2942 }
2943
2944 FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
2945 {
2946         (void)client_data;
2947
2948         if(decoder->private_->file == stdin) /*@@@@@@ feof() may work for stdin */
2949                 return false;
2950         return feof(decoder->private_->file)? true : false;
2951 }