try to limit the #defines (of fseeko to fseek and ftello to ftell) to just the versio...
[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                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1188                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1189                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1190                                 return false; /* read_callback_ sets the state for us */
1191
1192                         /* 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 */
1193                         /* else we have to check if the second byte is the end of a sync code */
1194                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1195                                 decoder->private_->lookahead = (FLAC__byte)x;
1196                                 decoder->private_->cached = true;
1197                         }
1198                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1199                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1200                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1201                                 return true;
1202                         }
1203                 }
1204                 i = 0;
1205                 if(first) {
1206                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1207                         first = false;
1208                 }
1209         }
1210
1211         decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
1212         return true;
1213 }
1214
1215 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
1216 {
1217         FLAC__bool is_last;
1218         FLAC__uint32 i, x, type, length;
1219
1220         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1221
1222         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN, read_callback_, decoder))
1223                 return false; /* read_callback_ sets the state for us */
1224         is_last = x? true : false;
1225
1226         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN, read_callback_, decoder))
1227                 return false; /* read_callback_ sets the state for us */
1228
1229         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN, read_callback_, decoder))
1230                 return false; /* read_callback_ sets the state for us */
1231
1232         if(type == FLAC__METADATA_TYPE_STREAMINFO) {
1233                 if(!read_metadata_streaminfo_(decoder, is_last, length))
1234                         return false;
1235
1236                 decoder->private_->has_stream_info = true;
1237                 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))
1238                         decoder->private_->do_md5_checking = false;
1239                 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
1240                         decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
1241         }
1242         else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
1243                 if(!read_metadata_seektable_(decoder, is_last, length))
1244                         return false;
1245
1246                 decoder->private_->has_seek_table = true;
1247                 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
1248                         decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
1249         }
1250         else {
1251                 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
1252                 unsigned real_length = length;
1253                 FLAC__StreamMetadata block;
1254
1255                 block.is_last = is_last;
1256                 block.type = (FLAC__MetadataType)type;
1257                 block.length = length;
1258
1259                 if(type == FLAC__METADATA_TYPE_APPLICATION) {
1260                         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))
1261                                 return false; /* read_callback_ sets the state for us */
1262
1263                         real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
1264
1265                         if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
1266                                 skip_it = !skip_it;
1267                 }
1268
1269                 if(skip_it) {
1270                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
1271                                 return false; /* read_callback_ sets the state for us */
1272                 }
1273                 else {
1274                         switch(type) {
1275                                 case FLAC__METADATA_TYPE_PADDING:
1276                                         /* skip the padding bytes */
1277                                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
1278                                                 return false; /* read_callback_ sets the state for us */
1279                                         break;
1280                                 case FLAC__METADATA_TYPE_APPLICATION:
1281                                         /* remember, we read the ID already */
1282                                         if(real_length > 0) {
1283                                                 if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
1284                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1285                                                         return false;
1286                                                 }
1287                                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length, read_callback_, decoder))
1288                                                         return false; /* read_callback_ sets the state for us */
1289                                         }
1290                                         else
1291                                                 block.data.application.data = 0;
1292                                         break;
1293                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1294                                         if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
1295                                                 return false;
1296                                         break;
1297                                 case FLAC__METADATA_TYPE_CUESHEET:
1298                                         if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
1299                                                 return false;
1300                                         break;
1301                                 case FLAC__METADATA_TYPE_PICTURE:
1302                                         if(!read_metadata_picture_(decoder, &block.data.picture))
1303                                                 return false;
1304                                         break;
1305                                 case FLAC__METADATA_TYPE_STREAMINFO:
1306                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1307                                         FLAC__ASSERT(0);
1308                                         break;
1309                                 default:
1310                                         if(real_length > 0) {
1311                                                 if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
1312                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1313                                                         return false;
1314                                                 }
1315                                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length, read_callback_, decoder))
1316                                                         return false; /* read_callback_ sets the state for us */
1317                                         }
1318                                         else
1319                                                 block.data.unknown.data = 0;
1320                                         break;
1321                         }
1322                         if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
1323                                 decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1324
1325                         /* now we have to free any malloc'ed data in the block */
1326                         switch(type) {
1327                                 case FLAC__METADATA_TYPE_PADDING:
1328                                         break;
1329                                 case FLAC__METADATA_TYPE_APPLICATION:
1330                                         if(0 != block.data.application.data)
1331                                                 free(block.data.application.data);
1332                                         break;
1333                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1334                                         if(0 != block.data.vorbis_comment.vendor_string.entry)
1335                                                 free(block.data.vorbis_comment.vendor_string.entry);
1336                                         if(block.data.vorbis_comment.num_comments > 0)
1337                                                 for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
1338                                                         if(0 != block.data.vorbis_comment.comments[i].entry)
1339                                                                 free(block.data.vorbis_comment.comments[i].entry);
1340                                         if(0 != block.data.vorbis_comment.comments)
1341                                                 free(block.data.vorbis_comment.comments);
1342                                         break;
1343                                 case FLAC__METADATA_TYPE_CUESHEET:
1344                                         if(block.data.cue_sheet.num_tracks > 0)
1345                                                 for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
1346                                                         if(0 != block.data.cue_sheet.tracks[i].indices)
1347                                                                 free(block.data.cue_sheet.tracks[i].indices);
1348                                         if(0 != block.data.cue_sheet.tracks)
1349                                                 free(block.data.cue_sheet.tracks);
1350                                         break;
1351                                 case FLAC__METADATA_TYPE_PICTURE:
1352                                         if(0 != block.data.picture.mime_type)
1353                                                 free(block.data.picture.mime_type);
1354                                         if(0 != block.data.picture.description)
1355                                                 free(block.data.picture.description);
1356                                         if(0 != block.data.picture.data)
1357                                                 free(block.data.picture.data);
1358                                         break;
1359                                 case FLAC__METADATA_TYPE_STREAMINFO:
1360                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1361                                         FLAC__ASSERT(0);
1362                                 default:
1363                                         if(0 != block.data.unknown.data)
1364                                                 free(block.data.unknown.data);
1365                                         break;
1366                         }
1367                 }
1368         }
1369
1370         if(is_last) {
1371                 /* if this fails, it's OK, it's just a hint for the seek routine */
1372                 if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
1373                         decoder->private_->first_frame_offset = 0;
1374                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1375         }
1376
1377         return true;
1378 }
1379
1380 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1381 {
1382         FLAC__uint32 x;
1383         unsigned bits, used_bits = 0;
1384
1385         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1386
1387         decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
1388         decoder->private_->stream_info.is_last = is_last;
1389         decoder->private_->stream_info.length = length;
1390
1391         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1392         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, bits, read_callback_, decoder))
1393                 return false; /* read_callback_ sets the state for us */
1394         decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1395         used_bits += bits;
1396
1397         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1398         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN, read_callback_, decoder))
1399                 return false; /* read_callback_ sets the state for us */
1400         decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1401         used_bits += bits;
1402
1403         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1404         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN, read_callback_, decoder))
1405                 return false; /* read_callback_ sets the state for us */
1406         decoder->private_->stream_info.data.stream_info.min_framesize = x;
1407         used_bits += bits;
1408
1409         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1410         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN, read_callback_, decoder))
1411                 return false; /* read_callback_ sets the state for us */
1412         decoder->private_->stream_info.data.stream_info.max_framesize = x;
1413         used_bits += bits;
1414
1415         bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1416         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN, read_callback_, decoder))
1417                 return false; /* read_callback_ sets the state for us */
1418         decoder->private_->stream_info.data.stream_info.sample_rate = x;
1419         used_bits += bits;
1420
1421         bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1422         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN, read_callback_, decoder))
1423                 return false; /* read_callback_ sets the state for us */
1424         decoder->private_->stream_info.data.stream_info.channels = x+1;
1425         used_bits += bits;
1426
1427         bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1428         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN, read_callback_, decoder))
1429                 return false; /* read_callback_ sets the state for us */
1430         decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1431         used_bits += bits;
1432
1433         bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1434         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))
1435                 return false; /* read_callback_ sets the state for us */
1436         used_bits += bits;
1437
1438         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16, read_callback_, decoder))
1439                 return false; /* read_callback_ sets the state for us */
1440         used_bits += 16*8;
1441
1442         /* skip the rest of the block */
1443         FLAC__ASSERT(used_bits % 8 == 0);
1444         length -= (used_bits / 8);
1445         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1446                 return false; /* read_callback_ sets the state for us */
1447
1448         return true;
1449 }
1450
1451 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1452 {
1453         FLAC__uint32 i, x;
1454         FLAC__uint64 xx;
1455
1456         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1457
1458         decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1459         decoder->private_->seek_table.is_last = is_last;
1460         decoder->private_->seek_table.length = length;
1461
1462         decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1463
1464         /* use realloc since we may pass through here several times (e.g. after seeking) */
1465         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)))) {
1466                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1467                 return false;
1468         }
1469         for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1470                 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN, read_callback_, decoder))
1471                         return false; /* read_callback_ sets the state for us */
1472                 decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1473
1474                 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN, read_callback_, decoder))
1475                         return false; /* read_callback_ sets the state for us */
1476                 decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1477
1478                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN, read_callback_, decoder))
1479                         return false; /* read_callback_ sets the state for us */
1480                 decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1481         }
1482         length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1483         /* if there is a partial point left, skip over it */
1484         if(length > 0) {
1485                 /*@@@ do an error_callback() here?  there's an argument for either way */
1486                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1487                         return false; /* read_callback_ sets the state for us */
1488         }
1489
1490         return true;
1491 }
1492
1493 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1494 {
1495         FLAC__uint32 i;
1496
1497         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1498
1499         /* read vendor string */
1500         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1501         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length, read_callback_, decoder))
1502                 return false; /* read_callback_ sets the state for us */
1503         if(obj->vendor_string.length > 0) {
1504                 if(0 == (obj->vendor_string.entry = (FLAC__byte*)malloc(obj->vendor_string.length+1))) {
1505                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1506                         return false;
1507                 }
1508                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length, read_callback_, decoder))
1509                         return false; /* read_callback_ sets the state for us */
1510                 obj->vendor_string.entry[obj->vendor_string.length] = '\0';
1511         }
1512         else
1513                 obj->vendor_string.entry = 0;
1514
1515         /* read num comments */
1516         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1517         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->num_comments, read_callback_, decoder))
1518                 return false; /* read_callback_ sets the state for us */
1519
1520         /* read comments */
1521         if(obj->num_comments > 0) {
1522                 if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)malloc(obj->num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1523                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1524                         return false;
1525                 }
1526                 for(i = 0; i < obj->num_comments; i++) {
1527                         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1528                         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->comments[i].length, read_callback_, decoder))
1529                                 return false; /* read_callback_ sets the state for us */
1530                         if(obj->comments[i].length > 0) {
1531                                 if(0 == (obj->comments[i].entry = (FLAC__byte*)malloc(obj->comments[i].length+1))) {
1532                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1533                                         return false;
1534                                 }
1535                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length, read_callback_, decoder))
1536                                         return false; /* read_callback_ sets the state for us */
1537                                 obj->comments[i].entry[obj->comments[i].length] = '\0';
1538                         }
1539                         else
1540                                 obj->comments[i].entry = 0;
1541                 }
1542         }
1543         else {
1544                 obj->comments = 0;
1545         }
1546
1547         return true;
1548 }
1549
1550 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1551 {
1552         FLAC__uint32 i, j, x;
1553
1554         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1555
1556         memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1557
1558         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1559         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))
1560                 return false; /* read_callback_ sets the state for us */
1561
1562         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN, read_callback_, decoder))
1563                 return false; /* read_callback_ sets the state for us */
1564
1565         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN, read_callback_, decoder))
1566                 return false; /* read_callback_ sets the state for us */
1567         obj->is_cd = x? true : false;
1568
1569         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN, read_callback_, decoder))
1570                 return false; /* read_callback_ sets the state for us */
1571
1572         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN, read_callback_, decoder))
1573                 return false; /* read_callback_ sets the state for us */
1574         obj->num_tracks = x;
1575
1576         if(obj->num_tracks > 0) {
1577                 if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1578                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1579                         return false;
1580                 }
1581                 for(i = 0; i < obj->num_tracks; i++) {
1582                         FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1583                         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN, read_callback_, decoder))
1584                                 return false; /* read_callback_ sets the state for us */
1585
1586                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN, read_callback_, decoder))
1587                                 return false; /* read_callback_ sets the state for us */
1588                         track->number = (FLAC__byte)x;
1589
1590                         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1591                         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))
1592                                 return false; /* read_callback_ sets the state for us */
1593
1594                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN, read_callback_, decoder))
1595                                 return false; /* read_callback_ sets the state for us */
1596                         track->type = x;
1597
1598                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN, read_callback_, decoder))
1599                                 return false; /* read_callback_ sets the state for us */
1600                         track->pre_emphasis = x;
1601
1602                         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN, read_callback_, decoder))
1603                                 return false; /* read_callback_ sets the state for us */
1604
1605                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN, read_callback_, decoder))
1606                                 return false; /* read_callback_ sets the state for us */
1607                         track->num_indices = (FLAC__byte)x;
1608
1609                         if(track->num_indices > 0) {
1610                                 if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1611                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1612                                         return false;
1613                                 }
1614                                 for(j = 0; j < track->num_indices; j++) {
1615                                         FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1616                                         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN, read_callback_, decoder))
1617                                                 return false; /* read_callback_ sets the state for us */
1618
1619                                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN, read_callback_, decoder))
1620                                                 return false; /* read_callback_ sets the state for us */
1621                                         index->number = (FLAC__byte)x;
1622
1623                                         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN, read_callback_, decoder))
1624                                                 return false; /* read_callback_ sets the state for us */
1625                                 }
1626                         }
1627                 }
1628         }
1629
1630         return true;
1631 }
1632
1633 FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
1634 {
1635         FLAC__uint32 len;
1636
1637         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1638
1639         /* read type */
1640         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN, read_callback_, decoder))
1641                 return false; /* read_callback_ sets the state for us */
1642
1643         /* read MIME type */
1644         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN, read_callback_, decoder))
1645                 return false; /* read_callback_ sets the state for us */
1646         if(0 == (obj->mime_type = (char*)malloc(len+1))) {
1647                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1648                 return false;
1649         }
1650         if(len > 0) {
1651                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, len, read_callback_, decoder))
1652                         return false; /* read_callback_ sets the state for us */
1653         }
1654         obj->mime_type[len] = '\0';
1655
1656         /* read description */
1657         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN, read_callback_, decoder))
1658                 return false; /* read_callback_ sets the state for us */
1659         if(0 == (obj->description = (FLAC__byte*)malloc(len+1))) {
1660                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1661                 return false;
1662         }
1663         if(len > 0) {
1664                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, len, read_callback_, decoder))
1665                         return false; /* read_callback_ sets the state for us */
1666         }
1667         obj->description[len] = '\0';
1668
1669         /* read width */
1670         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN, read_callback_, decoder))
1671                 return false; /* read_callback_ sets the state for us */
1672
1673         /* read height */
1674         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN, read_callback_, decoder))
1675                 return false; /* read_callback_ sets the state for us */
1676
1677         /* read depth */
1678         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN, read_callback_, decoder))
1679                 return false; /* read_callback_ sets the state for us */
1680
1681         /* read colors */
1682         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN, read_callback_, decoder))
1683                 return false; /* read_callback_ sets the state for us */
1684
1685         /* read data */
1686         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN, read_callback_, decoder))
1687                 return false; /* read_callback_ sets the state for us */
1688         if(0 == (obj->data = (FLAC__byte*)malloc(obj->data_length))) {
1689                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1690                 return false;
1691         }
1692         if(obj->data_length > 0) {
1693                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length, read_callback_, decoder))
1694                         return false; /* read_callback_ sets the state for us */
1695         }
1696
1697         return true;
1698 }
1699
1700 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1701 {
1702         FLAC__uint32 x;
1703         unsigned i, skip;
1704
1705         /* skip the version and flags bytes */
1706         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 24, read_callback_, decoder))
1707                 return false; /* read_callback_ sets the state for us */
1708         /* get the size (in bytes) to skip */
1709         skip = 0;
1710         for(i = 0; i < 4; i++) {
1711                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1712                         return false; /* read_callback_ sets the state for us */
1713                 skip <<= 7;
1714                 skip |= (x & 0x7f);
1715         }
1716         /* skip the rest of the tag */
1717         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, skip, read_callback_, decoder))
1718                 return false; /* read_callback_ sets the state for us */
1719         return true;
1720 }
1721
1722 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1723 {
1724         FLAC__uint32 x;
1725         FLAC__bool first = true;
1726
1727         /* If we know the total number of samples in the stream, stop if we've read that many. */
1728         /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1729         if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
1730                 if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
1731                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1732                         return true;
1733                 }
1734         }
1735
1736         /* make sure we're byte aligned */
1737         if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
1738                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
1739                         return false; /* read_callback_ sets the state for us */
1740         }
1741
1742         while(1) {
1743                 if(decoder->private_->cached) {
1744                         x = (FLAC__uint32)decoder->private_->lookahead;
1745                         decoder->private_->cached = false;
1746                 }
1747                 else {
1748                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1749                                 return false; /* read_callback_ sets the state for us */
1750                 }
1751                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1752                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1753                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1754                                 return false; /* read_callback_ sets the state for us */
1755
1756                         /* 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 */
1757                         /* else we have to check if the second byte is the end of a sync code */
1758                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1759                                 decoder->private_->lookahead = (FLAC__byte)x;
1760                                 decoder->private_->cached = true;
1761                         }
1762                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1763                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1764                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1765                                 return true;
1766                         }
1767                 }
1768                 if(first) {
1769                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1770                         first = false;
1771                 }
1772         }
1773
1774         return true;
1775 }
1776
1777 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
1778 {
1779         unsigned channel;
1780         unsigned i;
1781         FLAC__int32 mid, side, left, right;
1782         FLAC__uint16 frame_crc; /* the one we calculate from the input stream */
1783         FLAC__uint32 x;
1784
1785         *got_a_frame = false;
1786
1787         /* init the CRC */
1788         frame_crc = 0;
1789         FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
1790         FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
1791         FLAC__bitbuffer_reset_read_crc16(decoder->private_->input, frame_crc);
1792
1793         if(!read_frame_header_(decoder))
1794                 return false;
1795         if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
1796                 return true;
1797         if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
1798                 return false;
1799         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1800                 /*
1801                  * first figure the correct bits-per-sample of the subframe
1802                  */
1803                 unsigned bps = decoder->private_->frame.header.bits_per_sample;
1804                 switch(decoder->private_->frame.header.channel_assignment) {
1805                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1806                                 /* no adjustment needed */
1807                                 break;
1808                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1809                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1810                                 if(channel == 1)
1811                                         bps++;
1812                                 break;
1813                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1814                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1815                                 if(channel == 0)
1816                                         bps++;
1817                                 break;
1818                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1819                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1820                                 if(channel == 1)
1821                                         bps++;
1822                                 break;
1823                         default:
1824                                 FLAC__ASSERT(0);
1825                 }
1826                 /*
1827                  * now read it
1828                  */
1829                 if(!read_subframe_(decoder, channel, bps, do_full_decode))
1830                         return false;
1831                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
1832                         return true;
1833         }
1834         if(!read_zero_padding_(decoder))
1835                 return false;
1836
1837         /*
1838          * Read the frame CRC-16 from the footer and check
1839          */
1840         frame_crc = FLAC__bitbuffer_get_read_crc16(decoder->private_->input);
1841         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN, read_callback_, decoder))
1842                 return false; /* read_callback_ sets the state for us */
1843         if(frame_crc == (FLAC__uint16)x) {
1844                 if(do_full_decode) {
1845                         /* Undo any special channel coding */
1846                         switch(decoder->private_->frame.header.channel_assignment) {
1847                                 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1848                                         /* do nothing */
1849                                         break;
1850                                 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1851                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1852                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1853                                                 decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
1854                                         break;
1855                                 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1856                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1857                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1858                                                 decoder->private_->output[0][i] += decoder->private_->output[1][i];
1859                                         break;
1860                                 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1861                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1862                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
1863                                                 mid = decoder->private_->output[0][i];
1864                                                 side = decoder->private_->output[1][i];
1865                                                 mid <<= 1;
1866                                                 if(side & 1) /* i.e. if 'side' is odd... */
1867                                                         mid++;
1868                                                 left = mid + side;
1869                                                 right = mid - side;
1870                                                 decoder->private_->output[0][i] = left >> 1;
1871                                                 decoder->private_->output[1][i] = right >> 1;
1872                                         }
1873                                         break;
1874                                 default:
1875                                         FLAC__ASSERT(0);
1876                                         break;
1877                         }
1878                 }
1879         }
1880         else {
1881                 /* Bad frame, emit error and zero the output signal */
1882                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
1883                 if(do_full_decode) {
1884                         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1885                                 memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
1886                         }
1887                 }
1888         }
1889
1890         *got_a_frame = true;
1891
1892         /* put the latest values into the public section of the decoder instance */
1893         decoder->protected_->channels = decoder->private_->frame.header.channels;
1894         decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
1895         decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
1896         decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
1897         decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
1898
1899         FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1900         decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
1901
1902         /* write it */
1903         if(do_full_decode) {
1904                 if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
1905                         return false;
1906         }
1907
1908         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1909         return true;
1910 }
1911
1912 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
1913 {
1914         FLAC__uint32 x;
1915         FLAC__uint64 xx;
1916         unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
1917         FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
1918         unsigned raw_header_len;
1919         FLAC__bool is_unparseable = false;
1920         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);
1921         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);
1922
1923         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1924
1925         /* init the raw header with the saved bits from synchronization */
1926         raw_header[0] = decoder->private_->header_warmup[0];
1927         raw_header[1] = decoder->private_->header_warmup[1];
1928         raw_header_len = 2;
1929
1930         /*
1931          * check to make sure that the reserved bits are 0
1932          */
1933         if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
1934                 is_unparseable = true;
1935         }
1936
1937         /*
1938          * Note that along the way as we read the header, we look for a sync
1939          * code inside.  If we find one it would indicate that our original
1940          * sync was bad since there cannot be a sync code in a valid header.
1941          */
1942
1943         /*
1944          * read in the raw header as bytes so we can CRC it, and parse it on the way
1945          */
1946         for(i = 0; i < 2; i++) {
1947                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1948                         return false; /* read_callback_ sets the state for us */
1949                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1950                         /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
1951                         decoder->private_->lookahead = (FLAC__byte)x;
1952                         decoder->private_->cached = true;
1953                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
1954                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1955                         return true;
1956                 }
1957                 raw_header[raw_header_len++] = (FLAC__byte)x;
1958         }
1959
1960         switch(x = raw_header[2] >> 4) {
1961                 case 0:
1962                         if(is_known_fixed_blocksize_stream)
1963                                 decoder->private_->frame.header.blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
1964                         else
1965                                 is_unparseable = true;
1966                         break;
1967                 case 1:
1968                         decoder->private_->frame.header.blocksize = 192;
1969                         break;
1970                 case 2:
1971                 case 3:
1972                 case 4:
1973                 case 5:
1974                         decoder->private_->frame.header.blocksize = 576 << (x-2);
1975                         break;
1976                 case 6:
1977                 case 7:
1978                         blocksize_hint = x;
1979                         break;
1980                 case 8:
1981                 case 9:
1982                 case 10:
1983                 case 11:
1984                 case 12:
1985                 case 13:
1986                 case 14:
1987                 case 15:
1988                         decoder->private_->frame.header.blocksize = 256 << (x-8);
1989                         break;
1990                 default:
1991                         FLAC__ASSERT(0);
1992                         break;
1993         }
1994
1995         switch(x = raw_header[2] & 0x0f) {
1996                 case 0:
1997                         if(decoder->private_->has_stream_info)
1998                                 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
1999                         else
2000                                 is_unparseable = true;
2001                         break;
2002                 case 1:
2003                 case 2:
2004                 case 3:
2005                         is_unparseable = true;
2006                         break;
2007                 case 4:
2008                         decoder->private_->frame.header.sample_rate = 8000;
2009                         break;
2010                 case 5:
2011                         decoder->private_->frame.header.sample_rate = 16000;
2012                         break;
2013                 case 6:
2014                         decoder->private_->frame.header.sample_rate = 22050;
2015                         break;
2016                 case 7:
2017                         decoder->private_->frame.header.sample_rate = 24000;
2018                         break;
2019                 case 8:
2020                         decoder->private_->frame.header.sample_rate = 32000;
2021                         break;
2022                 case 9:
2023                         decoder->private_->frame.header.sample_rate = 44100;
2024                         break;
2025                 case 10:
2026                         decoder->private_->frame.header.sample_rate = 48000;
2027                         break;
2028                 case 11:
2029                         decoder->private_->frame.header.sample_rate = 96000;
2030                         break;
2031                 case 12:
2032                 case 13:
2033                 case 14:
2034                         sample_rate_hint = x;
2035                         break;
2036                 case 15:
2037                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2038                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2039                         return true;
2040                 default:
2041                         FLAC__ASSERT(0);
2042         }
2043
2044         x = (unsigned)(raw_header[3] >> 4);
2045         if(x & 8) {
2046                 decoder->private_->frame.header.channels = 2;
2047                 switch(x & 7) {
2048                         case 0:
2049                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2050                                 break;
2051                         case 1:
2052                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2053                                 break;
2054                         case 2:
2055                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2056                                 break;
2057                         default:
2058                                 is_unparseable = true;
2059                                 break;
2060                 }
2061         }
2062         else {
2063                 decoder->private_->frame.header.channels = (unsigned)x + 1;
2064                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2065         }
2066
2067         switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2068                 case 0:
2069                         if(decoder->private_->has_stream_info)
2070                                 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2071                         else
2072                                 is_unparseable = true;
2073                         break;
2074                 case 1:
2075                         decoder->private_->frame.header.bits_per_sample = 8;
2076                         break;
2077                 case 2:
2078                         decoder->private_->frame.header.bits_per_sample = 12;
2079                         break;
2080                 case 4:
2081                         decoder->private_->frame.header.bits_per_sample = 16;
2082                         break;
2083                 case 5:
2084                         decoder->private_->frame.header.bits_per_sample = 20;
2085                         break;
2086                 case 6:
2087                         decoder->private_->frame.header.bits_per_sample = 24;
2088                         break;
2089                 case 3:
2090                 case 7:
2091                         is_unparseable = true;
2092                         break;
2093                 default:
2094                         FLAC__ASSERT(0);
2095                         break;
2096         }
2097
2098         if(raw_header[3] & 0x01) { /* this should be a zero padding bit */
2099                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2100                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2101                 return true;
2102         }
2103
2104         /*
2105          * Now we get to the regrettable consequences of not knowing for sure
2106          * whether we got a frame number or a sample number.  There are no
2107          * encoders that do variable-blocksize encoding so unless we know from
2108          * the STREAMINFO that it is variable-blocksize we will assume it is
2109          * fixed-blocksize.  The trouble comes when we have no STREAMINFO; again
2110          * we will guess that is fixed-blocksize.  Where this can go wrong: 1) a
2111          * variable-blocksize stream with no STREAMINFO; 2) a fixed-blocksize
2112          * stream that was edited such that one or more frames before or
2113          * including this one do not have the same number of samples as the
2114          * STREAMINFO's min and max blocksize.
2115          */
2116         if(is_known_variable_blocksize_stream) {
2117                 if(blocksize_hint) {
2118                         if(!FLAC__bitbuffer_read_utf8_uint64(decoder->private_->input, &xx, read_callback_, decoder, raw_header, &raw_header_len))
2119                                 return false; /* read_callback_ sets the state for us */
2120                         if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
2121                                 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2122                                 decoder->private_->cached = true;
2123                                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2124                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2125                                 return true;
2126                         }
2127                         decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2128                         decoder->private_->frame.header.number.sample_number = xx;
2129                 }
2130                 else
2131                         is_unparseable = true;
2132         }
2133         else {
2134                 if(!FLAC__bitbuffer_read_utf8_uint32(decoder->private_->input, &x, read_callback_, decoder, raw_header, &raw_header_len))
2135                         return false; /* read_callback_ sets the state for us */
2136                 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
2137                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2138                         decoder->private_->cached = true;
2139                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2140                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2141                         return true;
2142                 }
2143                 decoder->private_->last_frame_number = x;
2144                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2145                 if(decoder->private_->has_stream_info) {
2146                         FLAC__ASSERT(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize);
2147                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
2148                         decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2149                 }
2150                 else if(blocksize_hint) {
2151                         if(decoder->private_->last_block_size)
2152                                 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->last_block_size * (FLAC__uint64)x;
2153                         else
2154                                 is_unparseable = true;
2155                 }
2156                 else {
2157                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
2158                         decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2159                 }
2160         }
2161
2162         if(blocksize_hint) {
2163                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2164                         return false; /* read_callback_ sets the state for us */
2165                 raw_header[raw_header_len++] = (FLAC__byte)x;
2166                 if(blocksize_hint == 7) {
2167                         FLAC__uint32 _x;
2168                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
2169                                 return false; /* read_callback_ sets the state for us */
2170                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2171                         x = (x << 8) | _x;
2172                 }
2173                 decoder->private_->frame.header.blocksize = x+1;
2174         }
2175
2176         if(sample_rate_hint) {
2177                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2178                         return false; /* read_callback_ sets the state for us */
2179                 raw_header[raw_header_len++] = (FLAC__byte)x;
2180                 if(sample_rate_hint != 12) {
2181                         FLAC__uint32 _x;
2182                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
2183                                 return false; /* read_callback_ sets the state for us */
2184                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2185                         x = (x << 8) | _x;
2186                 }
2187                 if(sample_rate_hint == 12)
2188                         decoder->private_->frame.header.sample_rate = x*1000;
2189                 else if(sample_rate_hint == 13)
2190                         decoder->private_->frame.header.sample_rate = x;
2191                 else
2192                         decoder->private_->frame.header.sample_rate = x*10;
2193         }
2194
2195         /* read the CRC-8 byte */
2196         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2197                 return false; /* read_callback_ sets the state for us */
2198         crc8 = (FLAC__byte)x;
2199
2200         if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
2201                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2202                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2203                 return true;
2204         }
2205
2206         if(is_unparseable) {
2207                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2208                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2209                 return true;
2210         }
2211
2212         return true;
2213 }
2214
2215 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2216 {
2217         FLAC__uint32 x;
2218         FLAC__bool wasted_bits;
2219         unsigned i;
2220
2221         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder)) /* MAGIC NUMBER */
2222                 return false; /* read_callback_ sets the state for us */
2223
2224         wasted_bits = (x & 1);
2225         x &= 0xfe;
2226
2227         if(wasted_bits) {
2228                 unsigned u;
2229                 if(!FLAC__bitbuffer_read_unary_unsigned(decoder->private_->input, &u, read_callback_, decoder))
2230                         return false; /* read_callback_ sets the state for us */
2231                 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
2232                 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
2233         }
2234         else
2235                 decoder->private_->frame.subframes[channel].wasted_bits = 0;
2236
2237         /*
2238          * Lots of magic numbers here
2239          */
2240         if(x & 0x80) {
2241                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2242                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2243                 return true;
2244         }
2245         else if(x == 0) {
2246                 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2247                         return false;
2248         }
2249         else if(x == 2) {
2250                 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2251                         return false;
2252         }
2253         else if(x < 16) {
2254                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2255                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2256                 return true;
2257         }
2258         else if(x <= 24) {
2259                 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2260                         return false;
2261                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2262                         return true;
2263         }
2264         else if(x < 64) {
2265                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2266                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2267                 return true;
2268         }
2269         else {
2270                 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2271                         return false;
2272                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2273                         return true;
2274         }
2275
2276         if(wasted_bits && do_full_decode) {
2277                 x = decoder->private_->frame.subframes[channel].wasted_bits;
2278                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2279                         decoder->private_->output[channel][i] <<= x;
2280         }
2281
2282         return true;
2283 }
2284
2285 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2286 {
2287         FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2288         FLAC__int32 x;
2289         unsigned i;
2290         FLAC__int32 *output = decoder->private_->output[channel];
2291
2292         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2293
2294         if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
2295                 return false; /* read_callback_ sets the state for us */
2296
2297         subframe->value = x;
2298
2299         /* decode the subframe */
2300         if(do_full_decode) {
2301                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2302                         output[i] = x;
2303         }
2304
2305         return true;
2306 }
2307
2308 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2309 {
2310         FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2311         FLAC__int32 i32;
2312         FLAC__uint32 u32;
2313         unsigned u;
2314
2315         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2316
2317         subframe->residual = decoder->private_->residual[channel];
2318         subframe->order = order;
2319
2320         /* read warm-up samples */
2321         for(u = 0; u < order; u++) {
2322                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
2323                         return false; /* read_callback_ sets the state for us */
2324                 subframe->warmup[u] = i32;
2325         }
2326
2327         /* read entropy coding method info */
2328         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
2329                 return false; /* read_callback_ sets the state for us */
2330         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2331         switch(subframe->entropy_coding_method.type) {
2332                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2333                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
2334                                 return false; /* read_callback_ sets the state for us */
2335                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2336                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2337                         break;
2338                 default:
2339                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2340                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2341                         return true;
2342         }
2343
2344         /* read residual */
2345         switch(subframe->entropy_coding_method.type) {
2346                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2347                         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]))
2348                                 return false;
2349                         break;
2350                 default:
2351                         FLAC__ASSERT(0);
2352         }
2353
2354         /* decode the subframe */
2355         if(do_full_decode) {
2356                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2357                 FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
2358         }
2359
2360         return true;
2361 }
2362
2363 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2364 {
2365         FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2366         FLAC__int32 i32;
2367         FLAC__uint32 u32;
2368         unsigned u;
2369
2370         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2371
2372         subframe->residual = decoder->private_->residual[channel];
2373         subframe->order = order;
2374
2375         /* read warm-up samples */
2376         for(u = 0; u < order; u++) {
2377                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
2378                         return false; /* read_callback_ sets the state for us */
2379                 subframe->warmup[u] = i32;
2380         }
2381
2382         /* read qlp coeff precision */
2383         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN, read_callback_, decoder))
2384                 return false; /* read_callback_ sets the state for us */
2385         if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
2386                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2387                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2388                 return true;
2389         }
2390         subframe->qlp_coeff_precision = u32+1;
2391
2392         /* read qlp shift */
2393         if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN, read_callback_, decoder))
2394                 return false; /* read_callback_ sets the state for us */
2395         subframe->quantization_level = i32;
2396
2397         /* read quantized lp coefficiencts */
2398         for(u = 0; u < order; u++) {
2399                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision, read_callback_, decoder))
2400                         return false; /* read_callback_ sets the state for us */
2401                 subframe->qlp_coeff[u] = i32;
2402         }
2403
2404         /* read entropy coding method info */
2405         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
2406                 return false; /* read_callback_ sets the state for us */
2407         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2408         switch(subframe->entropy_coding_method.type) {
2409                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2410                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
2411                                 return false; /* read_callback_ sets the state for us */
2412                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2413                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2414                         break;
2415                 default:
2416                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2417                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2418                         return true;
2419         }
2420
2421         /* read residual */
2422         switch(subframe->entropy_coding_method.type) {
2423                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2424                         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]))
2425                                 return false;
2426                         break;
2427                 default:
2428                         FLAC__ASSERT(0);
2429         }
2430
2431         /* decode the subframe */
2432         if(do_full_decode) {
2433                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2434                 if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2435                         if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2436                                 if(order <= 8)
2437                                         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);
2438                                 else
2439                                         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);
2440                         }
2441                         else
2442                                 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);
2443                 else
2444                         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);
2445         }
2446
2447         return true;
2448 }
2449
2450 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2451 {
2452         FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2453         FLAC__int32 x, *residual = decoder->private_->residual[channel];
2454         unsigned i;
2455
2456         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2457
2458         subframe->data = residual;
2459
2460         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2461                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
2462                         return false; /* read_callback_ sets the state for us */
2463                 residual[i] = x;
2464         }
2465
2466         /* decode the subframe */
2467         if(do_full_decode)
2468                 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2469
2470         return true;
2471 }
2472
2473 FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual)
2474 {
2475         FLAC__uint32 rice_parameter;
2476         int i;
2477         unsigned partition, sample, u;
2478         const unsigned partitions = 1u << partition_order;
2479         const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2480
2481         /* sanity checks */
2482         if(partition_order == 0) {
2483                 if(decoder->private_->frame.header.blocksize < predictor_order) {
2484                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2485                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2486                         return true;
2487                 }
2488         }
2489         else {
2490                 if(partition_samples < predictor_order) {
2491                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2492                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2493                         return true;
2494                 }
2495         }
2496
2497         if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2498                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2499                 return false;
2500         }
2501
2502         sample = 0;
2503         for(partition = 0; partition < partitions; partition++) {
2504                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN, read_callback_, decoder))
2505                         return false; /* read_callback_ sets the state for us */
2506                 partitioned_rice_contents->parameters[partition] = rice_parameter;
2507                 if(rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2508                         u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2509                         if(!FLAC__bitbuffer_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter, read_callback_, decoder))
2510                                 return false; /* read_callback_ sets the state for us */
2511                         sample += u;
2512                 }
2513                 else {
2514                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN, read_callback_, decoder))
2515                                 return false; /* read_callback_ sets the state for us */
2516                         partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2517                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2518                                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i, rice_parameter, read_callback_, decoder))
2519                                         return false; /* read_callback_ sets the state for us */
2520                                 residual[sample] = i;
2521                         }
2522                 }
2523         }
2524
2525         return true;
2526 }
2527
2528 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2529 {
2530         if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
2531                 FLAC__uint32 zero = 0;
2532                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
2533                         return false; /* read_callback_ sets the state for us */
2534                 if(zero != 0) {
2535                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2536                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2537                 }
2538         }
2539         return true;
2540 }
2541
2542 FLAC__bool read_callback_(FLAC__byte buffer[], unsigned *bytes, void *client_data)
2543 {
2544         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2545
2546         if(decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)) {
2547                 *bytes = 0;
2548                 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2549                 return false;
2550         }
2551         else if(*bytes > 0) {
2552                 /* While seeking, it is possible for our seek to land in the
2553                  * middle of audio data that looks exactly like a frame header
2554                  * from a future version of an encoder.  When that happens, our
2555                  * error callback will get an
2556                  * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
2557                  * unparseable_frame_count.  But there is a remote possibility
2558                  * that it is properly synced at such a "future-codec frame",
2559                  * so to make sure, we wait to see many "unparseable" errors in
2560                  * a row before bailing out.
2561                  */
2562                 if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2563                         decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2564                         return false;
2565                 }
2566                 else {
2567                         const FLAC__StreamDecoderReadStatus status = decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data);
2568                         if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
2569                                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2570                                 return false;
2571                         }
2572                         else if(*bytes == 0) {
2573                                 if(status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM || (decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data))) {
2574                                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2575                                         return false;
2576                                 }
2577                                 else
2578                                         return true;
2579                         }
2580                         else
2581                                 return true;
2582                 }
2583         }
2584         else {
2585                 /* abort to avoid a deadlock */
2586                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2587                 return false;
2588         }
2589 }
2590
2591 FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2592 {
2593         if(decoder->private_->is_seeking) {
2594                 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
2595                 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
2596                 FLAC__uint64 target_sample = decoder->private_->target_sample;
2597
2598                 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2599
2600                 decoder->private_->last_frame = *frame; /* save the frame */
2601                 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
2602                         unsigned delta = (unsigned)(target_sample - this_frame_sample);
2603                         /* kick out of seek mode */
2604                         decoder->private_->is_seeking = false;
2605                         /* shift out the samples before target_sample */
2606                         if(delta > 0) {
2607                                 unsigned channel;
2608                                 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
2609                                 for(channel = 0; channel < frame->header.channels; channel++)
2610                                         newbuffer[channel] = buffer[channel] + delta;
2611                                 decoder->private_->last_frame.header.blocksize -= delta;
2612                                 decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
2613                                 /* write the relevant samples */
2614                                 return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
2615                         }
2616                         else {
2617                                 /* write the relevant samples */
2618                                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2619                         }
2620                 }
2621                 else {
2622                         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2623                 }
2624         }
2625         else {
2626                 /*
2627                  * If we never got STREAMINFO, turn off MD5 checking to save
2628                  * cycles since we don't have a sum to compare to anyway
2629                  */
2630                 if(!decoder->private_->has_stream_info)
2631                         decoder->private_->do_md5_checking = false;
2632                 if(decoder->private_->do_md5_checking) {
2633                         if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
2634                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2635                 }
2636                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2637         }
2638 }
2639
2640 void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2641 {
2642         if(!decoder->private_->is_seeking)
2643                 decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
2644         else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
2645                 decoder->private_->unparseable_frame_count++;
2646 }
2647
2648 FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2649 {
2650         FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound;
2651         FLAC__int64 pos = -1, last_pos = -1;
2652         int i, lower_seek_point = -1, upper_seek_point = -1;
2653         unsigned approx_bytes_per_frame;
2654         FLAC__uint64 last_frame_sample = FLAC__U64L(0xffffffffffffffff);
2655         FLAC__bool needs_seek;
2656         const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
2657         const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2658         const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
2659         const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
2660         const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
2661         const unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
2662         const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
2663
2664         /* we are just guessing here, but we want to guess high, not low */
2665         if(max_framesize > 0)
2666                 approx_bytes_per_frame = max_framesize;
2667
2668         /*
2669          * Check if it's a known fixed-blocksize stream.  Note that though
2670          * the spec doesn't allow zeroes in the STREAMINFO block, we may
2671          * never get a STREAMINFO block when decoding so the value of
2672          * min_blocksize might be zero.
2673          */
2674         else if(min_blocksize == max_blocksize && min_blocksize > 0) {
2675                 /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
2676                 approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
2677         }
2678         else
2679                 approx_bytes_per_frame = 4608 * channels * bps/8 + 64;
2680
2681         /*
2682          * First, we set an upper and lower bound on where in the
2683          * stream we will search.  For now we assume the worst case
2684          * scenario, which is our best guess at the beginning of
2685          * the first and last frames.
2686          */
2687         lower_bound = first_frame_offset;
2688
2689         /* calc the upper_bound, beyond which we never want to seek */
2690         if(max_framesize > 0)
2691                 upper_bound = stream_length - (max_framesize + 128 + 2); /* 128 for a possible ID3V1 tag, 2 for indexing differences */
2692         else
2693                 upper_bound = stream_length - ((channels * bps * FLAC__MAX_BLOCK_SIZE) / 8 + 128 + 2);
2694
2695         /*
2696          * Now we refine the bounds if we have a seektable with
2697          * suitable points.  Note that according to the spec they
2698          * must be ordered by ascending sample number.
2699          */
2700         if(seek_table) {
2701                 /* find the closest seek point <= target_sample, if it exists */
2702                 for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
2703                         if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number <= target_sample)
2704                                 break;
2705                 }
2706                 if(i >= 0) { /* i.e. we found a suitable seek point... */
2707                         lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
2708                         lower_seek_point = i;
2709                 }
2710
2711                 /* find the closest seek point > target_sample, if it exists */
2712                 for(i = 0; i < (int)seek_table->num_points; i++) {
2713                         if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number > target_sample)
2714                                 break;
2715                 }
2716                 if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
2717                         upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
2718                         upper_seek_point = i;
2719                 }
2720         }
2721
2722         /*
2723          * Now guess at where within those bounds our target
2724          * sample will be.
2725          */
2726         if(seek_table && lower_seek_point >= 0) {
2727                 /* first see if our sample is within a few frames of the lower seekpoint */
2728                 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)) {
2729                         pos = (FLAC__int64)lower_bound;
2730                 }
2731                 else if(upper_seek_point >= 0) {
2732                         const FLAC__uint64 target_offset = target_sample - seek_table->points[lower_seek_point].sample_number;
2733                         const FLAC__uint64 range_samples = seek_table->points[upper_seek_point].sample_number - seek_table->points[lower_seek_point].sample_number;
2734                         const FLAC__uint64 range_bytes = (upper_bound>lower_bound? upper_bound - lower_bound - 1 : 0);
2735 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2736 #if defined _MSC_VER || defined __MINGW32__
2737                         /* with MSVC you have to spoon feed it the casting */
2738                         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;
2739 #else
2740                         pos = (FLAC__int64)lower_bound + (FLAC__int64)(((FLAC__double)target_offset / (FLAC__double)range_samples) * (FLAC__double)range_bytes) - approx_bytes_per_frame;
2741 #endif
2742 #else
2743                         /* a little less accurate: */
2744                         if (range_bytes <= 0xffffffff)
2745                                 pos = (FLAC__int64)lower_bound + (FLAC__int64)((target_offset * range_bytes) / range_samples) - approx_bytes_per_frame;
2746                         else /* @@@ WATCHOUT, ~2TB limit */
2747                                 pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_offset>>8) * (range_bytes>>8)) / (range_samples>>16)) - approx_bytes_per_frame;
2748 #endif
2749                 }
2750         }
2751
2752         /*
2753          * If there's no seek table, we need to use the metadata (if we
2754          * have it) and the filelength to estimate the position of the
2755          * frame with the correct sample.
2756          */
2757         if(pos < 0 && total_samples > 0) {
2758                 /*
2759                  * For max accuracy we should be using
2760                  * (stream_length-first_frame_offset-1) in the divisor, but the
2761                  * difference is trivial and (stream_length-first_frame_offset)
2762                  * has no chance of underflow.
2763                  */
2764 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2765 #if defined _MSC_VER || defined __MINGW32__
2766                 /* with VC++ you have to spoon feed it the casting */
2767                 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;
2768 #else
2769                 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;
2770 #endif
2771 #else
2772                 /* a little less accurate: */
2773                 if (stream_length < 0xffffffff)
2774                         pos = (FLAC__int64)first_frame_offset + (FLAC__int64)((target_sample * (stream_length-first_frame_offset)) / total_samples) - approx_bytes_per_frame;
2775                 else /* @@@ WATCHOUT, ~2TB limit */
2776                         pos = (FLAC__int64)first_frame_offset + (FLAC__int64)(((target_sample>>8) * ((stream_length-first_frame_offset)>>8)) / (total_samples>>16)) - approx_bytes_per_frame;
2777 #endif
2778         }
2779
2780         /*
2781          * If there's no seek table and total_samples is unknown, we
2782          * don't even bother trying to figure out a target, we just use
2783          * our current position.
2784          */
2785         if(pos < 0) {
2786                 FLAC__uint64 upos;
2787                 if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK) {
2788                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2789                         return false;
2790                 }
2791                 pos = (FLAC__int64)upos;
2792                 needs_seek = false;
2793         }
2794         else
2795                 needs_seek = true;
2796
2797         /* clip the position to the bounds, lower bound takes precedence */
2798         if(pos >= (FLAC__int64)upper_bound) {
2799                 pos = (FLAC__int64)upper_bound-1;
2800                 needs_seek = true;
2801         }
2802         if(pos < (FLAC__int64)lower_bound) {
2803                 pos = (FLAC__int64)lower_bound;
2804                 needs_seek = true;
2805         }
2806
2807         decoder->private_->target_sample = target_sample;
2808         while(1) {
2809                 if(needs_seek) {
2810                         if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
2811                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2812                                 return false;
2813                         }
2814                         if(!FLAC__stream_decoder_flush(decoder)) {
2815                                 /* above call sets the state for us */
2816                                 return false;
2817                         }
2818                 }
2819                 /* Now we need to get a frame.  First we need to reset our
2820                  * unparseable_frame_count; if we get too many unparseable
2821                  * frames in a row, the read callback will return
2822                  * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
2823                  * FLAC__stream_decoder_process_single() to return false.
2824                  */
2825                 decoder->private_->unparseable_frame_count = 0;
2826                 if(!FLAC__stream_decoder_process_single(decoder)) {
2827                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2828                         return false;
2829                 }
2830                 /* our write callback will change the state when it gets to the target frame */
2831                 /* 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 */
2832 #if 0
2833                 /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
2834                 if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
2835                         break;
2836 #endif
2837                 if(!decoder->private_->is_seeking) {
2838                         break;
2839                 }
2840                 else { /* we need to narrow the search */
2841                         const FLAC__uint64 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
2842                         FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2843                         if(this_frame_sample == last_frame_sample && pos < last_pos) {
2844                                 /* our last move backwards wasn't big enough, double it */
2845                                 pos -= (last_pos - pos);
2846                                 needs_seek = true;
2847                         }
2848                         else {
2849                                 if(target_sample < this_frame_sample) {
2850                                         last_pos = pos;
2851                                         approx_bytes_per_frame = decoder->private_->last_frame.header.blocksize * channels * bps/8 + 64;
2852                                         pos -= approx_bytes_per_frame;
2853                                         needs_seek = true;
2854                                 }
2855                                 else { /* target_sample >= this_frame_sample + this frame's blocksize */
2856                                         FLAC__uint64 upos;
2857                                         if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK) {
2858                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2859                                                 return false;
2860                                         }
2861                                         last_pos = pos;
2862                                         pos = (FLAC__int64)upos;
2863                                         pos -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
2864                                         needs_seek = false;
2865                                         /*
2866                                          * if we haven't hit the target frame yet and our position hasn't changed,
2867                                          * it means we're at the end of the stream and the seek target does not exist.
2868                                          */
2869                                         if(last_pos == pos) {
2870                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2871                                                 return false;
2872                                         }
2873                                 }
2874                         }
2875                         if(pos < (FLAC__int64)lower_bound)
2876                                 pos = (FLAC__int64)lower_bound;
2877                         last_frame_sample = this_frame_sample;
2878                 }
2879         }
2880
2881         return true;
2882 }
2883
2884 FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
2885 {
2886         (void)client_data;
2887
2888         if(*bytes > 0) {
2889                 *bytes = (unsigned)fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
2890                 if(ferror(decoder->private_->file))
2891                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2892                 else if(*bytes == 0)
2893                         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2894                 else
2895                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2896         }
2897         else
2898                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
2899 }
2900
2901 FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2902 {
2903         (void)client_data;
2904
2905         if(decoder->private_->file == stdin)
2906                 return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
2907         else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
2908                 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
2909         else
2910                 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2911 }
2912
2913 FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2914 {
2915         off_t pos;
2916         (void)client_data;
2917
2918         if(decoder->private_->file == stdin) /*@@@@@@ may work for stdin */
2919                 return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
2920         else if((pos = ftello(decoder->private_->file)) < 0)
2921                 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
2922         else {
2923                 *absolute_byte_offset = (FLAC__uint64)pos;
2924                 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2925         }
2926 }
2927
2928 FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2929 {
2930         struct stat filestats;
2931         (void)client_data;
2932
2933         if(decoder->private_->file == stdin)
2934                 return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
2935         else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
2936                 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
2937         else {
2938                 *stream_length = (FLAC__uint64)filestats.st_size;
2939                 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2940         }
2941 }
2942
2943 FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
2944 {
2945         (void)client_data;
2946
2947         if(decoder->private_->file == stdin) /*@@@@@@ feof() may work for stdin */
2948                 return false;
2949         return feof(decoder->private_->file)? true : false;
2950 }