stream_decoder.c 50.6 KB
Newer Older
1
/* libFLAC - Free Lossless Audio Codec library
Josh Coalson's avatar
Josh Coalson committed
2
 * Copyright (C) 2000,2001  Josh Coalson
Josh Coalson's avatar
Josh Coalson committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA  02111-1307, USA.
 */

#include <stdio.h>
#include <stdlib.h> /* for malloc() */
Josh Coalson's avatar
Josh Coalson committed
22
#include <string.h> /* for memset/memcpy() */
23
#include "FLAC/assert.h"
Josh Coalson's avatar
Josh Coalson committed
24
25
#include "FLAC/stream_decoder.h"
#include "private/bitbuffer.h"
26
#include "private/cpu.h"
Josh Coalson's avatar
Josh Coalson committed
27
28
29
30
31
32
#include "private/crc.h"
#include "private/fixed.h"
#include "private/lpc.h"

typedef struct FLAC__StreamDecoderPrivate {
	FLAC__StreamDecoderReadStatus (*read_callback)(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data);
33
	FLAC__StreamDecoderWriteStatus (*write_callback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data);
Josh Coalson's avatar
Josh Coalson committed
34
35
	void (*metadata_callback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
	void (*error_callback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
36
	void (*local_lpc_restore_signal)(const int32 residual[], unsigned data_len, const int32 qlp_coeff[], unsigned order, int lp_quantization, int32 data[]);
37
	void (*local_lpc_restore_signal_16bit)(const int32 residual[], unsigned data_len, const int32 qlp_coeff[], unsigned order, int lp_quantization, int32 data[]);
Josh Coalson's avatar
Josh Coalson committed
38
39
40
	void *client_data;
	FLAC__BitBuffer input;
	int32 *output[FLAC__MAX_CHANNELS];
41
	int32 *residual[FLAC__MAX_CHANNELS];
42
	unsigned output_capacity, output_channels;
Josh Coalson's avatar
Josh Coalson committed
43
44
	uint32 last_frame_number;
	uint64 samples_decoded;
45
46
47
	bool has_stream_info, has_seek_table;
	FLAC__StreamMetaData stream_info;
	FLAC__StreamMetaData seek_table;
48
	FLAC__Frame frame;
49
50
	bool cached; /* true if there is a byte in lookahead */
	FLAC__CPUInfo cpuinfo;
51
52
	byte header_warmup[2]; /* contains the sync code and reserved bits */
	byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
Josh Coalson's avatar
Josh Coalson committed
53
54
55
56
} FLAC__StreamDecoderPrivate;

static byte ID3V2_TAG_[3] = { 'I', 'D', '3' };

57
static bool stream_decoder_allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
Josh Coalson's avatar
Josh Coalson committed
58
59
60
61
62
63
static bool stream_decoder_find_metadata_(FLAC__StreamDecoder *decoder);
static bool stream_decoder_read_metadata_(FLAC__StreamDecoder *decoder);
static bool stream_decoder_skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
static bool stream_decoder_frame_sync_(FLAC__StreamDecoder *decoder);
static bool stream_decoder_read_frame_(FLAC__StreamDecoder *decoder, bool *got_a_frame);
static bool stream_decoder_read_frame_header_(FLAC__StreamDecoder *decoder);
64
65
66
67
68
static bool stream_decoder_read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps);
static bool stream_decoder_read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps);
static bool stream_decoder_read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order);
static bool stream_decoder_read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order);
static bool stream_decoder_read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps);
69
static bool stream_decoder_read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, int32 *residual);
Josh Coalson's avatar
Josh Coalson committed
70
71
72
static bool stream_decoder_read_zero_padding_(FLAC__StreamDecoder *decoder);
static bool read_callback_(byte buffer[], unsigned *bytes, void *client_data);

Josh Coalson's avatar
Josh Coalson committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const char *FLAC__StreamDecoderStateString[] = {
	"FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
	"FLAC__STREAM_DECODER_READ_METADATA",
	"FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
	"FLAC__STREAM_DECODER_READ_FRAME",
	"FLAC__STREAM_DECODER_END_OF_STREAM",
	"FLAC__STREAM_DECODER_ABORTED",
	"FLAC__STREAM_DECODER_UNPARSEABLE_STREAM",
	"FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
	"FLAC__STREAM_DECODER_UNINITIALIZED"
};

const char *FLAC__StreamDecoderReadStatusString[] = {
	"FLAC__STREAM_DECODER_READ_CONTINUE",
	"FLAC__STREAM_DECODER_READ_END_OF_STREAM",
	"FLAC__STREAM_DECODER_READ_ABORT"
};

const char *FLAC__StreamDecoderWriteStatusString[] = {
	"FLAC__STREAM_DECODER_WRITE_CONTINUE",
	"FLAC__STREAM_DECODER_WRITE_ABORT"
};

const char *FLAC__StreamDecoderErrorStatusString[] = {
97
98
99
	"FLAC__STREAM_DECODER_ERROR_LOST_SYNC",
	"FLAC__STREAM_DECODER_ERROR_BAD_HEADER",
	"FLAC__STREAM_DECODER_ERROR_FRAME_CRC_MISMATCH"
Josh Coalson's avatar
Josh Coalson committed
100
101
};

Josh Coalson's avatar
Josh Coalson committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
FLAC__StreamDecoder *FLAC__stream_decoder_get_new_instance()
{
	FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)malloc(sizeof(FLAC__StreamDecoder));
	if(decoder != 0) {
		decoder->state = FLAC__STREAM_DECODER_UNINITIALIZED;
		decoder->guts = 0;
	}
	return decoder;
}

void FLAC__stream_decoder_free_instance(FLAC__StreamDecoder *decoder)
{
	free(decoder);
}

FLAC__StreamDecoderState FLAC__stream_decoder_init(
	FLAC__StreamDecoder *decoder,
	FLAC__StreamDecoderReadStatus (*read_callback)(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data),
120
	FLAC__StreamDecoderWriteStatus (*write_callback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data),
Josh Coalson's avatar
Josh Coalson committed
121
122
123
124
125
126
127
	void (*metadata_callback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data),
	void (*error_callback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data),
	void *client_data
)
{
	unsigned i;

128
129
130
131
132
133
134
135
	FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
	FLAC__ASSERT(decoder != 0);
	FLAC__ASSERT(read_callback != 0);
	FLAC__ASSERT(write_callback != 0);
	FLAC__ASSERT(metadata_callback != 0);
	FLAC__ASSERT(error_callback != 0);
	FLAC__ASSERT(decoder->state == FLAC__STREAM_DECODER_UNINITIALIZED);
	FLAC__ASSERT(decoder->guts == 0);
Josh Coalson's avatar
Josh Coalson committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150

	decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;

	decoder->guts = (FLAC__StreamDecoderPrivate*)malloc(sizeof(FLAC__StreamDecoderPrivate));
	if(decoder->guts == 0)
		return decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;

	decoder->guts->read_callback = read_callback;
	decoder->guts->write_callback = write_callback;
	decoder->guts->metadata_callback = metadata_callback;
	decoder->guts->error_callback = error_callback;
	decoder->guts->client_data = client_data;

	FLAC__bitbuffer_init(&decoder->guts->input);

151
	for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
Josh Coalson's avatar
Josh Coalson committed
152
		decoder->guts->output[i] = 0;
153
154
		decoder->guts->residual[i] = 0;
	}
Josh Coalson's avatar
Josh Coalson committed
155
156

	decoder->guts->output_capacity = 0;
157
	decoder->guts->output_channels = 0;
Josh Coalson's avatar
Josh Coalson committed
158
159
	decoder->guts->last_frame_number = 0;
	decoder->guts->samples_decoded = 0;
160
161
	decoder->guts->has_stream_info = false;
	decoder->guts->has_seek_table = false;
162
	decoder->guts->cached = false;
Josh Coalson's avatar
Josh Coalson committed
163

164
165
166
167
168
169
	/*
	 * get the CPU info and set the function pointers
	 */
	FLAC__cpu_info(&decoder->guts->cpuinfo);
	/* first default to the non-asm routines */
	decoder->guts->local_lpc_restore_signal = FLAC__lpc_restore_signal;
170
	decoder->guts->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
171
	/* now override with asm where appropriate */
172
#ifndef FLAC__NO_ASM
173
	FLAC__ASSERT(decoder->guts->cpuinfo.use_asm);
174
#ifdef FLAC__CPU_IA32
175
	FLAC__ASSERT(decoder->guts->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
176
#ifdef FLAC__HAS_NASM
177
	if(decoder->guts->cpuinfo.data.ia32.mmx) {
178
		decoder->guts->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_i386;
179
180
181
182
183
184
		decoder->guts->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_i386_mmx;
	}
	else {
		decoder->guts->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_i386;
		decoder->guts->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_i386;
	}
185
#endif
186
#endif
187
188
#endif

Josh Coalson's avatar
Josh Coalson committed
189
190
191
192
193
194
	return decoder->state;
}

void FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
{
	unsigned i;
195
	FLAC__ASSERT(decoder != 0);
Josh Coalson's avatar
Josh Coalson committed
196
197
198
	if(decoder->state == FLAC__STREAM_DECODER_UNINITIALIZED)
		return;
	if(decoder->guts != 0) {
199
200
201
202
		if(decoder->guts->has_seek_table) {
			free(decoder->guts->seek_table.data.seek_table.points);
			decoder->guts->seek_table.data.seek_table.points = 0;
		}
Josh Coalson's avatar
Josh Coalson committed
203
204
205
206
207
208
		FLAC__bitbuffer_free(&decoder->guts->input);
		for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
			if(decoder->guts->output[i] != 0) {
				free(decoder->guts->output[i]);
				decoder->guts->output[i] = 0;
			}
209
210
211
212
			if(decoder->guts->residual[i] != 0) {
				free(decoder->guts->residual[i]);
				decoder->guts->residual[i] = 0;
			}
Josh Coalson's avatar
Josh Coalson committed
213
214
215
216
217
218
219
220
221
		}
		free(decoder->guts);
		decoder->guts = 0;
	}
	decoder->state = FLAC__STREAM_DECODER_UNINITIALIZED;
}

bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
{
222
	FLAC__ASSERT(decoder != 0);
Josh Coalson's avatar
Josh Coalson committed
223
224
225
226
227
228
229
230
231
232
233

	if(!FLAC__bitbuffer_clear(&decoder->guts->input)) {
		decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
		return false;
	}

	return true;
}

bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
{
234
	FLAC__ASSERT(decoder != 0);
Josh Coalson's avatar
Josh Coalson committed
235
236
237
238
239
240
241

	if(!FLAC__stream_decoder_flush(decoder)) {
		decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
		return false;
	}
	decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;

Josh Coalson's avatar
Josh Coalson committed
242
243
	decoder->guts->samples_decoded = 0;

Josh Coalson's avatar
Josh Coalson committed
244
245
246
247
248
249
	return true;
}

bool FLAC__stream_decoder_process_whole_stream(FLAC__StreamDecoder *decoder)
{
	bool dummy;
250
	FLAC__ASSERT(decoder != 0);
Josh Coalson's avatar
Josh Coalson committed
251
252
253
254

	if(decoder->state == FLAC__STREAM_DECODER_END_OF_STREAM)
		return true;

255
	FLAC__ASSERT(decoder->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA);
Josh Coalson's avatar
Josh Coalson committed
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282

	if(!FLAC__stream_decoder_reset(decoder)) {
		decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
		return false;
	}

	while(1) {
		switch(decoder->state) {
			case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
				if(!stream_decoder_find_metadata_(decoder))
					return false; /* above function sets the status for us */
				break;
			case FLAC__STREAM_DECODER_READ_METADATA:
				if(!stream_decoder_read_metadata_(decoder))
					return false; /* above function sets the status for us */
				break;
			case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
				if(!stream_decoder_frame_sync_(decoder))
					return true; /* above function sets the status for us */
				break;
			case FLAC__STREAM_DECODER_READ_FRAME:
				if(!stream_decoder_read_frame_(decoder, &dummy))
					return false; /* above function sets the status for us */
				break;
			case FLAC__STREAM_DECODER_END_OF_STREAM:
				return true;
			default:
283
				FLAC__ASSERT(0);
Josh Coalson's avatar
Josh Coalson committed
284
285
286
287
288
289
		}
	}
}

bool FLAC__stream_decoder_process_metadata(FLAC__StreamDecoder *decoder)
{
290
	FLAC__ASSERT(decoder != 0);
Josh Coalson's avatar
Josh Coalson committed
291
292
293
294

	if(decoder->state == FLAC__STREAM_DECODER_END_OF_STREAM)
		return true;

295
	FLAC__ASSERT(decoder->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA);
Josh Coalson's avatar
Josh Coalson committed
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317

	if(!FLAC__stream_decoder_reset(decoder)) {
		decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
		return false;
	}

	while(1) {
		switch(decoder->state) {
			case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
				if(!stream_decoder_find_metadata_(decoder))
					return false; /* above function sets the status for us */
				break;
			case FLAC__STREAM_DECODER_READ_METADATA:
				if(!stream_decoder_read_metadata_(decoder))
					return false; /* above function sets the status for us */
				break;
			case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
				return true;
				break;
			case FLAC__STREAM_DECODER_END_OF_STREAM:
				return true;
			default:
318
				FLAC__ASSERT(0);
Josh Coalson's avatar
Josh Coalson committed
319
320
321
322
323
324
325
		}
	}
}

bool FLAC__stream_decoder_process_one_frame(FLAC__StreamDecoder *decoder)
{
	bool got_a_frame;
326
	FLAC__ASSERT(decoder != 0);
Josh Coalson's avatar
Josh Coalson committed
327
328
329
330

	if(decoder->state == FLAC__STREAM_DECODER_END_OF_STREAM)
		return true;

331
	FLAC__ASSERT(decoder->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC);
Josh Coalson's avatar
Josh Coalson committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347

	while(1) {
		switch(decoder->state) {
			case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
				if(!stream_decoder_frame_sync_(decoder))
					return true; /* above function sets the status for us */
				break;
			case FLAC__STREAM_DECODER_READ_FRAME:
				if(!stream_decoder_read_frame_(decoder, &got_a_frame))
					return false; /* above function sets the status for us */
				if(got_a_frame)
					return true; /* above function sets the status for us */
				break;
			case FLAC__STREAM_DECODER_END_OF_STREAM:
				return true;
			default:
348
				FLAC__ASSERT(0);
Josh Coalson's avatar
Josh Coalson committed
349
350
351
352
353
354
355
		}
	}
}

bool FLAC__stream_decoder_process_remaining_frames(FLAC__StreamDecoder *decoder)
{
	bool dummy;
356
	FLAC__ASSERT(decoder != 0);
Josh Coalson's avatar
Josh Coalson committed
357
358
359
360

	if(decoder->state == FLAC__STREAM_DECODER_END_OF_STREAM)
		return true;

361
	FLAC__ASSERT(decoder->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC);
Josh Coalson's avatar
Josh Coalson committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375

	while(1) {
		switch(decoder->state) {
			case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
				if(!stream_decoder_frame_sync_(decoder))
					return true; /* above function sets the status for us */
				break;
			case FLAC__STREAM_DECODER_READ_FRAME:
				if(!stream_decoder_read_frame_(decoder, &dummy))
					return false; /* above function sets the status for us */
				break;
			case FLAC__STREAM_DECODER_END_OF_STREAM:
				return true;
			default:
376
				FLAC__ASSERT(0);
Josh Coalson's avatar
Josh Coalson committed
377
378
379
380
381
382
		}
	}
}

unsigned FLAC__stream_decoder_input_bytes_unconsumed(FLAC__StreamDecoder *decoder)
{
383
	FLAC__ASSERT(decoder != 0);
Josh Coalson's avatar
Josh Coalson committed
384
385
386
	return decoder->guts->input.bytes - decoder->guts->input.consumed_bytes;
}

387
bool stream_decoder_allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
Josh Coalson's avatar
Josh Coalson committed
388
389
390
391
{
	unsigned i;
	int32 *tmp;

392
	if(size <= decoder->guts->output_capacity && channels <= decoder->guts->output_channels)
Josh Coalson's avatar
Josh Coalson committed
393
394
		return true;

395
396
	/* @@@ should change to use realloc() */

Josh Coalson's avatar
Josh Coalson committed
397
398
399
400
401
	for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
		if(decoder->guts->output[i] != 0) {
			free(decoder->guts->output[i]);
			decoder->guts->output[i] = 0;
		}
402
403
404
405
		if(decoder->guts->residual[i] != 0) {
			free(decoder->guts->residual[i]);
			decoder->guts->residual[i] = 0;
		}
Josh Coalson's avatar
Josh Coalson committed
406
407
	}

408
	for(i = 0; i < channels; i++) {
Josh Coalson's avatar
Josh Coalson committed
409
410
411
412
413
414
		tmp = (int32*)malloc(sizeof(int32)*size);
		if(tmp == 0) {
			decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
			return false;
		}
		decoder->guts->output[i] = tmp;
415
416
417
418
419
420
421

		tmp = (int32*)malloc(sizeof(int32)*size);
		if(tmp == 0) {
			decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
			return false;
		}
		decoder->guts->residual[i] = tmp;
Josh Coalson's avatar
Josh Coalson committed
422
423
424
	}

	decoder->guts->output_capacity = size;
425
	decoder->guts->output_channels = channels;
Josh Coalson's avatar
Josh Coalson committed
426
427
428
429
430
431
432
433

	return true;
}

bool stream_decoder_find_metadata_(FLAC__StreamDecoder *decoder)
{
	uint32 x;
	unsigned i, id;
434
	bool first = true;
Josh Coalson's avatar
Josh Coalson committed
435

436
	FLAC__ASSERT(decoder->guts->input.consumed_bits == 0); /* make sure we're byte aligned */
Josh Coalson's avatar
Josh Coalson committed
437
438

	for(i = id = 0; i < 4; ) {
439
440
441
442
443
444
445
446
		if(decoder->guts->cached) {
			x = (uint32)decoder->guts->lookahead;
			decoder->guts->cached = false;
		}
		else {
			if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
				return false; /* the read_callback_ sets the state for us */
		}
Josh Coalson's avatar
Josh Coalson committed
447
		if(x == FLAC__STREAM_SYNC_STRING[i]) {
448
			first = true;
Josh Coalson's avatar
Josh Coalson committed
449
450
451
452
453
454
455
456
457
458
459
460
461
462
			i++;
			id = 0;
			continue;
		}
		if(x == ID3V2_TAG_[id]) {
			id++;
			i = 0;
			if(id == 3) {
				if(!stream_decoder_skip_id3v2_tag_(decoder))
					return false; /* the read_callback_ sets the state for us */
			}
			continue;
		}
		if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
463
464
			decoder->guts->header_warmup[0] = (byte)x;
			if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
465
				return false; /* the read_callback_ sets the state for us */
466
467
468
469
470
471
472
473
474

			/* 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 */
			/* else we have to check if the second byte is the end of a sync code */
			if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
				decoder->guts->lookahead = (byte)x;
				decoder->guts->cached = true;
			}
			else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
				decoder->guts->header_warmup[1] = (byte)x;
Josh Coalson's avatar
Josh Coalson committed
475
476
477
478
479
480
481
				decoder->state = FLAC__STREAM_DECODER_READ_FRAME;
				return true;
			}
		}
		i = 0;
		if(first) {
			decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_LOST_SYNC, decoder->guts->client_data);
482
			first = false;
Josh Coalson's avatar
Josh Coalson committed
483
484
485
486
487
488
489
490
491
492
		}
	}

	decoder->state = FLAC__STREAM_DECODER_READ_METADATA;
	return true;
}

bool stream_decoder_read_metadata_(FLAC__StreamDecoder *decoder)
{
	uint32 i, x, last_block, type, length;
493
	uint64 xx;
Josh Coalson's avatar
Josh Coalson committed
494

495
	FLAC__ASSERT(decoder->guts->input.consumed_bits == 0); /* make sure we're byte aligned */
Josh Coalson's avatar
Josh Coalson committed
496
497
498
499
500
501
502

	if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &last_block, FLAC__STREAM_METADATA_IS_LAST_LEN, read_callback_, decoder))
		return false; /* the read_callback_ sets the state for us */
	if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &type, FLAC__STREAM_METADATA_TYPE_LEN, read_callback_, decoder))
		return false; /* the read_callback_ sets the state for us */
	if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN, read_callback_, decoder))
		return false; /* the read_callback_ sets the state for us */
Josh Coalson's avatar
Josh Coalson committed
503
	if(type == FLAC__METADATA_TYPE_STREAMINFO) {
504
		unsigned used_bits = 0;
505
506
507
		decoder->guts->stream_info.type = type;
		decoder->guts->stream_info.is_last = last_block;
		decoder->guts->stream_info.length = length;
508

Josh Coalson's avatar
Josh Coalson committed
509
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
510
			return false; /* the read_callback_ sets the state for us */
511
		decoder->guts->stream_info.data.stream_info.min_blocksize = x;
Josh Coalson's avatar
Josh Coalson committed
512
		used_bits += FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
513

Josh Coalson's avatar
Josh Coalson committed
514
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
515
			return false; /* the read_callback_ sets the state for us */
516
		decoder->guts->stream_info.data.stream_info.max_blocksize = x;
Josh Coalson's avatar
Josh Coalson committed
517
		used_bits += FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
518

Josh Coalson's avatar
Josh Coalson committed
519
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
520
			return false; /* the read_callback_ sets the state for us */
521
		decoder->guts->stream_info.data.stream_info.min_framesize = x;
Josh Coalson's avatar
Josh Coalson committed
522
		used_bits += FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
523

Josh Coalson's avatar
Josh Coalson committed
524
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
525
			return false; /* the read_callback_ sets the state for us */
526
		decoder->guts->stream_info.data.stream_info.max_framesize = x;
Josh Coalson's avatar
Josh Coalson committed
527
		used_bits += FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
528

Josh Coalson's avatar
Josh Coalson committed
529
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
530
			return false; /* the read_callback_ sets the state for us */
531
		decoder->guts->stream_info.data.stream_info.sample_rate = x;
Josh Coalson's avatar
Josh Coalson committed
532
		used_bits += FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
533

Josh Coalson's avatar
Josh Coalson committed
534
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
535
			return false; /* the read_callback_ sets the state for us */
536
		decoder->guts->stream_info.data.stream_info.channels = x+1;
Josh Coalson's avatar
Josh Coalson committed
537
		used_bits += FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
538

Josh Coalson's avatar
Josh Coalson committed
539
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
540
			return false; /* the read_callback_ sets the state for us */
541
		decoder->guts->stream_info.data.stream_info.bits_per_sample = x+1;
Josh Coalson's avatar
Josh Coalson committed
542
		used_bits += FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
543

544
		if(!FLAC__bitbuffer_read_raw_uint64(&decoder->guts->input, &decoder->guts->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
545
			return false; /* the read_callback_ sets the state for us */
Josh Coalson's avatar
Josh Coalson committed
546
		used_bits += FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
547

Josh Coalson's avatar
Josh Coalson committed
548
549
550
		for(i = 0; i < 16; i++) {
			if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
				return false; /* the read_callback_ sets the state for us */
551
			decoder->guts->stream_info.data.stream_info.md5sum[i] = (byte)x;
Josh Coalson's avatar
Josh Coalson committed
552
		}
553
		used_bits += i*8;
Josh Coalson's avatar
Josh Coalson committed
554

555
		/* skip the rest of the block */
556
		FLAC__ASSERT(used_bits % 8 == 0);
557
558
559
560
561
562
		length -= (used_bits / 8);
		for(i = 0; i < length; i++) {
			if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
				return false; /* the read_callback_ sets the state for us */
		}

563
564
565
566
		decoder->guts->has_stream_info = true;
		decoder->guts->metadata_callback(decoder, &decoder->guts->stream_info, decoder->guts->client_data);
	}
	else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
Josh Coalson's avatar
Josh Coalson committed
567
568
		unsigned real_points;

569
570
571
572
573
574
575
576
577
578
		decoder->guts->seek_table.type = type;
		decoder->guts->seek_table.is_last = last_block;
		decoder->guts->seek_table.length = length;

		decoder->guts->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LEN;

		if(0 == (decoder->guts->seek_table.data.seek_table.points = (FLAC__StreamMetaData_SeekPoint*)malloc(decoder->guts->seek_table.data.seek_table.num_points * sizeof(FLAC__StreamMetaData_SeekPoint)))) {
			decoder->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
			return false;
		}
Josh Coalson's avatar
Josh Coalson committed
579
		for(i = real_points = 0; i < decoder->guts->seek_table.data.seek_table.num_points; i++) {
580
581
			if(!FLAC__bitbuffer_read_raw_uint64(&decoder->guts->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN, read_callback_, decoder))
				return false; /* the read_callback_ sets the state for us */
Josh Coalson's avatar
Josh Coalson committed
582
			decoder->guts->seek_table.data.seek_table.points[real_points].sample_number = xx;
583
584
585

			if(!FLAC__bitbuffer_read_raw_uint64(&decoder->guts->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN, read_callback_, decoder))
				return false; /* the read_callback_ sets the state for us */
Josh Coalson's avatar
Josh Coalson committed
586
			decoder->guts->seek_table.data.seek_table.points[real_points].stream_offset = xx;
587

Josh Coalson's avatar
Josh Coalson committed
588
			if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN, read_callback_, decoder))
589
				return false; /* the read_callback_ sets the state for us */
Josh Coalson's avatar
Josh Coalson committed
590
591
592
593
			decoder->guts->seek_table.data.seek_table.points[real_points].frame_samples = x;

			if(decoder->guts->seek_table.data.seek_table.points[real_points].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
				real_points++;
594
		}
Josh Coalson's avatar
Josh Coalson committed
595
		decoder->guts->seek_table.data.seek_table.num_points = real_points;
596
597
598

		decoder->guts->has_seek_table = true;
		decoder->guts->metadata_callback(decoder, &decoder->guts->seek_table, decoder->guts->client_data);
Josh Coalson's avatar
Josh Coalson committed
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
	}
	else {
		/* skip other metadata blocks */
		for(i = 0; i < length; i++) {
			if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
				return false; /* the read_callback_ sets the state for us */
		}
	}

	if(last_block)
		decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;

	return true;
}

bool stream_decoder_skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
{
	uint32 x;
	unsigned i, skip;

	/* skip the version and flags bytes */
	if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 24, read_callback_, decoder))
		return false; /* the read_callback_ sets the state for us */
	/* get the size (in bytes) to skip */
	skip = 0;
	for(i = 0; i < 4; i++) {
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
			return false; /* the read_callback_ sets the state for us */
		skip <<= 7;
		skip |= (x & 0x7f);
	}
	/* skip the rest of the tag */
	for(i = 0; i < skip; i++) {
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
			return false; /* the read_callback_ sets the state for us */
	}
	return true;
}

bool stream_decoder_frame_sync_(FLAC__StreamDecoder *decoder)
{
	uint32 x;
641
	bool first = true;
Josh Coalson's avatar
Josh Coalson committed
642
643
644

	/* If we know the total number of samples in the stream, stop if we've read that many. */
	/* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
645
646
	if(decoder->guts->has_stream_info && decoder->guts->stream_info.data.stream_info.total_samples) {
		if(decoder->guts->samples_decoded >= decoder->guts->stream_info.data.stream_info.total_samples) {
Josh Coalson's avatar
Josh Coalson committed
647
648
649
650
651
652
653
654
655
656
657
658
			decoder->state = FLAC__STREAM_DECODER_END_OF_STREAM;
			return true;
		}
	}

	/* make sure we're byte aligned */
	if(decoder->guts->input.consumed_bits != 0) {
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8-decoder->guts->input.consumed_bits, read_callback_, decoder))
			return false; /* the read_callback_ sets the state for us */
	}

	while(1) {
659
660
661
662
663
664
665
666
		if(decoder->guts->cached) {
			x = (uint32)decoder->guts->lookahead;
			decoder->guts->cached = false;
		}
		else {
			if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
				return false; /* the read_callback_ sets the state for us */
		}
Josh Coalson's avatar
Josh Coalson committed
667
		if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
668
669
			decoder->guts->header_warmup[0] = (byte)x;
			if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
670
				return false; /* the read_callback_ sets the state for us */
671
672
673
674
675
676
677
678
679

			/* 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 */
			/* else we have to check if the second byte is the end of a sync code */
			if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
				decoder->guts->lookahead = (byte)x;
				decoder->guts->cached = true;
			}
			else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
				decoder->guts->header_warmup[1] = (byte)x;
Josh Coalson's avatar
Josh Coalson committed
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
				decoder->state = FLAC__STREAM_DECODER_READ_FRAME;
				return true;
			}
		}
		if(first) {
			decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_LOST_SYNC, decoder->guts->client_data);
			first = 0;
		}
	}

	return true;
}

bool stream_decoder_read_frame_(FLAC__StreamDecoder *decoder, bool *got_a_frame)
{
	unsigned channel;
	unsigned i;
	int32 mid, side, left, right;
698
699
	uint16 frame_crc; /* the one we calculate from the input stream */
	uint32 x;
Josh Coalson's avatar
Josh Coalson committed
700
701
702

	*got_a_frame = false;

703
704
705
706
707
708
	/* init the CRC */
	frame_crc = 0;
	FLAC__CRC16_UPDATE(decoder->guts->header_warmup[0], frame_crc);
	FLAC__CRC16_UPDATE(decoder->guts->header_warmup[1], frame_crc);
	FLAC__bitbuffer_init_read_crc16(&decoder->guts->input, frame_crc);

Josh Coalson's avatar
Josh Coalson committed
709
710
	if(!stream_decoder_read_frame_header_(decoder))
		return false;
711
	if(decoder->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC)
Josh Coalson's avatar
Josh Coalson committed
712
		return true;
713
	if(!stream_decoder_allocate_output_(decoder, decoder->guts->frame.header.blocksize, decoder->guts->frame.header.channels))
Josh Coalson's avatar
Josh Coalson committed
714
		return false;
715
	for(channel = 0; channel < decoder->guts->frame.header.channels; channel++) {
716
717
718
719
720
721
722
723
724
		/*
		 * first figure the correct bits-per-sample of the subframe
		 */
		unsigned bps = decoder->guts->frame.header.bits_per_sample;
		switch(decoder->guts->frame.header.channel_assignment) {
			case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
				/* no adjustment needed */
				break;
			case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
725
				FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
726
727
728
729
				if(channel == 1)
					bps++;
				break;
			case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
730
				FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
731
732
733
734
				if(channel == 0)
					bps++;
				break;
			case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
735
				FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
736
737
738
739
				if(channel == 1)
					bps++;
				break;
			default:
740
				FLAC__ASSERT(0);
741
742
743
744
745
		}
		/*
		 * now read it
		 */
		if(!stream_decoder_read_subframe_(decoder, channel, bps))
Josh Coalson's avatar
Josh Coalson committed
746
747
748
749
750
751
752
753
754
			return false;
		if(decoder->state != FLAC__STREAM_DECODER_READ_FRAME) {
			decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
			return true;
		}
	}
	if(!stream_decoder_read_zero_padding_(decoder))
		return false;

755
756
757
758
759
760
761
762
763
764
765
766
767
	/*
	 * Read the frame CRC-16 from the footer and check
	 */
	frame_crc = decoder->guts->input.read_crc16;
	if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, FLAC__FRAME_FOOTER_CRC_LEN, read_callback_, decoder))
		return false; /* the read_callback_ sets the state for us */
	if(frame_crc == (uint16)x) {
		/* Undo any special channel coding */
		switch(decoder->guts->frame.header.channel_assignment) {
			case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
				/* do nothing */
				break;
			case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
768
				FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
769
770
771
772
				for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
					decoder->guts->output[1][i] = decoder->guts->output[0][i] - decoder->guts->output[1][i];
				break;
			case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
773
				FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
774
775
776
777
				for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
					decoder->guts->output[0][i] += decoder->guts->output[1][i];
				break;
			case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
778
				FLAC__ASSERT(decoder->guts->frame.header.channels == 2);
779
780
781
782
783
784
785
786
787
788
789
790
791
				for(i = 0; i < decoder->guts->frame.header.blocksize; i++) {
					mid = decoder->guts->output[0][i];
					side = decoder->guts->output[1][i];
					mid <<= 1;
					if(side & 1) /* i.e. if 'side' is odd... */
						mid++;
					left = mid + side;
					right = mid - side;
					decoder->guts->output[0][i] = left >> 1;
					decoder->guts->output[1][i] = right >> 1;
				}
				break;
			default:
792
				FLAC__ASSERT(0);
793
794
795
796
797
798
799
800
801
				break;
		}
	}
	else {
		/* Bad frame, emit error and zero the output signal */
		decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_FRAME_CRC_MISMATCH, decoder->guts->client_data);
		for(channel = 0; channel < decoder->guts->frame.header.channels; channel++) {
			memset(decoder->guts->output[channel], 0, sizeof(int32) * decoder->guts->frame.header.blocksize);
		}
Josh Coalson's avatar
Josh Coalson committed
802
803
804
805
806
	}

	*got_a_frame = true;

	/* put the latest values into the public section of the decoder instance */
807
808
809
810
811
	decoder->channels = decoder->guts->frame.header.channels;
	decoder->channel_assignment = decoder->guts->frame.header.channel_assignment;
	decoder->bits_per_sample = decoder->guts->frame.header.bits_per_sample;
	decoder->sample_rate = decoder->guts->frame.header.sample_rate;
	decoder->blocksize = decoder->guts->frame.header.blocksize;
Josh Coalson's avatar
Josh Coalson committed
812

Josh Coalson's avatar
Josh Coalson committed
813
	decoder->guts->samples_decoded = decoder->guts->frame.header.number.sample_number + decoder->guts->frame.header.blocksize;
Josh Coalson's avatar
Josh Coalson committed
814
815

	/* write it */
816
	/* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 3 here: */
817
	if(decoder->guts->write_callback(decoder, &decoder->guts->frame, decoder->guts->output, decoder->guts->client_data) != FLAC__STREAM_DECODER_WRITE_CONTINUE)
Josh Coalson's avatar
Josh Coalson committed
818
819
820
821
822
823
824
825
826
827
828
		return false;

	decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
	return true;
}

bool stream_decoder_read_frame_header_(FLAC__StreamDecoder *decoder)
{
	uint32 x;
	uint64 xx;
	unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
829
	byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
Josh Coalson's avatar
Josh Coalson committed
830
831
	unsigned raw_header_len;
	bool is_unparseable = false;
832
833
	const bool is_known_variable_blocksize_stream = (decoder->guts->has_stream_info && decoder->guts->stream_info.data.stream_info.min_blocksize != decoder->guts->stream_info.data.stream_info.max_blocksize);
	const bool is_known_fixed_blocksize_stream = (decoder->guts->has_stream_info && decoder->guts->stream_info.data.stream_info.min_blocksize == decoder->guts->stream_info.data.stream_info.max_blocksize);
Josh Coalson's avatar
Josh Coalson committed
834

835
	FLAC__ASSERT(decoder->guts->input.consumed_bits == 0); /* make sure we're byte aligned */
Josh Coalson's avatar
Josh Coalson committed
836

837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
	/* init the raw header with the saved bits from synchronization */
	raw_header[0] = decoder->guts->header_warmup[0];
	raw_header[1] = decoder->guts->header_warmup[1];
	raw_header_len = 2;

	/*
	 * check to make sure that the reserved bits are 0
	 */
	if(raw_header[1] & 0x03) { /* MAGIC NUMBER */
		is_unparseable = true;
	}

	/*
	 * Note that along the way as we read the header, we look for a sync
	 * code inside.  If we find one it would indicate that our original
	 * sync was bad since there cannot be a sync code in a valid header.
	 */
Josh Coalson's avatar
Josh Coalson committed
854
855
856
857
858
859
860

	/*
	 * read in the raw header as bytes so we can CRC it, and parse it on the way
	 */
	for(i = 0; i < 2; i++) {
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
			return false; /* the read_callback_ sets the state for us */
861
		if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
Josh Coalson's avatar
Josh Coalson committed
862
			/* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
863
864
865
866
867
			decoder->guts->lookahead = (byte)x;
			decoder->guts->cached = true;
			decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
			decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
			return true;
Josh Coalson's avatar
Josh Coalson committed
868
869
870
871
		}
		raw_header[raw_header_len++] = (byte)x;
	}

872
	switch(x = raw_header[2] >> 4) {
Josh Coalson's avatar
Josh Coalson committed
873
		case 0:
874
			if(is_known_fixed_blocksize_stream)
875
				decoder->guts->frame.header.blocksize = decoder->guts->stream_info.data.stream_info.min_blocksize;
Josh Coalson's avatar
Josh Coalson committed
876
877
878
879
			else
				is_unparseable = true;
			break;
		case 1:
880
			decoder->guts->frame.header.blocksize = 192;
Josh Coalson's avatar
Josh Coalson committed
881
882
883
884
885
			break;
		case 2:
		case 3:
		case 4:
		case 5:
886
			decoder->guts->frame.header.blocksize = 576 << (x-2);
Josh Coalson's avatar
Josh Coalson committed
887
888
889
890
891
			break;
		case 6:
		case 7:
			blocksize_hint = x;
			break;
892
893
894
895
896
897
898
899
900
901
		case 8:
		case 9:
		case 10:
		case 11:
		case 12:
		case 13:
		case 14:
		case 15:
			decoder->guts->frame.header.blocksize = 256 << (x-8);
			break;
Josh Coalson's avatar
Josh Coalson committed
902
		default:
903
			FLAC__ASSERT(0);
Josh Coalson's avatar
Josh Coalson committed
904
905
906
			break;
	}

907
	switch(x = raw_header[2] & 0x0f) {
Josh Coalson's avatar
Josh Coalson committed
908
		case 0:
909
910
			if(decoder->guts->has_stream_info)
				decoder->guts->frame.header.sample_rate = decoder->guts->stream_info.data.stream_info.sample_rate;
Josh Coalson's avatar
Josh Coalson committed
911
912
913
914
915
916
917
918
919
			else
				is_unparseable = true;
			break;
		case 1:
		case 2:
		case 3:
			is_unparseable = true;
			break;
		case 4:
920
			decoder->guts->frame.header.sample_rate = 8000;
Josh Coalson's avatar
Josh Coalson committed
921
922
			break;
		case 5:
923
			decoder->guts->frame.header.sample_rate = 16000;
Josh Coalson's avatar
Josh Coalson committed
924
925
			break;
		case 6:
926
			decoder->guts->frame.header.sample_rate = 22050;
Josh Coalson's avatar
Josh Coalson committed
927
928
			break;
		case 7:
929
			decoder->guts->frame.header.sample_rate = 24000;
Josh Coalson's avatar
Josh Coalson committed
930
931
			break;
		case 8:
932
			decoder->guts->frame.header.sample_rate = 32000;
Josh Coalson's avatar
Josh Coalson committed
933
934
			break;
		case 9:
935
			decoder->guts->frame.header.sample_rate = 44100;
Josh Coalson's avatar
Josh Coalson committed
936
937
			break;
		case 10:
938
			decoder->guts->frame.header.sample_rate = 48000;
Josh Coalson's avatar
Josh Coalson committed
939
940
			break;
		case 11:
941
			decoder->guts->frame.header.sample_rate = 96000;
Josh Coalson's avatar
Josh Coalson committed
942
943
944
945
946
947
948
			break;
		case 12:
		case 13:
		case 14:
			sample_rate_hint = x;
			break;
		case 15:
949
			decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
Josh Coalson's avatar
Josh Coalson committed
950
951
952
			decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
			return true;
		default:
953
			FLAC__ASSERT(0);
Josh Coalson's avatar
Josh Coalson committed
954
955
	}

956
	x = (unsigned)(raw_header[3] >> 4);
Josh Coalson's avatar
Josh Coalson committed
957
	if(x & 8) {
958
		decoder->guts->frame.header.channels = 2;
Josh Coalson's avatar
Josh Coalson committed
959
960
		switch(x & 7) {
			case 0:
961
				decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
Josh Coalson's avatar
Josh Coalson committed
962
963
				break;
			case 1:
964
				decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
Josh Coalson's avatar
Josh Coalson committed
965
966
				break;
			case 2:
967
				decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
Josh Coalson's avatar
Josh Coalson committed
968
969
970
971
972
973
974
				break;
			default:
				is_unparseable = true;
				break;
		}
	}
	else {
975
976
		decoder->guts->frame.header.channels = (unsigned)x + 1;
		decoder->guts->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
Josh Coalson's avatar
Josh Coalson committed
977
978
	}

979
	switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
Josh Coalson's avatar
Josh Coalson committed
980
		case 0:
981
982
			if(decoder->guts->has_stream_info)
				decoder->guts->frame.header.bits_per_sample = decoder->guts->stream_info.data.stream_info.bits_per_sample;
Josh Coalson's avatar
Josh Coalson committed
983
984
985
986
			else
				is_unparseable = true;
			break;
		case 1:
987
			decoder->guts->frame.header.bits_per_sample = 8;
Josh Coalson's avatar
Josh Coalson committed
988
989
			break;
		case 2:
990
			decoder->guts->frame.header.bits_per_sample = 12;
Josh Coalson's avatar
Josh Coalson committed
991
992
			break;
		case 4:
993
			decoder->guts->frame.header.bits_per_sample = 16;
Josh Coalson's avatar
Josh Coalson committed
994
995
			break;
		case 5:
996
			decoder->guts->frame.header.bits_per_sample = 20;
Josh Coalson's avatar
Josh Coalson committed
997
998
			break;
		case 6:
999
			decoder->guts->frame.header.bits_per_sample = 24;
Josh Coalson's avatar
Josh Coalson committed
1000
1001
1002
1003
1004
1005
			break;
		case 3:
		case 7:
			is_unparseable = true;
			break;
		default:
1006
			FLAC__ASSERT(0);
Josh Coalson's avatar
Josh Coalson committed
1007
1008
1009
			break;
	}

1010
1011
	if(raw_header[3] & 0x01) { /* this should be a zero padding bit */
		decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
Josh Coalson's avatar
Josh Coalson committed
1012
1013
1014
1015
		decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
		return true;
	}

1016
	if(blocksize_hint && is_known_variable_blocksize_stream) {
Josh Coalson's avatar
Josh Coalson committed
1017
1018
		if(!FLAC__bitbuffer_read_utf8_uint64(&decoder->guts->input, &xx, read_callback_, decoder, raw_header, &raw_header_len))
			return false; /* the read_callback_ sets the state for us */
1019
1020
1021
1022
1023
1024
		if(xx == 0xffffffffffffffff) { /* i.e. non-UTF8 code... */
			decoder->guts->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
			decoder->guts->cached = true;
			decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
			decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
			return true;
Josh Coalson's avatar
Josh Coalson committed
1025
		}
1026
		decoder->guts->frame.header.number.sample_number = xx;
Josh Coalson's avatar
Josh Coalson committed
1027
1028
1029
1030
	}
	else {
		if(!FLAC__bitbuffer_read_utf8_uint32(&decoder->guts->input, &x, read_callback_, decoder, raw_header, &raw_header_len))
			return false; /* the read_callback_ sets the state for us */
1031
1032
1033
1034
1035
1036
		if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
			decoder->guts->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
			decoder->guts->cached = true;
			decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
			decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
			return true;
Josh Coalson's avatar
Josh Coalson committed
1037
1038
		}
		decoder->guts->last_frame_number = x;
1039
1040
		if(decoder->guts->has_stream_info) {
			decoder->guts->frame.header.number.sample_number = (int64)decoder->guts->stream_info.data.stream_info.min_blocksize * (int64)x;
Josh Coalson's avatar
Josh Coalson committed
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
		}
		else {
			is_unparseable = true;
		}
	}

	if(blocksize_hint) {
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
			return false; /* the read_callback_ sets the state for us */
		raw_header[raw_header_len++] = (byte)x;
		if(blocksize_hint == 7) {
			uint32 _x;
			if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &_x, 8, read_callback_, decoder))
				return false; /* the read_callback_ sets the state for us */
			raw_header[raw_header_len++] = (byte)_x;
			x = (x << 8) | _x;
		}
1058
		decoder->guts->frame.header.blocksize = x+1;
Josh Coalson's avatar
Josh Coalson committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
	}

	if(sample_rate_hint) {
		if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
			return false; /* the read_callback_ sets the state for us */
		raw_header[raw_header_len++] = (byte)x;
		if(sample_rate_hint != 12) {
			uint32 _x;
			if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &_x, 8, read_callback_, decoder))
				return false; /* the read_callback_ sets the state for us */
			raw_header[raw_header_len++] = (byte)_x;
			x = (x << 8) | _x;
		}
		if(sample_rate_hint == 12)
1073
			decoder->guts->frame.header.sample_rate = x*1000;
Josh Coalson's avatar
Josh Coalson committed
1074
		else if(sample_rate_hint == 13)
1075
			decoder->guts->frame.header.sample_rate = x;
Josh Coalson's avatar
Josh Coalson committed
1076
		else
1077
			decoder->guts->frame.header.sample_rate = x*10;
Josh Coalson's avatar
Josh Coalson committed
1078
1079
	}

1080
	/* read the CRC-8 byte */
Josh Coalson's avatar
Josh Coalson committed
1081
1082
	if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder))
		return false; /* the read_callback_ sets the state for us */
1083
	crc8 = (byte)x;
Josh Coalson's avatar
Josh Coalson committed
1084

1085
1086
	if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
		decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_BAD_HEADER, decoder->guts->client_data);
Josh Coalson's avatar
Josh Coalson committed
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
		decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
		return true;
	}

	if(is_unparseable) {
		decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
		return false;
	}

	return true;
}

1099
bool stream_decoder_read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps)
Josh Coalson's avatar
Josh Coalson committed
1100
1101
{
	uint32 x;
1102
	bool wasted_bits;
Josh Coalson's avatar
Josh Coalson committed
1103

1104
	if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &x, 8, read_callback_, decoder)) /* MAGIC NUMBER */
Josh Coalson's avatar
Josh Coalson committed
1105
		return false; /* the read_callback_ sets the state for us */
1106
1107
1108
1109
1110
1111
1112
1113
1114

	wasted_bits = (x & 1);
	x &= 0xfe;

	if(wasted_bits) {
		unsigned u;
		if(!FLAC__bitbuffer_read_unary_unsigned(&decoder->guts->input, &u, read_callback_, decoder))
			return false; /* the read_callback_ sets the state for us */
		decoder->guts->frame.subframes[channel].wasted_bits = u+1;
1115
		bps -= decoder->guts->frame.subframes[channel].wasted_bits;
1116
1117
1118
1119
	}
	else
		decoder->guts->frame.subframes[channel].wasted_bits = 0;

1120
1121
1122
	/*
	 * Lots of magic numbers here
	 */
1123
	if(x & 0x80) {
Josh Coalson's avatar
Josh Coalson committed
1124
1125
1126
1127
1128
		decoder->guts->error_callback(decoder, FLAC__STREAM_DECODER_ERROR_LOST_SYNC, decoder->guts->client_data);
		decoder->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
		return true;
	}
	else if(x == 0) {
1129
1130
		if(!stream_decoder_read_subframe_constant_(decoder, channel, bps))
			return false;
Josh Coalson's avatar
Josh Coalson committed
1131
1132
	}
	else if(x == 2) {
1133
1134
		if(!stream_decoder_read_subframe_verbatim_(decoder, channel, bps))
			return false;
Josh Coalson's avatar
Josh Coalson committed
1135
1136
1137
1138
1139
1140
	}
	else if(x < 16) {
		decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
		return false;
	}
	else if(x <= 24) {
1141
1142
		if(!stream_decoder_read_subframe_fixed_(decoder, channel, bps, (x>>1)&7))
			return false;
Josh Coalson's avatar
Josh Coalson committed
1143
1144
1145
1146
1147
1148
	}
	else if(x < 64) {
		decoder->state = FLAC__STREAM_DECODER_UNPARSEABLE_STREAM;
		return false;
	}
	else {
1149
1150
		if(!stream_decoder_read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1))
			return false;
Josh Coalson's avatar
Josh Coalson committed
1151
	}
1152
1153

	if(wasted_bits) {
1154
1155
1156
1157
		unsigned i;
		x = decoder->guts->frame.subframes[channel].wasted_bits;
		for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
			decoder->guts->output[channel][i] <<= x;
1158
	}
1159

1160
	return true;
Josh Coalson's avatar
Josh Coalson committed
1161
1162
}

1163
bool stream_decoder_read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps)
Josh Coalson's avatar
Josh Coalson committed
1164
{
1165
	FLAC__Subframe_Constant *subframe = &decoder->guts->frame.subframes[channel].data.constant;
Josh Coalson's avatar
Josh Coalson committed
1166
1167
	int32 x;
	unsigned i;
1168
	int32 *output = decoder->guts->output[channel];
Josh Coalson's avatar
Josh Coalson committed
1169

1170
1171
	decoder->guts->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;

1172
	if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &x, bps, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
1173
1174
		return false; /* the read_callback_ sets the state for us */

1175
1176
1177
1178
1179
	subframe->value = x;

	/* decode the subframe */
	for(i = 0; i < decoder->guts->frame.header.blocksize; i++)
		output[i] = x;
Josh Coalson's avatar
Josh Coalson committed
1180
1181
1182
1183

	return true;
}

1184
bool stream_decoder_read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order)
Josh Coalson's avatar
Josh Coalson committed
1185
{
1186
	FLAC__Subframe_Fixed *subframe = &decoder->guts->frame.subframes[channel].data.fixed;
Josh Coalson's avatar
Josh Coalson committed
1187
1188
1189
1190
	int32 i32;
	uint32 u32;
	unsigned u;

1191
1192
1193
1194
	decoder->guts->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;

	subframe->residual = decoder->guts->residual[channel];
	subframe->order = order;
Josh Coalson's avatar
Josh Coalson committed
1195
1196
1197

	/* read warm-up samples */
	for(u = 0; u < order; u++) {
1198
		if(!FLAC__bitbuffer_read_raw_int32(&decoder->guts->input, &i32, bps, read_callback_, decoder))
Josh Coalson's avatar
Josh Coalson committed
1199
			return false; /* the read_callback_ sets the state for us */
1200
		subframe->warmup[u] = i32;
Josh Coalson's avatar
Josh Coalson committed
1201
1202
1203
1204
1205
	}

	/* read entropy coding method info */
	if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN, read_callback_, decoder))
		return false; /* the read_callback_ sets the state for us */
1206
1207
	subframe->entropy_coding_method.type = u32;
	switch(subframe->entropy_coding_method.type) {
Josh Coalson's avatar
Josh Coalson committed
1208
1209
1210
		case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
			if(!FLAC__bitbuffer_read_raw_uint32(&decoder->guts->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN, read_callback_, decoder))
				return false; /* the read_callback_ sets the state for us */