merge down from merged-API-layer branch: cvs -q up -dP -j API_LAYER_MERGING_BASELINE...
[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 /*@@@ [2G limit] hacks for MSVC6 */
51 #define fseeko fseek
52 #define ftello ftell
53 #endif
54 #include "FLAC/assert.h"
55 #include "protected/stream_decoder.h"
56 #include "private/bitbuffer.h"
57 #include "private/bitmath.h"
58 #include "private/cpu.h"
59 #include "private/crc.h"
60 #include "private/fixed.h"
61 #include "private/format.h"
62 #include "private/lpc.h"
63 #include "private/md5.h"
64 #include "private/memory.h"
65
66 #undef OLD_STAT_WAY /*@@@@@@ old way of keeping the filename and using stat(); remove remnants once we know this works */
67
68 #ifdef max
69 #undef max
70 #endif
71 #define max(a,b) ((a)>(b)?(a):(b))
72
73 /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
74 #ifdef _MSC_VER
75 #define FLAC__U64L(x) x
76 #else
77 #define FLAC__U64L(x) x##LLU
78 #endif
79
80 /***********************************************************************
81  *
82  * Private static data
83  *
84  ***********************************************************************/
85
86 static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
87
88 /***********************************************************************
89  *
90  * Private class method prototypes
91  *
92  ***********************************************************************/
93
94 static void set_defaults_(FLAC__StreamDecoder *decoder);
95 static FILE *get_binary_stdin_();
96 static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
97 static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
98 static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
99 static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
100 static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
101 static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
102 static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
103 static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
104 static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
105 static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
106 static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
107 static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
108 static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
109 static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
110 static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
111 static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
112 static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
113 static FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual);
114 static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
115 static FLAC__bool read_callback_(FLAC__byte buffer[], unsigned *bytes, void *client_data);
116 static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
117 static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
118 static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
119 static FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
120 static FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
121 static FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
122 static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
123 static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
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 #ifdef OLD_STAT_WAY
151         char *filename; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
152 #endif
153         FLAC__BitBuffer *input;
154         FLAC__int32 *output[FLAC__MAX_CHANNELS];
155         FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
156         FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
157         unsigned output_capacity, output_channels;
158         FLAC__uint32 last_frame_number;
159         FLAC__uint32 last_block_size;
160         FLAC__uint64 samples_decoded;
161         FLAC__bool has_stream_info, has_seek_table;
162         FLAC__StreamMetadata stream_info;
163         FLAC__StreamMetadata seek_table;
164         FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
165         FLAC__byte *metadata_filter_ids;
166         unsigned metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
167         FLAC__Frame frame;
168         FLAC__bool cached; /* true if there is a byte in lookahead */
169         FLAC__CPUInfo cpuinfo;
170         FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
171         FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
172         /* unaligned (original) pointers to allocated data */
173         FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
174         FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */
175         FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
176         FLAC__bool is_seeking;
177         struct FLAC__MD5Context md5context;
178         FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
179         /* (the rest of these are only used for seeking) */
180         FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
181         FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
182         FLAC__uint64 target_sample;
183         unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
184 } FLAC__StreamDecoderPrivate;
185
186 /***********************************************************************
187  *
188  * Public static class data
189  *
190  ***********************************************************************/
191
192 FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
193         "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
194         "FLAC__STREAM_DECODER_READ_METADATA",
195         "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
196         "FLAC__STREAM_DECODER_READ_FRAME",
197         "FLAC__STREAM_DECODER_END_OF_STREAM",
198         "FLAC__STREAM_DECODER_SEEK_ERROR",
199         "FLAC__STREAM_DECODER_ABORTED",
200         "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
201         "FLAC__STREAM_DECODER_UNINITIALIZED"
202 };
203
204 FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
205         "FLAC__STREAM_DECODER_INIT_STATUS_OK",
206         "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
207         "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
208         "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
209         "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
210 };
211
212 FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
213         "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
214         "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
215         "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
216 };
217
218 FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
219         "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
220         "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
221         "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
222 };
223
224 FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
225         "FLAC__STREAM_DECODER_TELL_STATUS_OK",
226         "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
227         "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
228 };
229
230 FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
231         "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
232         "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
233         "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
234 };
235
236 FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
237         "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
238         "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
239 };
240
241 FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
242         "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
243         "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
244         "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
245         "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
246 };
247
248 /***********************************************************************
249  *
250  * Class constructor/destructor
251  *
252  ***********************************************************************/
253 FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new()
254 {
255         FLAC__StreamDecoder *decoder;
256         unsigned i;
257
258         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
259
260         decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
261         if(decoder == 0) {
262                 return 0;
263         }
264
265         decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
266         if(decoder->protected_ == 0) {
267                 free(decoder);
268                 return 0;
269         }
270
271         decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
272         if(decoder->private_ == 0) {
273                 free(decoder->protected_);
274                 free(decoder);
275                 return 0;
276         }
277
278         decoder->private_->input = FLAC__bitbuffer_new();
279         if(decoder->private_->input == 0) {
280                 free(decoder->private_);
281                 free(decoder->protected_);
282                 free(decoder);
283                 return 0;
284         }
285
286         decoder->private_->metadata_filter_ids_capacity = 16;
287         if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
288                 FLAC__bitbuffer_delete(decoder->private_->input);
289                 free(decoder->private_);
290                 free(decoder->protected_);
291                 free(decoder);
292                 return 0;
293         }
294
295         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
296                 decoder->private_->output[i] = 0;
297                 decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
298         }
299
300         decoder->private_->output_capacity = 0;
301         decoder->private_->output_channels = 0;
302         decoder->private_->has_seek_table = false;
303
304         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
305                 FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
306
307         decoder->private_->file = 0;
308
309         set_defaults_(decoder);
310
311         decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
312
313         return decoder;
314 }
315
316 FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
317 {
318         unsigned i;
319
320         FLAC__ASSERT(0 != decoder);
321         FLAC__ASSERT(0 != decoder->protected_);
322         FLAC__ASSERT(0 != decoder->private_);
323         FLAC__ASSERT(0 != decoder->private_->input);
324
325         FLAC__stream_decoder_finish(decoder);
326
327         if(0 != decoder->private_->metadata_filter_ids)
328                 free(decoder->private_->metadata_filter_ids);
329
330         FLAC__bitbuffer_delete(decoder->private_->input);
331
332         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
333                 FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
334
335         free(decoder->private_);
336         free(decoder->protected_);
337         free(decoder);
338 }
339
340 /***********************************************************************
341  *
342  * Public class methods
343  *
344  ***********************************************************************/
345
346 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
347         FLAC__StreamDecoder *decoder,
348         FLAC__StreamDecoderReadCallback read_callback,
349         FLAC__StreamDecoderSeekCallback seek_callback,
350         FLAC__StreamDecoderTellCallback tell_callback,
351         FLAC__StreamDecoderLengthCallback length_callback,
352         FLAC__StreamDecoderEofCallback eof_callback,
353         FLAC__StreamDecoderWriteCallback write_callback,
354         FLAC__StreamDecoderMetadataCallback metadata_callback,
355         FLAC__StreamDecoderErrorCallback error_callback,
356         void *client_data
357 )
358 {
359         FLAC__ASSERT(0 != decoder);
360
361         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
362                 return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
363
364         if(
365                 0 == read_callback ||
366                 0 == write_callback ||
367                 0 == error_callback ||
368                 (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
369         )
370                 return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
371
372         /*
373          * get the CPU info and set the function pointers
374          */
375         FLAC__cpu_info(&decoder->private_->cpuinfo);
376         /* first default to the non-asm routines */
377         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
378         decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
379         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
380         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
381         /* now override with asm where appropriate */
382 #ifndef FLAC__NO_ASM
383         if(decoder->private_->cpuinfo.use_asm) {
384 #ifdef FLAC__CPU_IA32
385                 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
386 #ifdef FLAC__HAS_NASM
387                 if(decoder->private_->cpuinfo.data.ia32.mmx) {
388                         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
389                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
390                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
391                 }
392                 else {
393                         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
394                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
395                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
396                 }
397 #endif
398 #elif defined FLAC__CPU_PPC
399                 FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
400                 if(decoder->private_->cpuinfo.data.ppc.altivec) {
401                         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
402                         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
403                 }
404 #endif
405         }
406 #endif
407
408         /* from here on, errors are fatal */
409
410         if(!FLAC__bitbuffer_init(decoder->private_->input)) {
411                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
412                 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
413         }
414
415         decoder->private_->read_callback = read_callback;
416         decoder->private_->seek_callback = seek_callback;
417         decoder->private_->tell_callback = tell_callback;
418         decoder->private_->length_callback = length_callback;
419         decoder->private_->eof_callback = eof_callback;
420         decoder->private_->write_callback = write_callback;
421         decoder->private_->metadata_callback = metadata_callback;
422         decoder->private_->error_callback = error_callback;
423         decoder->private_->client_data = client_data;
424         decoder->private_->last_frame_number = 0;
425         decoder->private_->last_block_size = 0;
426         decoder->private_->samples_decoded = 0;
427         decoder->private_->has_stream_info = false;
428         decoder->private_->cached = false;
429
430         decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
431         decoder->private_->is_seeking = false;
432
433         decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
434         if(!FLAC__stream_decoder_reset(decoder)) {
435                 /* above call sets the state for us */
436                 return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
437         }
438
439         return FLAC__STREAM_DECODER_INIT_STATUS_OK;
440 }
441
442 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
443         FLAC__StreamDecoder *decoder,
444         FILE *file,
445         FLAC__StreamDecoderWriteCallback write_callback,
446         FLAC__StreamDecoderMetadataCallback metadata_callback,
447         FLAC__StreamDecoderErrorCallback error_callback,
448         void *client_data
449 )
450 {
451         FLAC__ASSERT(0 != decoder);
452         FLAC__ASSERT(0 != file);
453
454         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
455                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
456
457         if(0 == write_callback || 0 == error_callback)
458                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
459
460         /*
461          * To make sure that our file does not go unclosed after an error, we
462          * must assign the FILE pointer before any further error can occur in
463          * this routine.
464          */
465         if(file == stdin)
466                 file = get_binary_stdin_(); /* just to be safe */
467
468         decoder->private_->file = file;
469
470 #ifdef OLD_STAT_WAY
471         if(0 != decoder->private_->filename) {
472                 free(decoder->private_->filename);
473                 decoder->private_->filename = 0;
474         }
475         if(filename) {
476                 if(0 == (decoder->private_->filename = strdup(filename))) {
477                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
478                         return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
479                 }
480         }
481 #endif
482
483         return FLAC__stream_decoder_init_stream(
484                 decoder,
485                 file_read_callback_,
486                 decoder->private_->file == stdin? 0: file_seek_callback_,
487                 decoder->private_->file == stdin? 0: file_tell_callback_,/*@@@@@@ might work for stdin*/
488                 decoder->private_->file == stdin? 0: file_length_callback_,
489                 decoder->private_->file == stdin? 0: file_eof_callback_,/*@@@@@@ might work for stdin*/
490                 write_callback,
491                 metadata_callback,
492                 error_callback,
493                 client_data
494         );
495 }
496
497 FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
498         FLAC__StreamDecoder *decoder,
499         const char *filename,
500         FLAC__StreamDecoderWriteCallback write_callback,
501         FLAC__StreamDecoderMetadataCallback metadata_callback,
502         FLAC__StreamDecoderErrorCallback error_callback,
503         void *client_data
504 )
505 {
506         FILE *file;
507
508         FLAC__ASSERT(0 != decoder);
509
510         /*
511          * To make sure that our file does not go unclosed after an error, we
512          * have to do the same entrance checks here that are later performed
513          * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
514          */
515         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
516                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
517
518         if(0 == write_callback || 0 == error_callback)
519                 return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
520
521         file = filename? fopen(filename, "rb") : stdin;
522
523         if(0 == file)
524                 return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
525
526 #ifdef OLD_STAT_WAY
527         if(0 != decoder->private_->filename) {
528                 free(decoder->private_->filename);
529                 decoder->private_->filename = 0;
530         }
531         if(filename) {
532                 if(0 == (decoder->private_->filename = strdup(filename))) {
533                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
534                         return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
535                 }
536         }
537 #endif
538
539         return FLAC__stream_decoder_init_FILE(decoder, file, write_callback, metadata_callback, error_callback, client_data);
540 }
541
542 FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
543 {
544         FLAC__bool md5_failed = false;
545         unsigned i;
546
547         FLAC__ASSERT(0 != decoder);
548         FLAC__ASSERT(0 != decoder->private_);
549         FLAC__ASSERT(0 != decoder->protected_);
550
551         if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
552                 return true;
553
554         /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
555          * always call FLAC__MD5Final()
556          */
557         FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
558
559         if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
560                 free(decoder->private_->seek_table.data.seek_table.points);
561                 decoder->private_->seek_table.data.seek_table.points = 0;
562                 decoder->private_->has_seek_table = false;
563         }
564         FLAC__bitbuffer_free(decoder->private_->input);
565         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
566                 /* WATCHOUT:
567                  * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
568                  * output arrays have a buffer of up to 3 zeroes in front
569                  * (at negative indices) for alignment purposes; we use 4
570                  * to keep the data well-aligned.
571                  */
572                 if(0 != decoder->private_->output[i]) {
573                         free(decoder->private_->output[i]-4);
574                         decoder->private_->output[i] = 0;
575                 }
576                 if(0 != decoder->private_->residual_unaligned[i]) {
577                         free(decoder->private_->residual_unaligned[i]);
578                         decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
579                 }
580         }
581         decoder->private_->output_capacity = 0;
582         decoder->private_->output_channels = 0;
583
584         if(0 != decoder->private_->file && decoder->private_->file != stdin) {
585                 fclose(decoder->private_->file);
586                 decoder->private_->file = 0;
587         }
588
589 #ifdef OLD_STAT_WAY
590         if(0 != decoder->private_->filename) {
591                 free(decoder->private_->filename);
592                 decoder->private_->filename = 0;
593         }
594 #endif
595
596         if(decoder->private_->do_md5_checking) {
597                 if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
598                         md5_failed = true;
599         }
600         decoder->private_->is_seeking = false;
601
602         set_defaults_(decoder);
603
604         decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
605
606         return !md5_failed;
607 }
608
609 FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
610 {
611         FLAC__ASSERT(0 != decoder);
612         FLAC__ASSERT(0 != decoder->protected_);
613         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
614                 return false;
615         decoder->protected_->md5_checking = value;
616         return true;
617 }
618
619 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
620 {
621         FLAC__ASSERT(0 != decoder);
622         FLAC__ASSERT(0 != decoder->private_);
623         FLAC__ASSERT(0 != decoder->protected_);
624         FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
625         /* double protection */
626         if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
627                 return false;
628         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
629                 return false;
630         decoder->private_->metadata_filter[type] = true;
631         if(type == FLAC__METADATA_TYPE_APPLICATION)
632                 decoder->private_->metadata_filter_ids_count = 0;
633         return true;
634 }
635
636 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
637 {
638         FLAC__ASSERT(0 != decoder);
639         FLAC__ASSERT(0 != decoder->private_);
640         FLAC__ASSERT(0 != decoder->protected_);
641         FLAC__ASSERT(0 != id);
642         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
643                 return false;
644
645         if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
646                 return true;
647
648         FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
649
650         if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
651                 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2))) {
652                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
653                         return false;
654                 }
655                 decoder->private_->metadata_filter_ids_capacity *= 2;
656         }
657
658         memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
659         decoder->private_->metadata_filter_ids_count++;
660
661         return true;
662 }
663
664 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
665 {
666         unsigned i;
667         FLAC__ASSERT(0 != decoder);
668         FLAC__ASSERT(0 != decoder->private_);
669         FLAC__ASSERT(0 != decoder->protected_);
670         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
671                 return false;
672         for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
673                 decoder->private_->metadata_filter[i] = true;
674         decoder->private_->metadata_filter_ids_count = 0;
675         return true;
676 }
677
678 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
679 {
680         FLAC__ASSERT(0 != decoder);
681         FLAC__ASSERT(0 != decoder->private_);
682         FLAC__ASSERT(0 != decoder->protected_);
683         FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
684         /* double protection */
685         if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
686                 return false;
687         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
688                 return false;
689         decoder->private_->metadata_filter[type] = false;
690         if(type == FLAC__METADATA_TYPE_APPLICATION)
691                 decoder->private_->metadata_filter_ids_count = 0;
692         return true;
693 }
694
695 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
696 {
697         FLAC__ASSERT(0 != decoder);
698         FLAC__ASSERT(0 != decoder->private_);
699         FLAC__ASSERT(0 != decoder->protected_);
700         FLAC__ASSERT(0 != id);
701         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
702                 return false;
703
704         if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
705                 return true;
706
707         FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
708
709         if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
710                 if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)realloc(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity * 2))) {
711                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
712                         return false;
713                 }
714                 decoder->private_->metadata_filter_ids_capacity *= 2;
715         }
716
717         memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
718         decoder->private_->metadata_filter_ids_count++;
719
720         return true;
721 }
722
723 FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
724 {
725         FLAC__ASSERT(0 != decoder);
726         FLAC__ASSERT(0 != decoder->private_);
727         FLAC__ASSERT(0 != decoder->protected_);
728         if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
729                 return false;
730         memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
731         decoder->private_->metadata_filter_ids_count = 0;
732         return true;
733 }
734
735 FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
736 {
737         FLAC__ASSERT(0 != decoder);
738         FLAC__ASSERT(0 != decoder->protected_);
739         return decoder->protected_->state;
740 }
741
742 FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
743 {
744         return FLAC__StreamDecoderStateString[decoder->protected_->state];
745 }
746
747 FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
748 {
749         FLAC__ASSERT(0 != decoder);
750         FLAC__ASSERT(0 != decoder->protected_);
751         return decoder->protected_->md5_checking;
752 }
753
754 FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
755 {
756         FLAC__ASSERT(0 != decoder);
757         FLAC__ASSERT(0 != decoder->protected_);
758         return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
759 }
760
761 FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
762 {
763         FLAC__ASSERT(0 != decoder);
764         FLAC__ASSERT(0 != decoder->protected_);
765         return decoder->protected_->channels;
766 }
767
768 FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
769 {
770         FLAC__ASSERT(0 != decoder);
771         FLAC__ASSERT(0 != decoder->protected_);
772         return decoder->protected_->channel_assignment;
773 }
774
775 FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
776 {
777         FLAC__ASSERT(0 != decoder);
778         FLAC__ASSERT(0 != decoder->protected_);
779         return decoder->protected_->bits_per_sample;
780 }
781
782 FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
783 {
784         FLAC__ASSERT(0 != decoder);
785         FLAC__ASSERT(0 != decoder->protected_);
786         return decoder->protected_->sample_rate;
787 }
788
789 FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
790 {
791         FLAC__ASSERT(0 != decoder);
792         FLAC__ASSERT(0 != decoder->protected_);
793         return decoder->protected_->blocksize;
794 }
795
796 FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
797 {
798         FLAC__ASSERT(0 != decoder);
799         FLAC__ASSERT(0 != decoder->private_);
800         FLAC__ASSERT(0 != position);
801
802         if(0 == decoder->private_->tell_callback)
803                 return false;
804         if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
805                 return false;
806         FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
807         *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
808         return true;
809 }
810
811 FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
812 {
813         FLAC__ASSERT(0 != decoder);
814         FLAC__ASSERT(0 != decoder->private_);
815         FLAC__ASSERT(0 != decoder->protected_);
816
817         decoder->private_->samples_decoded = 0;
818         decoder->private_->do_md5_checking = false;
819
820         if(!FLAC__bitbuffer_clear(decoder->private_->input)) {
821                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
822                 return false;
823         }
824         decoder->private_->last_frame_number = 0;
825         decoder->private_->last_block_size = 0;
826         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
827
828         return true;
829 }
830
831 FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
832 {
833         FLAC__ASSERT(0 != decoder);
834         FLAC__ASSERT(0 != decoder->private_);
835         FLAC__ASSERT(0 != decoder->protected_);
836
837         if(!FLAC__stream_decoder_flush(decoder)) {
838                 /* above call sets the state for us */
839                 return false;
840         }
841
842         /* Rewind if necessary.  If FLAC__stream_decoder_init() is calling us,
843          * (internal_reset_hack) don't try to rewind since we are already at
844          * the beginning of the stream and don't want to fail if the input is
845          * not seekable.
846          */
847         if(!decoder->private_->internal_reset_hack) {
848                 if(decoder->private_->file == stdin)
849                         return false; /* can't rewind stdin, reset fails */
850                 if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
851                         return false; /* seekable and seek fails, reset fails */
852         }
853         else
854                 decoder->private_->internal_reset_hack = false;
855
856         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
857
858         decoder->private_->has_stream_info = false;
859         if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
860                 free(decoder->private_->seek_table.data.seek_table.points);
861                 decoder->private_->seek_table.data.seek_table.points = 0;
862                 decoder->private_->has_seek_table = false;
863         }
864         decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
865
866         /* We initialize the FLAC__MD5Context even though we may never use it.  This
867          * is because md5 checking may be turned on to start and then turned off if
868          * a seek occurs.  So we init the context here and finalize it in
869          * FLAC__seekable_stream_decoder_finish() to make sure things are always
870          * cleaned up properly.
871          */
872         FLAC__MD5Init(&decoder->private_->md5context);
873
874         decoder->private_->first_frame_offset = 0;
875         decoder->private_->unparseable_frame_count = 0;
876
877         return true;
878 }
879
880 FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
881 {
882         FLAC__bool got_a_frame;
883         FLAC__ASSERT(0 != decoder);
884         FLAC__ASSERT(0 != decoder->protected_);
885
886         while(1) {
887                 switch(decoder->protected_->state) {
888                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
889                                 if(!find_metadata_(decoder))
890                                         return false; /* above function sets the status for us */
891                                 break;
892                         case FLAC__STREAM_DECODER_READ_METADATA:
893                                 if(!read_metadata_(decoder))
894                                         return false; /* above function sets the status for us */
895                                 else
896                                         return true;
897                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
898                                 if(!frame_sync_(decoder))
899                                         return true; /* above function sets the status for us */
900                                 break;
901                         case FLAC__STREAM_DECODER_READ_FRAME:
902                                 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
903                                         return false; /* above function sets the status for us */
904                                 if(got_a_frame)
905                                         return true; /* above function sets the status for us */
906                                 break;
907                         case FLAC__STREAM_DECODER_END_OF_STREAM:
908                         case FLAC__STREAM_DECODER_ABORTED:
909                                 return true;
910                         default:
911                                 FLAC__ASSERT(0);
912                                 return false;
913                 }
914         }
915 }
916
917 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
918 {
919         FLAC__ASSERT(0 != decoder);
920         FLAC__ASSERT(0 != decoder->protected_);
921
922         while(1) {
923                 switch(decoder->protected_->state) {
924                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
925                                 if(!find_metadata_(decoder))
926                                         return false; /* above function sets the status for us */
927                                 break;
928                         case FLAC__STREAM_DECODER_READ_METADATA:
929                                 if(!read_metadata_(decoder))
930                                         return false; /* above function sets the status for us */
931                                 break;
932                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
933                         case FLAC__STREAM_DECODER_READ_FRAME:
934                         case FLAC__STREAM_DECODER_END_OF_STREAM:
935                         case FLAC__STREAM_DECODER_ABORTED:
936                                 return true;
937                         default:
938                                 FLAC__ASSERT(0);
939                                 return false;
940                 }
941         }
942 }
943
944 FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
945 {
946         FLAC__bool dummy;
947         FLAC__ASSERT(0 != decoder);
948         FLAC__ASSERT(0 != decoder->protected_);
949
950         while(1) {
951                 switch(decoder->protected_->state) {
952                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
953                                 if(!find_metadata_(decoder))
954                                         return false; /* above function sets the status for us */
955                                 break;
956                         case FLAC__STREAM_DECODER_READ_METADATA:
957                                 if(!read_metadata_(decoder))
958                                         return false; /* above function sets the status for us */
959                                 break;
960                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
961                                 if(!frame_sync_(decoder))
962                                         return true; /* above function sets the status for us */
963                                 break;
964                         case FLAC__STREAM_DECODER_READ_FRAME:
965                                 if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
966                                         return false; /* above function sets the status for us */
967                                 break;
968                         case FLAC__STREAM_DECODER_END_OF_STREAM:
969                         case FLAC__STREAM_DECODER_ABORTED:
970                                 return true;
971                         default:
972                                 FLAC__ASSERT(0);
973                                 return false;
974                 }
975         }
976 }
977
978 FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
979 {
980         FLAC__bool got_a_frame;
981         FLAC__ASSERT(0 != decoder);
982         FLAC__ASSERT(0 != decoder->protected_);
983
984         while(1) {
985                 switch(decoder->protected_->state) {
986                         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
987                         case FLAC__STREAM_DECODER_READ_METADATA:
988                                 return false; /* above function sets the status for us */
989                         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
990                                 if(!frame_sync_(decoder))
991                                         return true; /* above function sets the status for us */
992                                 break;
993                         case FLAC__STREAM_DECODER_READ_FRAME:
994                                 if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
995                                         return false; /* above function sets the status for us */
996                                 if(got_a_frame)
997                                         return true; /* above function sets the status for us */
998                                 break;
999                         case FLAC__STREAM_DECODER_END_OF_STREAM:
1000                         case FLAC__STREAM_DECODER_ABORTED:
1001                                 return true;
1002                         default:
1003                                 FLAC__ASSERT(0);
1004                                 return false;
1005                 }
1006         }
1007 }
1008
1009 FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
1010 {
1011         FLAC__uint64 length;
1012
1013         FLAC__ASSERT(0 != decoder);
1014
1015         if(
1016                 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
1017                 decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
1018                 decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
1019                 decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
1020                 decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
1021         )
1022                 return false;
1023
1024         if(0 == decoder->private_->seek_callback)
1025                 return false;
1026
1027         FLAC__ASSERT(decoder->private_->seek_callback);
1028         FLAC__ASSERT(decoder->private_->tell_callback);
1029         FLAC__ASSERT(decoder->private_->length_callback);
1030         FLAC__ASSERT(decoder->private_->eof_callback);
1031
1032         if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
1033                 return false;
1034
1035         decoder->private_->is_seeking = true;
1036
1037         /* turn off md5 checking if a seek is attempted */
1038         decoder->private_->do_md5_checking = false;
1039
1040         /* get the file length (currently our algorithm needs to know the length so it's also an error to get FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED) */
1041         if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
1042                 decoder->private_->is_seeking = false;
1043                 return false;
1044         }
1045         /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
1046         if(
1047                 decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
1048                 decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
1049         ) {
1050                 if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
1051                         /* above call sets the state for us */
1052                         decoder->private_->is_seeking = false;
1053                         return false;
1054                 }
1055                 /* check this again in case we didn't know total_samples the first time */
1056                 if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
1057                         decoder->private_->is_seeking = false;
1058                         return false;
1059                 }
1060         }
1061
1062         {
1063                 FLAC__bool ok = seek_to_absolute_sample_(decoder, length, sample);
1064                 decoder->private_->is_seeking = false;
1065                 return ok;
1066         }
1067 }
1068
1069 /***********************************************************************
1070  *
1071  * Protected class methods
1072  *
1073  ***********************************************************************/
1074
1075 unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
1076 {
1077         FLAC__ASSERT(0 != decoder);
1078         return FLAC__bitbuffer_get_input_bytes_unconsumed(decoder->private_->input);
1079 }
1080
1081 /***********************************************************************
1082  *
1083  * Private class methods
1084  *
1085  ***********************************************************************/
1086
1087 void set_defaults_(FLAC__StreamDecoder *decoder)
1088 {
1089         decoder->private_->read_callback = 0;
1090         decoder->private_->seek_callback = 0;
1091         decoder->private_->tell_callback = 0;
1092         decoder->private_->length_callback = 0;
1093         decoder->private_->eof_callback = 0;
1094         decoder->private_->write_callback = 0;
1095         decoder->private_->metadata_callback = 0;
1096         decoder->private_->error_callback = 0;
1097         decoder->private_->client_data = 0;
1098 #ifdef OLD_STAT_WAY
1099         decoder->private_->filename = 0;
1100 #endif
1101
1102         memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
1103         decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
1104         decoder->private_->metadata_filter_ids_count = 0;
1105
1106         decoder->protected_->md5_checking = false;
1107 }
1108
1109 /*
1110  * This will forcibly set stdin to binary mode (for OSes that require it)
1111  */
1112 FILE *get_binary_stdin_()
1113 {
1114         /* if something breaks here it is probably due to the presence or
1115          * absence of an underscore before the identifiers 'setmode',
1116          * 'fileno', and/or 'O_BINARY'; check your system header files.
1117          */
1118 #if defined _MSC_VER || defined __MINGW32__
1119         _setmode(_fileno(stdin), _O_BINARY);
1120 #elif defined __CYGWIN__ || defined __EMX__
1121         /* almost certainly not needed for any modern Cygwin, but let's be safe... */
1122         setmode(_fileno(stdin), _O_BINARY);
1123 #endif
1124
1125         return stdin;
1126 }
1127
1128 FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
1129 {
1130         unsigned i;
1131         FLAC__int32 *tmp;
1132
1133         if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
1134                 return true;
1135
1136         /* simply using realloc() is not practical because the number of channels may change mid-stream */
1137
1138         for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
1139                 if(0 != decoder->private_->output[i]) {
1140                         free(decoder->private_->output[i]-4);
1141                         decoder->private_->output[i] = 0;
1142                 }
1143                 if(0 != decoder->private_->residual_unaligned[i]) {
1144                         free(decoder->private_->residual_unaligned[i]);
1145                         decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
1146                 }
1147         }
1148
1149         for(i = 0; i < channels; i++) {
1150                 /* WATCHOUT:
1151                  * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
1152                  * output arrays have a buffer of up to 3 zeroes in front
1153                  * (at negative indices) for alignment purposes; we use 4
1154                  * to keep the data well-aligned.
1155                  */
1156                 tmp = (FLAC__int32*)malloc(sizeof(FLAC__int32)*(size+4));
1157                 if(tmp == 0) {
1158                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1159                         return false;
1160                 }
1161                 memset(tmp, 0, sizeof(FLAC__int32)*4);
1162                 decoder->private_->output[i] = tmp + 4;
1163
1164                 /* WATCHOUT:
1165                  * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
1166                  */
1167                 if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
1168                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1169                         return false;
1170                 }
1171         }
1172
1173         decoder->private_->output_capacity = size;
1174         decoder->private_->output_channels = channels;
1175
1176         return true;
1177 }
1178
1179 FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
1180 {
1181         unsigned i;
1182
1183         FLAC__ASSERT(0 != decoder);
1184         FLAC__ASSERT(0 != decoder->private_);
1185
1186         for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
1187                 if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
1188                         return true;
1189
1190         return false;
1191 }
1192
1193 FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
1194 {
1195         FLAC__uint32 x;
1196         unsigned i, id;
1197         FLAC__bool first = true;
1198
1199         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1200
1201         for(i = id = 0; i < 4; ) {
1202                 if(decoder->private_->cached) {
1203                         x = (FLAC__uint32)decoder->private_->lookahead;
1204                         decoder->private_->cached = false;
1205                 }
1206                 else {
1207                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1208                                 return false; /* read_callback_ sets the state for us */
1209                 }
1210                 if(x == FLAC__STREAM_SYNC_STRING[i]) {
1211                         first = true;
1212                         i++;
1213                         id = 0;
1214                         continue;
1215                 }
1216                 if(x == ID3V2_TAG_[id]) {
1217                         id++;
1218                         i = 0;
1219                         if(id == 3) {
1220                                 if(!skip_id3v2_tag_(decoder))
1221                                         return false; /* skip_id3v2_tag_ sets the state for us */
1222                         }
1223                         continue;
1224                 }
1225                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1226                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1227                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1228                                 return false; /* read_callback_ sets the state for us */
1229
1230                         /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
1231                         /* else we have to check if the second byte is the end of a sync code */
1232                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1233                                 decoder->private_->lookahead = (FLAC__byte)x;
1234                                 decoder->private_->cached = true;
1235                         }
1236                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1237                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1238                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1239                                 return true;
1240                         }
1241                 }
1242                 i = 0;
1243                 if(first) {
1244                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1245                         first = false;
1246                 }
1247         }
1248
1249         decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
1250         return true;
1251 }
1252
1253 FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
1254 {
1255         FLAC__bool is_last;
1256         FLAC__uint32 i, x, type, length;
1257
1258         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1259
1260         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN, read_callback_, decoder))
1261                 return false; /* read_callback_ sets the state for us */
1262         is_last = x? true : false;
1263
1264         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN, read_callback_, decoder))
1265                 return false; /* read_callback_ sets the state for us */
1266
1267         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN, read_callback_, decoder))
1268                 return false; /* read_callback_ sets the state for us */
1269
1270         if(type == FLAC__METADATA_TYPE_STREAMINFO) {
1271                 if(!read_metadata_streaminfo_(decoder, is_last, length))
1272                         return false;
1273
1274                 decoder->private_->has_stream_info = true;
1275                 if(0 == memcmp(decoder->private_->stream_info.data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
1276                         decoder->private_->do_md5_checking = false;
1277                 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
1278                         decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
1279         }
1280         else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
1281                 if(!read_metadata_seektable_(decoder, is_last, length))
1282                         return false;
1283
1284                 decoder->private_->has_seek_table = true;
1285                 if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
1286                         decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
1287         }
1288         else {
1289                 FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
1290                 unsigned real_length = length;
1291                 FLAC__StreamMetadata block;
1292
1293                 block.is_last = is_last;
1294                 block.type = (FLAC__MetadataType)type;
1295                 block.length = length;
1296
1297                 if(type == FLAC__METADATA_TYPE_APPLICATION) {
1298                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8, read_callback_, decoder))
1299                                 return false; /* read_callback_ sets the state for us */
1300
1301                         real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
1302
1303                         if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
1304                                 skip_it = !skip_it;
1305                 }
1306
1307                 if(skip_it) {
1308                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
1309                                 return false; /* read_callback_ sets the state for us */
1310                 }
1311                 else {
1312                         switch(type) {
1313                                 case FLAC__METADATA_TYPE_PADDING:
1314                                         /* skip the padding bytes */
1315                                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, real_length, read_callback_, decoder))
1316                                                 return false; /* read_callback_ sets the state for us */
1317                                         break;
1318                                 case FLAC__METADATA_TYPE_APPLICATION:
1319                                         /* remember, we read the ID already */
1320                                         if(real_length > 0) {
1321                                                 if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
1322                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1323                                                         return false;
1324                                                 }
1325                                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length, read_callback_, decoder))
1326                                                         return false; /* read_callback_ sets the state for us */
1327                                         }
1328                                         else
1329                                                 block.data.application.data = 0;
1330                                         break;
1331                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1332                                         if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
1333                                                 return false;
1334                                         break;
1335                                 case FLAC__METADATA_TYPE_CUESHEET:
1336                                         if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
1337                                                 return false;
1338                                         break;
1339                                 case FLAC__METADATA_TYPE_STREAMINFO:
1340                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1341                                         FLAC__ASSERT(0);
1342                                         break;
1343                                 default:
1344                                         if(real_length > 0) {
1345                                                 if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
1346                                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1347                                                         return false;
1348                                                 }
1349                                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length, read_callback_, decoder))
1350                                                         return false; /* read_callback_ sets the state for us */
1351                                         }
1352                                         else
1353                                                 block.data.unknown.data = 0;
1354                                         break;
1355                         }
1356                         if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
1357                                 decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1358
1359                         /* now we have to free any malloc'ed data in the block */
1360                         switch(type) {
1361                                 case FLAC__METADATA_TYPE_PADDING:
1362                                         break;
1363                                 case FLAC__METADATA_TYPE_APPLICATION:
1364                                         if(0 != block.data.application.data)
1365                                                 free(block.data.application.data);
1366                                         break;
1367                                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1368                                         if(0 != block.data.vorbis_comment.vendor_string.entry)
1369                                                 free(block.data.vorbis_comment.vendor_string.entry);
1370                                         if(block.data.vorbis_comment.num_comments > 0)
1371                                                 for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
1372                                                         if(0 != block.data.vorbis_comment.comments[i].entry)
1373                                                                 free(block.data.vorbis_comment.comments[i].entry);
1374                                         if(0 != block.data.vorbis_comment.comments)
1375                                                 free(block.data.vorbis_comment.comments);
1376                                         break;
1377                                 case FLAC__METADATA_TYPE_CUESHEET:
1378                                         if(block.data.cue_sheet.num_tracks > 0)
1379                                                 for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
1380                                                         if(0 != block.data.cue_sheet.tracks[i].indices)
1381                                                                 free(block.data.cue_sheet.tracks[i].indices);
1382                                         if(0 != block.data.cue_sheet.tracks)
1383                                                 free(block.data.cue_sheet.tracks);
1384                                         break;
1385                                 case FLAC__METADATA_TYPE_STREAMINFO:
1386                                 case FLAC__METADATA_TYPE_SEEKTABLE:
1387                                         FLAC__ASSERT(0);
1388                                 default:
1389                                         if(0 != block.data.unknown.data)
1390                                                 free(block.data.unknown.data);
1391                                         break;
1392                         }
1393                 }
1394         }
1395
1396         if(is_last) {
1397                 /* if this fails, it's OK, it's just a hint for the seek routine */
1398                 if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
1399                         decoder->private_->first_frame_offset = 0;
1400                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1401         }
1402
1403         return true;
1404 }
1405
1406 FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1407 {
1408         FLAC__uint32 x;
1409         unsigned bits, used_bits = 0;
1410
1411         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1412
1413         decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
1414         decoder->private_->stream_info.is_last = is_last;
1415         decoder->private_->stream_info.length = length;
1416
1417         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1418         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, bits, read_callback_, decoder))
1419                 return false; /* read_callback_ sets the state for us */
1420         decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1421         used_bits += bits;
1422
1423         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1424         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN, read_callback_, decoder))
1425                 return false; /* read_callback_ sets the state for us */
1426         decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1427         used_bits += bits;
1428
1429         bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1430         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN, read_callback_, decoder))
1431                 return false; /* read_callback_ sets the state for us */
1432         decoder->private_->stream_info.data.stream_info.min_framesize = x;
1433         used_bits += bits;
1434
1435         bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1436         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN, read_callback_, decoder))
1437                 return false; /* read_callback_ sets the state for us */
1438         decoder->private_->stream_info.data.stream_info.max_framesize = x;
1439         used_bits += bits;
1440
1441         bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1442         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN, read_callback_, decoder))
1443                 return false; /* read_callback_ sets the state for us */
1444         decoder->private_->stream_info.data.stream_info.sample_rate = x;
1445         used_bits += bits;
1446
1447         bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1448         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN, read_callback_, decoder))
1449                 return false; /* read_callback_ sets the state for us */
1450         decoder->private_->stream_info.data.stream_info.channels = x+1;
1451         used_bits += bits;
1452
1453         bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1454         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN, read_callback_, decoder))
1455                 return false; /* read_callback_ sets the state for us */
1456         decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1457         used_bits += bits;
1458
1459         bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1460         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN, read_callback_, decoder))
1461                 return false; /* read_callback_ sets the state for us */
1462         used_bits += bits;
1463
1464         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16, read_callback_, decoder))
1465                 return false; /* read_callback_ sets the state for us */
1466         used_bits += 16*8;
1467
1468         /* skip the rest of the block */
1469         FLAC__ASSERT(used_bits % 8 == 0);
1470         length -= (used_bits / 8);
1471         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1472                 return false; /* read_callback_ sets the state for us */
1473
1474         return true;
1475 }
1476
1477 FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1478 {
1479         FLAC__uint32 i, x;
1480         FLAC__uint64 xx;
1481
1482         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1483
1484         decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1485         decoder->private_->seek_table.is_last = is_last;
1486         decoder->private_->seek_table.length = length;
1487
1488         decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1489
1490         /* use realloc since we may pass through here several times (e.g. after seeking) */
1491         if(0 == (decoder->private_->seek_table.data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)realloc(decoder->private_->seek_table.data.seek_table.points, decoder->private_->seek_table.data.seek_table.num_points * sizeof(FLAC__StreamMetadata_SeekPoint)))) {
1492                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1493                 return false;
1494         }
1495         for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1496                 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN, read_callback_, decoder))
1497                         return false; /* read_callback_ sets the state for us */
1498                 decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1499
1500                 if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN, read_callback_, decoder))
1501                         return false; /* read_callback_ sets the state for us */
1502                 decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1503
1504                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN, read_callback_, decoder))
1505                         return false; /* read_callback_ sets the state for us */
1506                 decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1507         }
1508         length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1509         /* if there is a partial point left, skip over it */
1510         if(length > 0) {
1511                 /*@@@ do an error_callback() here?  there's an argument for either way */
1512                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, length, read_callback_, decoder))
1513                         return false; /* read_callback_ sets the state for us */
1514         }
1515
1516         return true;
1517 }
1518
1519 FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1520 {
1521         FLAC__uint32 i;
1522
1523         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1524
1525         /* read vendor string */
1526         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1527         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length, read_callback_, decoder))
1528                 return false; /* read_callback_ sets the state for us */
1529         if(obj->vendor_string.length > 0) {
1530                 if(0 == (obj->vendor_string.entry = (FLAC__byte*)malloc(obj->vendor_string.length+1))) {
1531                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1532                         return false;
1533                 }
1534                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length, read_callback_, decoder))
1535                         return false; /* read_callback_ sets the state for us */
1536                 obj->vendor_string.entry[obj->vendor_string.length] = '\0';
1537         }
1538         else
1539                 obj->vendor_string.entry = 0;
1540
1541         /* read num comments */
1542         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1543         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->num_comments, read_callback_, decoder))
1544                 return false; /* read_callback_ sets the state for us */
1545
1546         /* read comments */
1547         if(obj->num_comments > 0) {
1548                 if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)malloc(obj->num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1549                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1550                         return false;
1551                 }
1552                 for(i = 0; i < obj->num_comments; i++) {
1553                         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1554                         if(!FLAC__bitbuffer_read_raw_uint32_little_endian(decoder->private_->input, &obj->comments[i].length, read_callback_, decoder))
1555                                 return false; /* read_callback_ sets the state for us */
1556                         if(obj->comments[i].length > 0) {
1557                                 if(0 == (obj->comments[i].entry = (FLAC__byte*)malloc(obj->comments[i].length+1))) {
1558                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1559                                         return false;
1560                                 }
1561                                 if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length, read_callback_, decoder))
1562                                         return false; /* read_callback_ sets the state for us */
1563                                 obj->comments[i].entry[obj->comments[i].length] = '\0';
1564                         }
1565                         else
1566                                 obj->comments[i].entry = 0;
1567                 }
1568         }
1569         else {
1570                 obj->comments = 0;
1571         }
1572
1573         return true;
1574 }
1575
1576 FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1577 {
1578         FLAC__uint32 i, j, x;
1579
1580         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1581
1582         memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1583
1584         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1585         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8, read_callback_, decoder))
1586                 return false; /* read_callback_ sets the state for us */
1587
1588         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN, read_callback_, decoder))
1589                 return false; /* read_callback_ sets the state for us */
1590
1591         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN, read_callback_, decoder))
1592                 return false; /* read_callback_ sets the state for us */
1593         obj->is_cd = x? true : false;
1594
1595         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN, read_callback_, decoder))
1596                 return false; /* read_callback_ sets the state for us */
1597
1598         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN, read_callback_, decoder))
1599                 return false; /* read_callback_ sets the state for us */
1600         obj->num_tracks = x;
1601
1602         if(obj->num_tracks > 0) {
1603                 if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1604                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1605                         return false;
1606                 }
1607                 for(i = 0; i < obj->num_tracks; i++) {
1608                         FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1609                         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN, read_callback_, decoder))
1610                                 return false; /* read_callback_ sets the state for us */
1611
1612                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN, read_callback_, decoder))
1613                                 return false; /* read_callback_ sets the state for us */
1614                         track->number = (FLAC__byte)x;
1615
1616                         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1617                         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8, read_callback_, decoder))
1618                                 return false; /* read_callback_ sets the state for us */
1619
1620                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN, read_callback_, decoder))
1621                                 return false; /* read_callback_ sets the state for us */
1622                         track->type = x;
1623
1624                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN, read_callback_, decoder))
1625                                 return false; /* read_callback_ sets the state for us */
1626                         track->pre_emphasis = x;
1627
1628                         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN, read_callback_, decoder))
1629                                 return false; /* read_callback_ sets the state for us */
1630
1631                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN, read_callback_, decoder))
1632                                 return false; /* read_callback_ sets the state for us */
1633                         track->num_indices = (FLAC__byte)x;
1634
1635                         if(track->num_indices > 0) {
1636                                 if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1637                                         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1638                                         return false;
1639                                 }
1640                                 for(j = 0; j < track->num_indices; j++) {
1641                                         FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1642                                         if(!FLAC__bitbuffer_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN, read_callback_, decoder))
1643                                                 return false; /* read_callback_ sets the state for us */
1644
1645                                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN, read_callback_, decoder))
1646                                                 return false; /* read_callback_ sets the state for us */
1647                                         index->number = (FLAC__byte)x;
1648
1649                                         if(!FLAC__bitbuffer_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN, read_callback_, decoder))
1650                                                 return false; /* read_callback_ sets the state for us */
1651                                 }
1652                         }
1653                 }
1654         }
1655
1656         return true;
1657 }
1658
1659 FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1660 {
1661         FLAC__uint32 x;
1662         unsigned i, skip;
1663
1664         /* skip the version and flags bytes */
1665         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 24, read_callback_, decoder))
1666                 return false; /* read_callback_ sets the state for us */
1667         /* get the size (in bytes) to skip */
1668         skip = 0;
1669         for(i = 0; i < 4; i++) {
1670                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1671                         return false; /* read_callback_ sets the state for us */
1672                 skip <<= 7;
1673                 skip |= (x & 0x7f);
1674         }
1675         /* skip the rest of the tag */
1676         if(!FLAC__bitbuffer_read_byte_block_aligned_no_crc(decoder->private_->input, 0, skip, read_callback_, decoder))
1677                 return false; /* read_callback_ sets the state for us */
1678         return true;
1679 }
1680
1681 FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1682 {
1683         FLAC__uint32 x;
1684         FLAC__bool first = true;
1685
1686         /* If we know the total number of samples in the stream, stop if we've read that many. */
1687         /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1688         if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
1689                 if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
1690                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1691                         return true;
1692                 }
1693         }
1694
1695         /* make sure we're byte aligned */
1696         if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
1697                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
1698                         return false; /* read_callback_ sets the state for us */
1699         }
1700
1701         while(1) {
1702                 if(decoder->private_->cached) {
1703                         x = (FLAC__uint32)decoder->private_->lookahead;
1704                         decoder->private_->cached = false;
1705                 }
1706                 else {
1707                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1708                                 return false; /* read_callback_ sets the state for us */
1709                 }
1710                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1711                         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1712                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1713                                 return false; /* read_callback_ sets the state for us */
1714
1715                         /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
1716                         /* else we have to check if the second byte is the end of a sync code */
1717                         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1718                                 decoder->private_->lookahead = (FLAC__byte)x;
1719                                 decoder->private_->cached = true;
1720                         }
1721                         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1722                                 decoder->private_->header_warmup[1] = (FLAC__byte)x;
1723                                 decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1724                                 return true;
1725                         }
1726                 }
1727                 if(first) {
1728                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1729                         first = false;
1730                 }
1731         }
1732
1733         return true;
1734 }
1735
1736 FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
1737 {
1738         unsigned channel;
1739         unsigned i;
1740         FLAC__int32 mid, side, left, right;
1741         FLAC__uint16 frame_crc; /* the one we calculate from the input stream */
1742         FLAC__uint32 x;
1743
1744         *got_a_frame = false;
1745
1746         /* init the CRC */
1747         frame_crc = 0;
1748         FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
1749         FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
1750         FLAC__bitbuffer_reset_read_crc16(decoder->private_->input, frame_crc);
1751
1752         if(!read_frame_header_(decoder))
1753                 return false;
1754         if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
1755                 return true;
1756         if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
1757                 return false;
1758         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1759                 /*
1760                  * first figure the correct bits-per-sample of the subframe
1761                  */
1762                 unsigned bps = decoder->private_->frame.header.bits_per_sample;
1763                 switch(decoder->private_->frame.header.channel_assignment) {
1764                         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1765                                 /* no adjustment needed */
1766                                 break;
1767                         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1768                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1769                                 if(channel == 1)
1770                                         bps++;
1771                                 break;
1772                         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1773                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1774                                 if(channel == 0)
1775                                         bps++;
1776                                 break;
1777                         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1778                                 FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1779                                 if(channel == 1)
1780                                         bps++;
1781                                 break;
1782                         default:
1783                                 FLAC__ASSERT(0);
1784                 }
1785                 /*
1786                  * now read it
1787                  */
1788                 if(!read_subframe_(decoder, channel, bps, do_full_decode))
1789                         return false;
1790                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
1791                         return true;
1792         }
1793         if(!read_zero_padding_(decoder))
1794                 return false;
1795
1796         /*
1797          * Read the frame CRC-16 from the footer and check
1798          */
1799         frame_crc = FLAC__bitbuffer_get_read_crc16(decoder->private_->input);
1800         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN, read_callback_, decoder))
1801                 return false; /* read_callback_ sets the state for us */
1802         if(frame_crc == (FLAC__uint16)x) {
1803                 if(do_full_decode) {
1804                         /* Undo any special channel coding */
1805                         switch(decoder->private_->frame.header.channel_assignment) {
1806                                 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
1807                                         /* do nothing */
1808                                         break;
1809                                 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
1810                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1811                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1812                                                 decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
1813                                         break;
1814                                 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
1815                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1816                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
1817                                                 decoder->private_->output[0][i] += decoder->private_->output[1][i];
1818                                         break;
1819                                 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
1820                                         FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
1821                                         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
1822                                                 mid = decoder->private_->output[0][i];
1823                                                 side = decoder->private_->output[1][i];
1824                                                 mid <<= 1;
1825                                                 if(side & 1) /* i.e. if 'side' is odd... */
1826                                                         mid++;
1827                                                 left = mid + side;
1828                                                 right = mid - side;
1829                                                 decoder->private_->output[0][i] = left >> 1;
1830                                                 decoder->private_->output[1][i] = right >> 1;
1831                                         }
1832                                         break;
1833                                 default:
1834                                         FLAC__ASSERT(0);
1835                                         break;
1836                         }
1837                 }
1838         }
1839         else {
1840                 /* Bad frame, emit error and zero the output signal */
1841                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
1842                 if(do_full_decode) {
1843                         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
1844                                 memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
1845                         }
1846                 }
1847         }
1848
1849         *got_a_frame = true;
1850
1851         /* put the latest values into the public section of the decoder instance */
1852         decoder->protected_->channels = decoder->private_->frame.header.channels;
1853         decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
1854         decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
1855         decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
1856         decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
1857
1858         FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1859         decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
1860
1861         /* write it */
1862         if(do_full_decode) {
1863                 if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
1864                         return false;
1865         }
1866
1867         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1868         return true;
1869 }
1870
1871 FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
1872 {
1873         FLAC__uint32 x;
1874         FLAC__uint64 xx;
1875         unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
1876         FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
1877         unsigned raw_header_len;
1878         FLAC__bool is_unparseable = false;
1879         const FLAC__bool is_known_variable_blocksize_stream = (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize);
1880         const FLAC__bool is_known_fixed_blocksize_stream = (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize);
1881
1882         FLAC__ASSERT(FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input));
1883
1884         /* init the raw header with the saved bits from synchronization */
1885         raw_header[0] = decoder->private_->header_warmup[0];
1886         raw_header[1] = decoder->private_->header_warmup[1];
1887         raw_header_len = 2;
1888
1889         /*
1890          * check to make sure that the reserved bits are 0
1891          */
1892         if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
1893                 is_unparseable = true;
1894         }
1895
1896         /*
1897          * Note that along the way as we read the header, we look for a sync
1898          * code inside.  If we find one it would indicate that our original
1899          * sync was bad since there cannot be a sync code in a valid header.
1900          */
1901
1902         /*
1903          * read in the raw header as bytes so we can CRC it, and parse it on the way
1904          */
1905         for(i = 0; i < 2; i++) {
1906                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
1907                         return false; /* read_callback_ sets the state for us */
1908                 if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1909                         /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
1910                         decoder->private_->lookahead = (FLAC__byte)x;
1911                         decoder->private_->cached = true;
1912                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
1913                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1914                         return true;
1915                 }
1916                 raw_header[raw_header_len++] = (FLAC__byte)x;
1917         }
1918
1919         switch(x = raw_header[2] >> 4) {
1920                 case 0:
1921                         if(is_known_fixed_blocksize_stream)
1922                                 decoder->private_->frame.header.blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
1923                         else
1924                                 is_unparseable = true;
1925                         break;
1926                 case 1:
1927                         decoder->private_->frame.header.blocksize = 192;
1928                         break;
1929                 case 2:
1930                 case 3:
1931                 case 4:
1932                 case 5:
1933                         decoder->private_->frame.header.blocksize = 576 << (x-2);
1934                         break;
1935                 case 6:
1936                 case 7:
1937                         blocksize_hint = x;
1938                         break;
1939                 case 8:
1940                 case 9:
1941                 case 10:
1942                 case 11:
1943                 case 12:
1944                 case 13:
1945                 case 14:
1946                 case 15:
1947                         decoder->private_->frame.header.blocksize = 256 << (x-8);
1948                         break;
1949                 default:
1950                         FLAC__ASSERT(0);
1951                         break;
1952         }
1953
1954         switch(x = raw_header[2] & 0x0f) {
1955                 case 0:
1956                         if(decoder->private_->has_stream_info)
1957                                 decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
1958                         else
1959                                 is_unparseable = true;
1960                         break;
1961                 case 1:
1962                 case 2:
1963                 case 3:
1964                         is_unparseable = true;
1965                         break;
1966                 case 4:
1967                         decoder->private_->frame.header.sample_rate = 8000;
1968                         break;
1969                 case 5:
1970                         decoder->private_->frame.header.sample_rate = 16000;
1971                         break;
1972                 case 6:
1973                         decoder->private_->frame.header.sample_rate = 22050;
1974                         break;
1975                 case 7:
1976                         decoder->private_->frame.header.sample_rate = 24000;
1977                         break;
1978                 case 8:
1979                         decoder->private_->frame.header.sample_rate = 32000;
1980                         break;
1981                 case 9:
1982                         decoder->private_->frame.header.sample_rate = 44100;
1983                         break;
1984                 case 10:
1985                         decoder->private_->frame.header.sample_rate = 48000;
1986                         break;
1987                 case 11:
1988                         decoder->private_->frame.header.sample_rate = 96000;
1989                         break;
1990                 case 12:
1991                 case 13:
1992                 case 14:
1993                         sample_rate_hint = x;
1994                         break;
1995                 case 15:
1996                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
1997                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1998                         return true;
1999                 default:
2000                         FLAC__ASSERT(0);
2001         }
2002
2003         x = (unsigned)(raw_header[3] >> 4);
2004         if(x & 8) {
2005                 decoder->private_->frame.header.channels = 2;
2006                 switch(x & 7) {
2007                         case 0:
2008                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2009                                 break;
2010                         case 1:
2011                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2012                                 break;
2013                         case 2:
2014                                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2015                                 break;
2016                         default:
2017                                 is_unparseable = true;
2018                                 break;
2019                 }
2020         }
2021         else {
2022                 decoder->private_->frame.header.channels = (unsigned)x + 1;
2023                 decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2024         }
2025
2026         switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2027                 case 0:
2028                         if(decoder->private_->has_stream_info)
2029                                 decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2030                         else
2031                                 is_unparseable = true;
2032                         break;
2033                 case 1:
2034                         decoder->private_->frame.header.bits_per_sample = 8;
2035                         break;
2036                 case 2:
2037                         decoder->private_->frame.header.bits_per_sample = 12;
2038                         break;
2039                 case 4:
2040                         decoder->private_->frame.header.bits_per_sample = 16;
2041                         break;
2042                 case 5:
2043                         decoder->private_->frame.header.bits_per_sample = 20;
2044                         break;
2045                 case 6:
2046                         decoder->private_->frame.header.bits_per_sample = 24;
2047                         break;
2048                 case 3:
2049                 case 7:
2050                         is_unparseable = true;
2051                         break;
2052                 default:
2053                         FLAC__ASSERT(0);
2054                         break;
2055         }
2056
2057         if(raw_header[3] & 0x01) { /* this should be a zero padding bit */
2058                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2059                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2060                 return true;
2061         }
2062
2063         /*
2064          * Now we get to the regrettable consequences of not knowing for sure
2065          * whether we got a frame number or a sample number.  There are no
2066          * encoders that do variable-blocksize encoding so unless we know from
2067          * the STREAMINFO that it is variable-blocksize we will assume it is
2068          * fixed-blocksize.  The trouble comes when we have no STREAMINFO; again
2069          * we will guess that is fixed-blocksize.  Where this can go wrong: 1) a
2070          * variable-blocksize stream with no STREAMINFO; 2) a fixed-blocksize
2071          * stream that was edited such that one or more frames before or
2072          * including this one do not have the same number of samples as the
2073          * STREAMINFO's min and max blocksize.
2074          */
2075         if(is_known_variable_blocksize_stream) {
2076                 if(blocksize_hint) {
2077                         if(!FLAC__bitbuffer_read_utf8_uint64(decoder->private_->input, &xx, read_callback_, decoder, raw_header, &raw_header_len))
2078                                 return false; /* read_callback_ sets the state for us */
2079                         if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
2080                                 decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2081                                 decoder->private_->cached = true;
2082                                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2083                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2084                                 return true;
2085                         }
2086                         decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2087                         decoder->private_->frame.header.number.sample_number = xx;
2088                 }
2089                 else
2090                         is_unparseable = true;
2091         }
2092         else {
2093                 if(!FLAC__bitbuffer_read_utf8_uint32(decoder->private_->input, &x, read_callback_, decoder, raw_header, &raw_header_len))
2094                         return false; /* read_callback_ sets the state for us */
2095                 if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
2096                         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2097                         decoder->private_->cached = true;
2098                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2099                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2100                         return true;
2101                 }
2102                 decoder->private_->last_frame_number = x;
2103                 decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2104                 if(decoder->private_->has_stream_info) {
2105                         FLAC__ASSERT(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize);
2106                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
2107                         decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2108                 }
2109                 else if(blocksize_hint) {
2110                         if(decoder->private_->last_block_size)
2111                                 decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->last_block_size * (FLAC__uint64)x;
2112                         else
2113                                 is_unparseable = true;
2114                 }
2115                 else {
2116                         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
2117                         decoder->private_->last_block_size = decoder->private_->frame.header.blocksize;
2118                 }
2119         }
2120
2121         if(blocksize_hint) {
2122                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2123                         return false; /* read_callback_ sets the state for us */
2124                 raw_header[raw_header_len++] = (FLAC__byte)x;
2125                 if(blocksize_hint == 7) {
2126                         FLAC__uint32 _x;
2127                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
2128                                 return false; /* read_callback_ sets the state for us */
2129                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2130                         x = (x << 8) | _x;
2131                 }
2132                 decoder->private_->frame.header.blocksize = x+1;
2133         }
2134
2135         if(sample_rate_hint) {
2136                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2137                         return false; /* read_callback_ sets the state for us */
2138                 raw_header[raw_header_len++] = (FLAC__byte)x;
2139                 if(sample_rate_hint != 12) {
2140                         FLAC__uint32 _x;
2141                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &_x, 8, read_callback_, decoder))
2142                                 return false; /* read_callback_ sets the state for us */
2143                         raw_header[raw_header_len++] = (FLAC__byte)_x;
2144                         x = (x << 8) | _x;
2145                 }
2146                 if(sample_rate_hint == 12)
2147                         decoder->private_->frame.header.sample_rate = x*1000;
2148                 else if(sample_rate_hint == 13)
2149                         decoder->private_->frame.header.sample_rate = x;
2150                 else
2151                         decoder->private_->frame.header.sample_rate = x*10;
2152         }
2153
2154         /* read the CRC-8 byte */
2155         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder))
2156                 return false; /* read_callback_ sets the state for us */
2157         crc8 = (FLAC__byte)x;
2158
2159         if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
2160                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2161                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2162                 return true;
2163         }
2164
2165         if(is_unparseable) {
2166                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2167                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2168                 return true;
2169         }
2170
2171         return true;
2172 }
2173
2174 FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2175 {
2176         FLAC__uint32 x;
2177         FLAC__bool wasted_bits;
2178         unsigned i;
2179
2180         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &x, 8, read_callback_, decoder)) /* MAGIC NUMBER */
2181                 return false; /* read_callback_ sets the state for us */
2182
2183         wasted_bits = (x & 1);
2184         x &= 0xfe;
2185
2186         if(wasted_bits) {
2187                 unsigned u;
2188                 if(!FLAC__bitbuffer_read_unary_unsigned(decoder->private_->input, &u, read_callback_, decoder))
2189                         return false; /* read_callback_ sets the state for us */
2190                 decoder->private_->frame.subframes[channel].wasted_bits = u+1;
2191                 bps -= decoder->private_->frame.subframes[channel].wasted_bits;
2192         }
2193         else
2194                 decoder->private_->frame.subframes[channel].wasted_bits = 0;
2195
2196         /*
2197          * Lots of magic numbers here
2198          */
2199         if(x & 0x80) {
2200                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2201                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2202                 return true;
2203         }
2204         else if(x == 0) {
2205                 if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2206                         return false;
2207         }
2208         else if(x == 2) {
2209                 if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2210                         return false;
2211         }
2212         else if(x < 16) {
2213                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2214                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2215                 return true;
2216         }
2217         else if(x <= 24) {
2218                 if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2219                         return false;
2220                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2221                         return true;
2222         }
2223         else if(x < 64) {
2224                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2225                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2226                 return true;
2227         }
2228         else {
2229                 if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2230                         return false;
2231                 if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2232                         return true;
2233         }
2234
2235         if(wasted_bits && do_full_decode) {
2236                 x = decoder->private_->frame.subframes[channel].wasted_bits;
2237                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2238                         decoder->private_->output[channel][i] <<= x;
2239         }
2240
2241         return true;
2242 }
2243
2244 FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2245 {
2246         FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2247         FLAC__int32 x;
2248         unsigned i;
2249         FLAC__int32 *output = decoder->private_->output[channel];
2250
2251         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2252
2253         if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
2254                 return false; /* read_callback_ sets the state for us */
2255
2256         subframe->value = x;
2257
2258         /* decode the subframe */
2259         if(do_full_decode) {
2260                 for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2261                         output[i] = x;
2262         }
2263
2264         return true;
2265 }
2266
2267 FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2268 {
2269         FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2270         FLAC__int32 i32;
2271         FLAC__uint32 u32;
2272         unsigned u;
2273
2274         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2275
2276         subframe->residual = decoder->private_->residual[channel];
2277         subframe->order = order;
2278
2279         /* read warm-up samples */
2280         for(u = 0; u < order; u++) {
2281                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
2282                         return false; /* read_callback_ sets the state for us */
2283                 subframe->warmup[u] = i32;
2284         }
2285
2286         /* read entropy coding method info */
2287         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
2288                 return false; /* read_callback_ sets the state for us */
2289         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2290         switch(subframe->entropy_coding_method.type) {
2291                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2292                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
2293                                 return false; /* read_callback_ sets the state for us */
2294                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2295                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2296                         break;
2297                 default:
2298                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2299                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2300                         return true;
2301         }
2302
2303         /* read residual */
2304         switch(subframe->entropy_coding_method.type) {
2305                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2306                         if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel]))
2307                                 return false;
2308                         break;
2309                 default:
2310                         FLAC__ASSERT(0);
2311         }
2312
2313         /* decode the subframe */
2314         if(do_full_decode) {
2315                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2316                 FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
2317         }
2318
2319         return true;
2320 }
2321
2322 FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2323 {
2324         FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2325         FLAC__int32 i32;
2326         FLAC__uint32 u32;
2327         unsigned u;
2328
2329         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2330
2331         subframe->residual = decoder->private_->residual[channel];
2332         subframe->order = order;
2333
2334         /* read warm-up samples */
2335         for(u = 0; u < order; u++) {
2336                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, bps, read_callback_, decoder))
2337                         return false; /* read_callback_ sets the state for us */
2338                 subframe->warmup[u] = i32;
2339         }
2340
2341         /* read qlp coeff precision */
2342         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN, read_callback_, decoder))
2343                 return false; /* read_callback_ sets the state for us */
2344         if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
2345                 send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2346                 decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2347                 return true;
2348         }
2349         subframe->qlp_coeff_precision = u32+1;
2350
2351         /* read qlp shift */
2352         if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN, read_callback_, decoder))
2353                 return false; /* read_callback_ sets the state for us */
2354         subframe->quantization_level = i32;
2355
2356         /* read quantized lp coefficiencts */
2357         for(u = 0; u < order; u++) {
2358                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision, read_callback_, decoder))
2359                         return false; /* read_callback_ sets the state for us */
2360                 subframe->qlp_coeff[u] = i32;
2361         }
2362
2363         /* read entropy coding method info */
2364         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
2365                 return false; /* read_callback_ sets the state for us */
2366         subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2367         switch(subframe->entropy_coding_method.type) {
2368                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2369                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
2370                                 return false; /* read_callback_ sets the state for us */
2371                         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2372                         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2373                         break;
2374                 default:
2375                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2376                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2377                         return true;
2378         }
2379
2380         /* read residual */
2381         switch(subframe->entropy_coding_method.type) {
2382                 case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2383                         if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel]))
2384                                 return false;
2385                         break;
2386                 default:
2387                         FLAC__ASSERT(0);
2388         }
2389
2390         /* decode the subframe */
2391         if(do_full_decode) {
2392                 memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2393                 if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2394                         if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2395                                 if(order <= 8)
2396                                         decoder->private_->local_lpc_restore_signal_16bit_order8(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
2397                                 else
2398                                         decoder->private_->local_lpc_restore_signal_16bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
2399                         }
2400                         else
2401                                 decoder->private_->local_lpc_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
2402                 else
2403                         decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
2404         }
2405
2406         return true;
2407 }
2408
2409 FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2410 {
2411         FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2412         FLAC__int32 x, *residual = decoder->private_->residual[channel];
2413         unsigned i;
2414
2415         decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2416
2417         subframe->data = residual;
2418
2419         for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2420                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &x, bps, read_callback_, decoder))
2421                         return false; /* read_callback_ sets the state for us */
2422                 residual[i] = x;
2423         }
2424
2425         /* decode the subframe */
2426         if(do_full_decode)
2427                 memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2428
2429         return true;
2430 }
2431
2432 FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual)
2433 {
2434         FLAC__uint32 rice_parameter;
2435         int i;
2436         unsigned partition, sample, u;
2437         const unsigned partitions = 1u << partition_order;
2438         const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2439
2440         /* sanity checks */
2441         if(partition_order == 0) {
2442                 if(decoder->private_->frame.header.blocksize < predictor_order) {
2443                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2444                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2445                         return true;
2446                 }
2447         }
2448         else {
2449                 if(partition_samples < predictor_order) {
2450                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2451                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2452                         return true;
2453                 }
2454         }
2455
2456         if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2457                 decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2458                 return false;
2459         }
2460
2461         sample = 0;
2462         for(partition = 0; partition < partitions; partition++) {
2463                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN, read_callback_, decoder))
2464                         return false; /* read_callback_ sets the state for us */
2465                 partitioned_rice_contents->parameters[partition] = rice_parameter;
2466                 if(rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2467                         u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2468                         if(!FLAC__bitbuffer_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter, read_callback_, decoder))
2469                                 return false; /* read_callback_ sets the state for us */
2470                         sample += u;
2471                 }
2472                 else {
2473                         if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN, read_callback_, decoder))
2474                                 return false; /* read_callback_ sets the state for us */
2475                         partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2476                         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2477                                 if(!FLAC__bitbuffer_read_raw_int32(decoder->private_->input, &i, rice_parameter, read_callback_, decoder))
2478                                         return false; /* read_callback_ sets the state for us */
2479                                 residual[sample] = i;
2480                         }
2481                 }
2482         }
2483
2484         return true;
2485 }
2486
2487 FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2488 {
2489         if(!FLAC__bitbuffer_is_consumed_byte_aligned(decoder->private_->input)) {
2490                 FLAC__uint32 zero = 0;
2491                 if(!FLAC__bitbuffer_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitbuffer_bits_left_for_byte_alignment(decoder->private_->input), read_callback_, decoder))
2492                         return false; /* read_callback_ sets the state for us */
2493                 if(zero != 0) {
2494                         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2495                         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2496                 }
2497         }
2498         return true;
2499 }
2500
2501 FLAC__bool read_callback_(FLAC__byte buffer[], unsigned *bytes, void *client_data)
2502 {
2503         FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2504
2505         if(decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)) {
2506                 *bytes = 0;
2507                 decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2508                 return false;
2509         }
2510         else if(*bytes > 0) {
2511                 /* While seeking, it is possible for our seek to land in the
2512                  * middle of audio data that looks exactly like a frame header
2513                  * from a future version of an encoder.  When that happens, our
2514                  * error callback will get an
2515                  * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
2516                  * unparseable_frame_count.  But there is a remote possibility
2517                  * that it is properly synced at such a "future-codec frame",
2518                  * so to make sure, we wait to see many "unparseable" errors in
2519                  * a row before bailing out.
2520                  */
2521                 if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2522                         decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2523                         return false;
2524                 }
2525                 else {
2526                         const FLAC__StreamDecoderReadStatus status = decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data);
2527                         if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
2528                                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2529                                 return false;
2530                         }
2531                         else if(*bytes == 0) {
2532                                 if(status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM || (decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data))) {
2533                                         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2534                                         return false;
2535                                 }
2536                                 else
2537                                         return true;
2538                         }
2539                         else
2540                                 return true;
2541                 }
2542         }
2543         else {
2544                 /* abort to avoid a deadlock */
2545                 decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2546                 return false;
2547         }
2548 }
2549
2550 FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2551 {
2552         if(decoder->private_->is_seeking) {
2553                 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
2554                 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
2555                 FLAC__uint64 target_sample = decoder->private_->target_sample;
2556
2557                 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2558
2559                 decoder->private_->last_frame = *frame; /* save the frame */
2560                 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
2561                         unsigned delta = (unsigned)(target_sample - this_frame_sample);
2562                         /* kick out of seek mode */
2563                         decoder->private_->is_seeking = false;
2564                         /* shift out the samples before target_sample */
2565                         if(delta > 0) {
2566                                 unsigned channel;
2567                                 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
2568                                 for(channel = 0; channel < frame->header.channels; channel++)
2569                                         newbuffer[channel] = buffer[channel] + delta;
2570                                 decoder->private_->last_frame.header.blocksize -= delta;
2571                                 decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
2572                                 /* write the relevant samples */
2573                                 return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
2574                         }
2575                         else {
2576                                 /* write the relevant samples */
2577                                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2578                         }
2579                 }
2580                 else {
2581                         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2582                 }
2583         }
2584         else {
2585                 /*
2586                  * If we never got STREAMINFO, turn off MD5 checking to save
2587                  * cycles since we don't have a sum to compare to anyway
2588                  */
2589                 if(!decoder->private_->has_stream_info)
2590                         decoder->private_->do_md5_checking = false;
2591                 if(decoder->private_->do_md5_checking) {
2592                         if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
2593                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2594                 }
2595                 return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2596         }
2597 }
2598
2599 void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2600 {
2601         if(!decoder->private_->is_seeking)
2602                 decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
2603         else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
2604                 decoder->private_->unparseable_frame_count++;
2605 }
2606
2607 FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2608 {
2609         FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound;
2610         FLAC__int64 pos = -1, last_pos = -1;
2611         int i, lower_seek_point = -1, upper_seek_point = -1;
2612         unsigned approx_bytes_per_frame;
2613         FLAC__uint64 last_frame_sample = FLAC__U64L(0xffffffffffffffff);
2614         FLAC__bool needs_seek;
2615         const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
2616         const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2617         const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
2618         const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
2619         const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
2620         const unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
2621         const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
2622
2623         /* we are just guessing here, but we want to guess high, not low */
2624         if(max_framesize > 0)
2625                 approx_bytes_per_frame = max_framesize;
2626
2627         /*
2628          * Check if it's a known fixed-blocksize stream.  Note that though
2629          * the spec doesn't allow zeroes in the STREAMINFO block, we may
2630          * never get a STREAMINFO block when decoding so the value of
2631          * min_blocksize might be zero.
2632          */
2633         else if(min_blocksize == max_blocksize && min_blocksize > 0) {
2634                 /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
2635                 approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
2636         }
2637         else
2638                 approx_bytes_per_frame = 4608 * channels * bps/8 + 64;
2639
2640         /*
2641          * First, we set an upper and lower bound on where in the
2642          * stream we will search.  For now we assume the worst case
2643          * scenario, which is our best guess at the beginning of
2644          * the first and last frames.
2645          */
2646         lower_bound = first_frame_offset;
2647
2648         /* calc the upper_bound, beyond which we never want to seek */
2649         if(max_framesize > 0)
2650                 upper_bound = stream_length - (max_framesize + 128 + 2); /* 128 for a possible ID3V1 tag, 2 for indexing differences */
2651         else
2652                 upper_bound = stream_length - ((channels * bps * FLAC__MAX_BLOCK_SIZE) / 8 + 128 + 2);
2653
2654         /*
2655          * Now we refine the bounds if we have a seektable with
2656          * suitable points.  Note that according to the spec they
2657          * must be ordered by ascending sample number.
2658          */
2659         if(seek_table) {
2660                 /* find the closest seek point <= target_sample, if it exists */
2661                 for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
2662                         if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number <= target_sample)
2663                                 break;
2664                 }
2665                 if(i >= 0) { /* i.e. we found a suitable seek point... */
2666                         lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
2667                         lower_seek_point = i;
2668                 }
2669
2670                 /* find the closest seek point > target_sample, if it exists */
2671                 for(i = 0; i < (int)seek_table->num_points; i++) {
2672                         if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && seek_table->points[i].sample_number > target_sample)
2673                                 break;
2674                 }
2675                 if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
2676                         upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
2677                         upper_seek_point = i;
2678                 }
2679         }
2680
2681         /*
2682          * Now guess at where within those bounds our target
2683          * sample will be.
2684          */
2685         if(seek_table && lower_seek_point >= 0) {
2686                 /* first see if our sample is within a few frames of the lower seekpoint */
2687                 if(seek_table->points[lower_seek_point].sample_number <= target_sample && target_sample < seek_table->points[lower_seek_point].sample_number + (seek_table->points[lower_seek_point].frame_samples * 4)) {
2688                         pos = (FLAC__int64)lower_bound;
2689                 }
2690                 else if(upper_seek_point >= 0) {
2691                         const FLAC__uint64 target_offset = target_sample - seek_table->points[lower_seek_point].sample_number;
2692                         const FLAC__uint64 range_samples = seek_table->points[upper_seek_point].sample_number - seek_table->points[lower_seek_point].sample_number;
2693                         const FLAC__uint64 range_bytes = (upper_bound>lower_bound? upper_bound - lower_bound - 1 : 0);
2694 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2695 #if defined _MSC_VER || defined __MINGW32__
2696                         /* with MSVC you have to spoon feed it the casting */
2697                         pos = (FLAC__int64)lower_bound + (FLAC__int64)(((FLAC__double)(FLAC__int64)target_offset / (FLAC__double)(FLAC__int64)range_samples) * (FLAC__double)(FLAC__int64)(range_bytes-1)) - approx_bytes_per_frame;
2698 #else
2699                         pos = (FLAC__int64)lower_bound + (FLAC__int64)(((FLAC__double)target_offset / (FLAC__double)range_samples) * (FLAC__double)range_bytes) - approx_bytes_per_frame;
2700 #endif
2701 #else
2702                         /* a little less accurate: */
2703                         if (range_bytes <= 0xffffffff)
2704                                 pos = (FLAC__int64)lower_bound + (FLAC__int64)((target_offset * range_bytes) / range_samples) - approx_bytes_per_frame;
2705                         else /* @@@ WATCHOUT, ~2TB limit */
2706                                 pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_offset>>8) * (range_bytes>>8)) / (range_samples>>16)) - approx_bytes_per_frame;
2707 #endif
2708                 }
2709         }
2710
2711         /*
2712          * If there's no seek table, we need to use the metadata (if we
2713          * have it) and the filelength to estimate the position of the
2714          * frame with the correct sample.
2715          */
2716         if(pos < 0 && total_samples > 0) {
2717                 /*
2718                  * For max accuracy we should be using
2719                  * (stream_length-first_frame_offset-1) in the divisor, but the
2720                  * difference is trivial and (stream_length-first_frame_offset)
2721                  * has no chance of underflow.
2722                  */
2723 #ifndef FLAC__INTEGER_ONLY_LIBRARY
2724 #if defined _MSC_VER || defined __MINGW32__
2725                 /* with VC++ you have to spoon feed it the casting */
2726                 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)(((FLAC__double)(FLAC__int64)target_sample / (FLAC__double)(FLAC__int64)total_samples) * (FLAC__double)(FLAC__int64)(stream_length-first_frame_offset)) - approx_bytes_per_frame;
2727 #else
2728                 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)(((FLAC__double)target_sample / (FLAC__double)total_samples) * (FLAC__double)(stream_length-first_frame_offset)) - approx_bytes_per_frame;
2729 #endif
2730 #else
2731                 /* a little less accurate: */
2732                 if (stream_length < 0xffffffff)
2733                         pos = (FLAC__int64)first_frame_offset + (FLAC__int64)((target_sample * (stream_length-first_frame_offset)) / total_samples) - approx_bytes_per_frame;
2734                 else /* @@@ WATCHOUT, ~2TB limit */
2735                         pos = (FLAC__int64)first_frame_offset + (FLAC__int64)(((target_sample>>8) * ((stream_length-first_frame_offset)>>8)) / (total_samples>>16)) - approx_bytes_per_frame;
2736 #endif
2737         }
2738
2739         /*
2740          * If there's no seek table and total_samples is unknown, we
2741          * don't even bother trying to figure out a target, we just use
2742          * our current position.
2743          */
2744         if(pos < 0) {
2745                 FLAC__uint64 upos;
2746                 if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK) {
2747                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2748                         return false;
2749                 }
2750                 pos = (FLAC__int64)upos;
2751                 needs_seek = false;
2752         }
2753         else
2754                 needs_seek = true;
2755
2756         /* clip the position to the bounds, lower bound takes precedence */
2757         if(pos >= (FLAC__int64)upper_bound) {
2758                 pos = (FLAC__int64)upper_bound-1;
2759                 needs_seek = true;
2760         }
2761         if(pos < (FLAC__int64)lower_bound) {
2762                 pos = (FLAC__int64)lower_bound;
2763                 needs_seek = true;
2764         }
2765
2766         decoder->private_->target_sample = target_sample;
2767         while(1) {
2768                 if(needs_seek) {
2769                         if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
2770                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2771                                 return false;
2772                         }
2773                         if(!FLAC__stream_decoder_flush(decoder)) {
2774                                 /* above call sets the state for us */
2775                                 return false;
2776                         }
2777                 }
2778                 /* Now we need to get a frame.  First we need to reset our
2779                  * unparseable_frame_count; if we get too many unparseable
2780                  * frames in a row, the read callback will return
2781                  * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
2782                  * FLAC__stream_decoder_process_single() to return false.
2783                  */
2784                 decoder->private_->unparseable_frame_count = 0;
2785                 if(!FLAC__stream_decoder_process_single(decoder)) {
2786                         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2787                         return false;
2788                 }
2789                 /* our write callback will change the state when it gets to the target frame */
2790                 /* actually, we could have got_a_frame if our decoder is at FLAC__STREAM_DECODER_END_OF_STREAM so we need to check for that also */
2791 #if 0
2792                 /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
2793                 if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
2794                         break;
2795 #endif
2796                 if(!decoder->private_->is_seeking) {
2797                         break;
2798                 }
2799                 else { /* we need to narrow the search */
2800                         const FLAC__uint64 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
2801                         FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2802                         if(this_frame_sample == last_frame_sample && pos < last_pos) {
2803                                 /* our last move backwards wasn't big enough, double it */
2804                                 pos -= (last_pos - pos);
2805                                 needs_seek = true;
2806                         }
2807                         else {
2808                                 if(target_sample < this_frame_sample) {
2809                                         last_pos = pos;
2810                                         approx_bytes_per_frame = decoder->private_->last_frame.header.blocksize * channels * bps/8 + 64;
2811                                         pos -= approx_bytes_per_frame;
2812                                         needs_seek = true;
2813                                 }
2814                                 else { /* target_sample >= this_frame_sample + this frame's blocksize */
2815                                         FLAC__uint64 upos;
2816                                         if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK) {
2817                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2818                                                 return false;
2819                                         }
2820                                         last_pos = pos;
2821                                         pos = (FLAC__int64)upos;
2822                                         pos -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
2823                                         needs_seek = false;
2824                                         /*
2825                                          * if we haven't hit the target frame yet and our position hasn't changed,
2826                                          * it means we're at the end of the stream and the seek target does not exist.
2827                                          */
2828                                         if(last_pos == pos) {
2829                                                 decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
2830                                                 return false;
2831                                         }
2832                                 }
2833                         }
2834                         if(pos < (FLAC__int64)lower_bound)
2835                                 pos = (FLAC__int64)lower_bound;
2836                         last_frame_sample = this_frame_sample;
2837                 }
2838         }
2839
2840         return true;
2841 }
2842
2843 FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
2844 {
2845         (void)client_data;
2846
2847         if(*bytes > 0) {
2848                 *bytes = (unsigned)fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
2849                 if(ferror(decoder->private_->file))
2850                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2851                 else if(*bytes == 0)
2852                         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2853                 else
2854                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2855         }
2856         else
2857                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
2858 }
2859
2860 FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2861 {
2862         (void)client_data;
2863
2864         if(decoder->private_->file == stdin)
2865                 return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
2866         else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
2867                 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
2868         else
2869                 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2870 }
2871
2872 FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2873 {
2874         off_t pos;
2875         (void)client_data;
2876
2877         if(decoder->private_->file == stdin) /*@@@@@@ may work for stdin */
2878                 return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
2879         else if((pos = ftello(decoder->private_->file)) < 0)
2880                 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
2881         else {
2882                 *absolute_byte_offset = (FLAC__uint64)pos;
2883                 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2884         }
2885 }
2886
2887 FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2888 {
2889         struct stat filestats;
2890         (void)client_data;
2891
2892         if(decoder->private_->file == stdin)
2893                 return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
2894 #ifdef OLD_STAT_WAY
2895         else if(0 == decoder->private_->filename || fstat(fileno(decoder->private_->file), &filestats) != 0)
2896 #endif
2897         else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
2898                 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
2899         else {
2900                 *stream_length = (FLAC__uint64)filestats.st_size;
2901                 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2902         }
2903 }
2904
2905 FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
2906 {
2907         (void)client_data;
2908
2909         if(decoder->private_->file == stdin) /*@@@@@@ feof() may work for stdin */
2910                 return false;
2911         return feof(decoder->private_->file)? true : false;
2912 }