encode.c 116 KB
Newer Older
Josh Coalson's avatar
Josh Coalson committed
1
/* flac - Command-line FLAC encoder/decoder
2
 * Copyright (C) 2000-2009  Josh Coalson
3
 * Copyright (C) 2011-2016  Xiph.Org Foundation
Josh Coalson's avatar
Josh Coalson committed
4
5
6
7
8
9
10
11
12
13
14
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
Miroslav Lichvar's avatar
Miroslav Lichvar committed
15
16
17
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Josh Coalson's avatar
Josh Coalson committed
18
19
 */

20
#ifdef HAVE_CONFIG_H
Josh Coalson's avatar
Josh Coalson committed
21
22
23
24
#  include <config.h>
#endif

#include <errno.h>
25
#include <limits.h> /* for LONG_MAX */
26
#include <math.h> /* for floor() */
Josh Coalson's avatar
Josh Coalson committed
27
#include <stdio.h> /* for FILE etc. */
Josh Coalson's avatar
Josh Coalson committed
28
#include <stdlib.h> /* for malloc */
29
#include <string.h> /* for strcmp(), strerror() */
30
#include <sys/stat.h>
Josh Coalson's avatar
Josh Coalson committed
31
#include "FLAC/all.h"
32
#include "share/alloc.h"
33
#include "share/grabbag.h"
34
#include "share/compat.h"
35
#include "share/private.h"
36
#include "share/safe_str.h"
Josh Coalson's avatar
Josh Coalson committed
37
#include "encode.h"
38

Josh Coalson's avatar
Josh Coalson committed
39
40
41
42
#ifdef min
#undef min
#endif
#define min(x,y) ((x)<(y)?(x):(y))
43
44
45
46
#ifdef max
#undef max
#endif
#define max(x,y) ((x)>(y)?(x):(y))
Josh Coalson's avatar
Josh Coalson committed
47

Josh Coalson's avatar
Josh Coalson committed
48
/* this MUST be >= 588 so that sector aligning can take place with one read */
Josh Coalson's avatar
Josh Coalson committed
49
/* this MUST be < 2^sizeof(size_t) / ( FLAC__MAX_CHANNELS * (FLAC__MAX_BITS_PER_SAMPLE/8) ) */
Josh Coalson's avatar
Josh Coalson committed
50
51
#define CHUNK_OF_SAMPLES 2048

52
typedef struct {
53
54
55
56
57
	uint32_t sample_rate;
	uint32_t channels;
	uint32_t bits_per_sample; /* width of sample point, including 'shift' bits, valid bps is bits_per_sample-shift */
	uint32_t shift; /* # of LSBs samples have been shifted left by */
	uint32_t bytes_per_wide_sample; /* for convenience, always == channels*((bps+7)/8), or 0 if N/A to input format (like FLAC) */
58
59
60
61
62
63
64
	FLAC__bool is_unsigned_samples;
	FLAC__bool is_big_endian;
	FLAC__uint32 channel_mask;
} SampleInfo;

/* this is the client_data attached to the FLAC decoder when encoding from a FLAC file */
typedef struct {
65
	FLAC__off_t filesize;
66
	const FLAC__byte *lookahead;
67
	uint32_t lookahead_length;
68
69
70
71
72
73
	size_t num_metadata_blocks;
	FLAC__StreamMetadata *metadata_blocks[1024]; /*@@@ BAD MAGIC number */
	FLAC__uint64 samples_left_to_process;
	FLAC__bool fatal_error;
} FLACDecoderData;

Josh Coalson's avatar
Josh Coalson committed
74
typedef struct {
75
#if FLAC__HAS_OGG
Josh Coalson's avatar
Josh Coalson committed
76
77
	FLAC__bool use_ogg;
#endif
Josh Coalson's avatar
Josh Coalson committed
78
	FLAC__bool verify;
79
	FLAC__bool is_stdout;
80
	FLAC__bool outputfile_opened; /* true if we successfully opened the output file and we want it to be deleted if there is an error */
Josh Coalson's avatar
Josh Coalson committed
81
	const char *inbasefilename;
82
	const char *infilename;
Josh Coalson's avatar
Josh Coalson committed
83
84
	const char *outfilename;

85
	FLAC__bool treat_warnings_as_errors;
86
	FLAC__bool continue_through_decode_errors;
87
	FLAC__bool replay_gain;
88
89
	FLAC__uint64 total_samples_to_encode; /* (i.e. "wide samples" aka "sample frames") WATCHOUT: may be 0 to mean 'unknown' */
	FLAC__uint64 unencoded_size; /* an estimate of the input size, only used in the progress indicator */
Josh Coalson's avatar
Josh Coalson committed
90
91
	FLAC__uint64 bytes_written;
	FLAC__uint64 samples_written;
92
93
	uint32_t stats_frames_interval;
	uint32_t old_frames_written;
Josh Coalson's avatar
Josh Coalson committed
94

95
96
97
98
99
	SampleInfo info;

	FileFormat format;
	union {
		struct {
Josh Coalson's avatar
Josh Coalson committed
100
			FLAC__uint64 data_bytes;
101
102
103
104
105
106
107
		} iff;
		struct {
			FLAC__StreamDecoder *decoder;
			FLACDecoderData client_data;
		} flac;
	} fmt;

108
	FLAC__StreamEncoder *encoder;
Josh Coalson's avatar
Josh Coalson committed
109
110
111

	FILE *fin;
	FLAC__StreamMetadata *seek_table_template;
112
	double progress, compression_ratio;
Josh Coalson's avatar
Josh Coalson committed
113
} EncoderSession;
Josh Coalson's avatar
Josh Coalson committed
114

115
const int FLAC_ENCODE__DEFAULT_PADDING = 8192;
Josh Coalson's avatar
Josh Coalson committed
116

117
static FLAC__bool is_big_endian_host_;
Josh Coalson's avatar
Josh Coalson committed
118

119
#define UBUFFER_INT8_SIZE 0x10000
120
121

static union {
122
123
124
125
126
	FLAC__int8 s8[UBUFFER_INT8_SIZE];
	FLAC__uint8 u8[UBUFFER_INT8_SIZE];
	FLAC__int16 s16[UBUFFER_INT8_SIZE/2];
	FLAC__uint16 u16[UBUFFER_INT8_SIZE/2];
} ubuffer;
127

Josh Coalson's avatar
Josh Coalson committed
128

129
130
131
132
133
134
135
static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
static FLAC__int32 *input_[FLAC__MAX_CHANNELS];


/*
 * local routines
 */
136
static FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, FLAC__off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, uint32_t lookahead_length);
137
static void EncoderSession_destroy(EncoderSession *e);
138
static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero, foreign_metadata_t *foreign_metadata, FLAC__bool error_on_compression_fail);
139
static int EncoderSession_finish_error(EncoderSession *e);
140
static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options);
141
static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], uint32_t samples);
142
static FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e);
143
static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
144
145
146
147
static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, uint32_t sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, uint32_t num_metadata);
static FLAC__bool format_input(FLAC__int32 *dest[], uint32_t wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, uint32_t channels, uint32_t bps, uint32_t shift, size_t *channel_map);
static void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, uint32_t frames_written, uint32_t total_frames_estimate, void *client_data);
148
static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
149
150
151
152
153
154
155
static FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
static FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
static FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data);
static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
static void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
static void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
156
static FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, uint32_t sample_rate, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors);
Josh Coalson's avatar
Josh Coalson committed
157
static void print_stats(const EncoderSession *encoder_session);
158
static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
159
160
static void print_error_with_state(const EncoderSession *e, const char *message);
static void print_verify_error(EncoderSession *e);
161
162
163
static FLAC__bool read_bytes(FILE *f, FLAC__byte *buf, size_t n, FLAC__bool eof_ok, const char *fn);
static FLAC__bool read_uint16(FILE *f, FLAC__bool big_endian, FLAC__uint16 *val, const char *fn);
static FLAC__bool read_uint32(FILE *f, FLAC__bool big_endian, FLAC__uint32 *val, const char *fn);
Josh Coalson's avatar
Josh Coalson committed
164
static FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn);
165
static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn);
166
static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
167
static uint32_t count_channel_mask_bits(FLAC__uint32 mask);
Josh Coalson's avatar
Josh Coalson committed
168
#if 0
169
static FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, uint32_t channels);
Josh Coalson's avatar
Josh Coalson committed
170
#endif
Josh Coalson's avatar
Josh Coalson committed
171

172
static FLAC__bool get_sample_info_raw(EncoderSession *e, encode_options_t options)
173
{
174
175
176
177
178
179
180
181
	e->info.sample_rate = options.format_options.raw.sample_rate;
	e->info.channels = options.format_options.raw.channels;
	e->info.bits_per_sample = options.format_options.raw.bps;
	e->info.shift = 0;
	e->info.bytes_per_wide_sample = options.format_options.raw.channels * ((options.format_options.raw.bps+7)/8);
	e->info.is_unsigned_samples = options.format_options.raw.is_unsigned_samples;
	e->info.is_big_endian = options.format_options.raw.is_big_endian;
	e->info.channel_mask = 0;
182

183
184
	return true;
}
185

186
187
static FLAC__bool get_sample_info_wave(EncoderSession *e, encode_options_t options)
{
Josh Coalson's avatar
Josh Coalson committed
188
	FLAC__bool got_fmt_chunk = false, got_data_chunk = false, got_ds64_chunk = false;
189
	uint32_t sample_rate = 0, channels = 0, bps = 0, shift = 0;
190
	FLAC__uint32 channel_mask = 0;
Josh Coalson's avatar
Josh Coalson committed
191
	FLAC__uint64 ds64_data_size = 0;
192

193
194
	e->info.is_unsigned_samples = false;
	e->info.is_big_endian = false;
195

196
197
	if(e->format == FORMAT_WAVE64) {
		/*
198
		 * lookahead[] already has "riff\x2E\x91\xCF\x11\xA5\xD6\x28\xDB", skip over remaining header
199
200
201
202
203
204
205
206
		 */
		if(!fskip_ahead(e->fin, 16+8+16-12)) { /* riff GUID + riff size + WAVE GUID - lookahead */
			flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over remaining \"riff\" header\n", e->inbasefilename);
			return false;
		}
	}
	/* else lookahead[] already has "RIFFxxxxWAVE" or "RF64xxxxWAVE" */

207
	while(!feof(e->fin) && !got_data_chunk) {
208
209
210
211
212
		/* chunk IDs are 4 bytes for WAVE/RF64, 16 for Wave64 */
		/* for WAVE/RF64 we want the 5th char zeroed so we can treat it like a C string */
		char chunk_id[16] = { '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' };

		if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, e->format==FORMAT_WAVE64?16:4, /*eof_ok=*/true, e->inbasefilename)) {
213
214
			flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename);
			return false;
215
		}
216
		if(feof(e->fin))
217
			break;
218

219
		if(e->format == FORMAT_RF64 && !memcmp(chunk_id, "ds64", 4)) { /* RF64 64-bit sizes chunk */
Josh Coalson's avatar
Josh Coalson committed
220
221
222
223
224
225
			FLAC__uint32 xx, data_bytes;

			if(got_ds64_chunk) {
				flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'ds64' chunks\n", e->inbasefilename);
				return false;
			}
226
			if(got_fmt_chunk) {
Josh Coalson's avatar
Josh Coalson committed
227
228
229
230
231
232
233
234
235
				flac__utils_printf(stderr, 1, "%s: ERROR: 'ds64' chunk appears after 'fmt ' or 'data' chunk\n", e->inbasefilename);
				return false;
			}

			/* ds64 chunk size */
			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
				return false;
			data_bytes = xx;
			if(data_bytes < 28) {
236
				flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'ds64' chunk has length = %u\n", e->inbasefilename, (uint32_t)data_bytes);
Josh Coalson's avatar
Josh Coalson committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
				return false;
			}
			if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */
				data_bytes++;

			/* RIFF 64-bit size, lo/hi */
			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
				return false;
			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
				return false;

			/* 'data' 64-bit size */
			if(!read_uint64(e->fin, /*big_endian=*/false, &ds64_data_size, e->inbasefilename))
				return false;

			data_bytes -= 16;

			/* skip any extra data in the ds64 chunk */
			if(!fskip_ahead(e->fin, data_bytes)) {
				flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'ds64' data\n", e->inbasefilename);
				return false;
			}

			got_ds64_chunk = true;
		}
262
263
		else if(
			!memcmp(chunk_id, "fmt ", 4) &&
264
			(e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "fmt \xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 16))
265
		) { /* format chunk */
266
			FLAC__uint16 x;
Josh Coalson's avatar
Josh Coalson committed
267
			FLAC__uint32 xx, data_bytes;
268
			FLAC__uint16 wFormatTag; /* wFormatTag word from the 'fmt ' chunk */
269

270
271
272
			if(got_fmt_chunk) {
				flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'fmt ' chunks\n", e->inbasefilename);
				return false;
273
274
			}

275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
			/* see
			 *   http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
			 *   http://windowssdk.msdn.microsoft.com/en-us/library/ms713497.aspx
			 *   http://msdn.microsoft.com/library/default.asp?url=/library/en-us/audio_r/hh/Audio_r/aud-prop_d40f094e-44f9-4baa-8a15-03e4fb369501.xml.asp
			 *
			 * WAVEFORMAT is
			 * 4 byte: chunk size
			 * 2 byte: format type: 1 for WAVE_FORMAT_PCM, 65534 for WAVE_FORMAT_EXTENSIBLE
			 * 2 byte: # channels
			 * 4 byte: sample rate (Hz)
			 * 4 byte: avg bytes per sec
			 * 2 byte: block align
			 * 2 byte: bits per sample (not necessarily all significant)
			 * WAVEFORMATEX adds
			 * 2 byte: extension size in bytes (usually 0 for WAVEFORMATEX and 22 for WAVEFORMATEXTENSIBLE with PCM)
			 * WAVEFORMATEXTENSIBLE adds
			 * 2 byte: valid bits per sample
			 * 4 byte: channel mask
			 * 16 byte: subformat GUID, first 2 bytes have format type, 1 being PCM
			 *
			 * Current spec says WAVEFORMATEX with PCM must have bps == 8 or 16, or any multiple of 8 for WAVEFORMATEXTENSIBLE.
			 * Lots of old broken WAVEs/apps have don't follow it, e.g. 20 bps but a block align of 3/6 for mono/stereo.
			 *
			 * Block align for WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE is also supposed to be channels*bps/8
			 *
			 * If the channel mask has more set bits than # of channels, the extra MSBs are ignored.
			 * If the channel mask has less set bits than # of channels, the extra channels are unassigned to any speaker.
			 *
303
			 * Data is supposed to be uint32_t for bps <= 8 else signed.
304
			 */
305

306
307
308
309
			/* fmt chunk size */
			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
				return false;
			data_bytes = xx;
310
311
312
313
314
			if(e->format == FORMAT_WAVE64) {
				/* other half of the size field should be 0 */
				if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
					return false;
				if(xx) {
315
					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly large Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (uint32_t)xx, (uint32_t)data_bytes);
316
317
318
319
					return false;
				}
				/* subtract size of header */
				if (data_bytes < 16+8) {
320
					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (uint32_t)xx, (uint32_t)data_bytes);
321
322
323
324
					return false;
				}
				data_bytes -= (16+8);
			}
325
			if(data_bytes < 16) {
326
				flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'fmt ' chunk has length = %u\n", e->inbasefilename, (uint32_t)data_bytes);
327
				return false;
328
			}
329
330
331
332
333
334
335
			if(e->format != FORMAT_WAVE64) {
				if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */
					data_bytes++;
			}
			else { /* Wave64 */
				data_bytes = (data_bytes+7) & (~7u); /* should never happen, but enforce Wave64 alignment rules */
			}
336

337
338
339
340
			/* format code */
			if(!read_uint16(e->fin, /*big_endian=*/false, &wFormatTag, e->inbasefilename))
				return false;
			if(wFormatTag != 1 /*WAVE_FORMAT_PCM*/ && wFormatTag != 65534 /*WAVE_FORMAT_EXTENSIBLE*/) {
341
				flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", e->inbasefilename, (uint32_t)wFormatTag);
342
				return false;
343
			}
344

345
346
347
			/* number of channels */
			if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
				return false;
348
			channels = (uint32_t)x;
349

350
351
352
353
			/* sample rate */
			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
				return false;
			sample_rate = xx;
354

355
356
357
358
359
360
			/* avg bytes per second (ignored) */
			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
				return false;
			/* block align */
			if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
				return false;
Erik de Castro Lopo's avatar
Erik de Castro Lopo committed
361

362
363
364
			/* bits per sample */
			if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
				return false;
365
			bps = (uint32_t)x;
366

367
			e->info.is_unsigned_samples = (bps <= 8);
368

369
370
371
372
			if(wFormatTag == 1) {
				if(bps != 8 && bps != 16) {
					if(bps == 24 || bps == 32) {
						/* let these slide with a warning since they're unambiguous */
373
						flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (uint32_t)wFormatTag, bps);
374
375
376
377
378
						if(e->treat_warnings_as_errors)
							return false;
					}
					else {
						/* @@@ we could add an option to specify left- or right-justified blocks so we knew how to set 'shift' */
379
						flac__utils_printf(stderr, 1, "%s: ERROR: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (uint32_t)wFormatTag, bps);
380
381
						return false;
					}
382
				}
383
384
385
386
#if 0 /* @@@ reinstate once we can get an answer about whether the samples are left- or right-justified */
				if((bps+7)/8 * channels == block_align) {
					if(bps % 8) {
						/* assume legacy file is byte aligned with some LSBs zero; this is double-checked in format_input() */
387
						flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", e->inbasefilename, (uint32_t)wFormatTag, block_align, bps, channels);
388
389
390
391
392
393
394
						if(e->treat_warnings_as_errors)
							return false;
						shift = 8 - (bps % 8);
						bps += shift;
					}
					else
						shift = 0;
395
396
				}
				else {
397
					flac__utils_printf(stderr, 1, "%s: ERROR: illegal WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", e->inbasefilename, (uint32_t)wFormatTag, block_align, bps, channels);
398
					return false;
399
				}
400
401
402
#else
				shift = 0;
#endif
403
404
405
				if(channels > 2 && !options.channel_map_none) {
					flac__utils_printf(stderr, 1, "%s: ERROR: WAVE has >2 channels but is not WAVE_FORMAT_EXTENSIBLE; cannot assign channels\n", e->inbasefilename);
					return false;
406
				}
407
408
				FLAC__ASSERT(data_bytes >= 16);
				data_bytes -= 16;
409
			}
410
411
			else {
				if(data_bytes < 40) {
412
					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with size %u\n", e->inbasefilename, (uint32_t)data_bytes);
413
					return false;
414
415
				}
				/* cbSize */
416
417
				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
					return false;
418
				if(x < 22) {
419
					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with cbSize %u\n", e->inbasefilename, (uint32_t)x);
420
					return false;
421
422
				}
				/* valid bps */
423
424
				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
					return false;
425
426
				if((uint32_t)x > bps) {
					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", e->inbasefilename, (uint32_t)x, bps);
427
					return false;
428
				}
429
				shift = bps - (uint32_t)x;
430
				/* channel mask */
431
432
				if(!read_uint32(e->fin, /*big_endian=*/false, &channel_mask, e->inbasefilename))
					return false;
433
434
435
				/* for mono/stereo and unassigned channels, we fake the mask */
				if(channel_mask == 0) {
					if(channels == 1)
436
						channel_mask = 0x0004;
437
438
439
					else if(channels == 2)
						channel_mask = 0x0003;
				}
440
441
				/* set channel mapping */
				/* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
442
443
				/* front left, front right, front center, LFE, back left, back right, back center, side left, side right */
				/* the default mapping is sufficient for 1-8 channels */
444
445
446
#if 0
				/* @@@ example for dolby/vorbis order, for reference later in case it becomes important */
				if(
447
					options.channel_map_none ||
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
					channel_mask == 0x0001 || /* 1 channel: (mono) */
					channel_mask == 0x0003 || /* 2 channels: front left, front right */
					channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
					channel_mask == 0x0603    /* 4 channels: front left, front right, side left, side right */
				) {
					/* keep default channel order */
				}
				else if(
					channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
					channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
					channel_mask == 0x0607    /* 5 channels: front left, front right, front center, side left, side right */
				) {
					/* to dolby order: front left, center, front right [, surround left, surround right ] */
					channel_map[1] = 2;
					channel_map[2] = 1;
				}
				else if(
					channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
466
467
468
					channel_mask == 0x060f || /* 6 channels: front left, front right, front center, LFE, side left, side right */
					channel_mask == 0x070f || /* 7 channels: front left, front right, front center, LFE, back center, side left, side right */
					channel_mask == 0x063f    /* 8 channels: front left, front right, front center, LFE, back left, back right, side left, side right */
469
470
471
472
473
474
475
476
477
478
				) {
					/* to dolby order: front left, center, front right, surround left, surround right, LFE */
					channel_map[1] = 2;
					channel_map[2] = 1;
					channel_map[3] = 5;
					channel_map[4] = 3;
					channel_map[5] = 4;
				}
#else
				if(
479
					options.channel_map_none ||
480
481
482
					channel_mask == 0x0001 || /* 1 channel: front left */
					channel_mask == 0x0002 || /* 1 channel: front right */
					channel_mask == 0x0004 || /* 1 channel: mono or front center */
483
484
485
486
487
488
489
					channel_mask == 0x0003 || /* 2 channels: front left, front right */
					channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
					channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
					channel_mask == 0x0603 || /* 4 channels: front left, front right, side left, side right */
					channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
					channel_mask == 0x0607 || /* 5 channels: front left, front right, front center, side left, side right */
					channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
490
491
492
					channel_mask == 0x060f || /* 6 channels: front left, front right, front center, LFE, side left, side right */
					channel_mask == 0x070f || /* 7 channels: front left, front right, front center, LFE, back center, side left, side right */
					channel_mask == 0x063f    /* 8 channels: front left, front right, front center, LFE, back left, back right, side left, side right */
493
494
				) {
					/* keep default channel order */
495
				}
496
497
#endif
				else {
498
					flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk with unsupported channel mask=0x%04X\n\nUse --channel-map=none option to encode the input\n", e->inbasefilename, (uint32_t)channel_mask);
499
					return false;
500
				}
501
				if(!options.channel_map_none) {
502
					if(count_channel_mask_bits(channel_mask) < channels) {
503
						flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has unassigned channels (#channels=%u)\n", e->inbasefilename, (uint32_t)channel_mask, channels);
504
						return false;
505
506
507
508
509
510
511
512
513
514
					}
#if 0
					/* supporting this is too difficult with channel mapping; e.g. what if mask is 0x003f but #channels=4?
					 * there would be holes in the order that would have to be filled in, or the mask would have to be
					 * limited and the logic above rerun to see if it still fits into the FLAC mapping.
					 */
					else if(count_channel_mask_bits(channel_mask) > channels)
						channel_mask = limit_channel_mask(channel_mask, channels);
#else
					else if(count_channel_mask_bits(channel_mask) > channels) {
515
						flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has extra bits for non-existant channels (#channels=%u)\n", e->inbasefilename, (uint32_t)channel_mask, channels);
516
						return false;
517
518
519
					}
#endif
				}
520
				/* first part of GUID */
521
522
				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
					return false;
523
				if(x != 1) {
524
					flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE chunk with non-PCM format %u\n", e->inbasefilename, (uint32_t)x);
525
					return false;
526
527
528
529
				}
				data_bytes -= 26;
			}

530
			e->info.bytes_per_wide_sample = channels * (bps / 8);
531

532
			/* skip any extra data in the fmt chunk */
533
534
535
			if(!fskip_ahead(e->fin, data_bytes)) {
				flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'fmt' data\n", e->inbasefilename);
				return false;
536
537
538
539
			}

			got_fmt_chunk = true;
		}
540
541
		else if(
			!memcmp(chunk_id, "data", 4) &&
542
			(e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "data\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 16))
543
		) { /* data chunk */
544
			FLAC__uint32 xx;
Josh Coalson's avatar
Josh Coalson committed
545
			FLAC__uint64 data_bytes;
546

547
548
549
			if(!got_fmt_chunk) {
				flac__utils_printf(stderr, 1, "%s: ERROR: got 'data' chunk before 'fmt' chunk\n", e->inbasefilename);
				return false;
550
			}
551

552
			/* data size */
553
554
555
556
557
558
559
560
561
562
			if(e->format != FORMAT_WAVE64) {
				if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
					return false;
				data_bytes = xx;
			}
			else { /* Wave64 */
				if(!read_uint64(e->fin, /*big_endian=*/false, &data_bytes, e->inbasefilename))
					return false;
				/* subtract size of header */
				if (data_bytes < 16+8) {
563
					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'data' chunk has length = 0x00000000%08X\n", e->inbasefilename, (uint32_t)data_bytes);
564
565
566
567
568
					return false;
				}
				data_bytes -= (16+8);
			}
			if(e->format == FORMAT_RF64) {
Josh Coalson's avatar
Josh Coalson committed
569
570
571
572
573
574
575
				if(!got_ds64_chunk) {
					flac__utils_printf(stderr, 1, "%s: ERROR: RF64 file has no 'ds64' chunk before 'data' chunk\n", e->inbasefilename);
					return false;
				}
				if(data_bytes == 0xffffffff)
					data_bytes = ds64_data_size;
			}
576
577
			if(options.ignore_chunk_sizes) {
				FLAC__ASSERT(!options.sector_align);
Josh Coalson's avatar
Josh Coalson committed
578
579
				if(data_bytes) {
					flac__utils_printf(stderr, 1, "%s: WARNING: 'data' chunk has non-zero size, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id);
580
581
					if(e->treat_warnings_as_errors)
						return false;
582
				}
Josh Coalson's avatar
Josh Coalson committed
583
				data_bytes = (FLAC__uint64)0 - (FLAC__uint64)e->info.bytes_per_wide_sample; /* max out data_bytes; we'll use EOF as signal to stop reading */
584
			}
Josh Coalson's avatar
Josh Coalson committed
585
586
587
			else if(0 == data_bytes) {
				flac__utils_printf(stderr, 1, "%s: ERROR: 'data' chunk has size of 0\n", e->inbasefilename);
				return false;
588
			}
589

590
			e->fmt.iff.data_bytes = data_bytes;
591

592
			got_data_chunk = true;
593
			break;
594
595
		}
		else {
596
			FLAC__uint32 xx;
597
			FLAC__uint64 skip;
598
			if(!options.format_options.iff.foreign_metadata) {
599
600
601
602
603
				if(e->format != FORMAT_WAVE64)
					flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id);
				else
					flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk %02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X (use --keep-foreign-metadata to keep)\n",
						e->inbasefilename,
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
						(uint32_t)((const uint8_t *)chunk_id)[3],
						(uint32_t)((const uint8_t *)chunk_id)[2],
						(uint32_t)((const uint8_t *)chunk_id)[1],
						(uint32_t)((const uint8_t *)chunk_id)[0],
						(uint32_t)((const uint8_t *)chunk_id)[5],
						(uint32_t)((const uint8_t *)chunk_id)[4],
						(uint32_t)((const uint8_t *)chunk_id)[7],
						(uint32_t)((const uint8_t *)chunk_id)[6],
						(uint32_t)((const uint8_t *)chunk_id)[9],
						(uint32_t)((const uint8_t *)chunk_id)[8],
						(uint32_t)((const uint8_t *)chunk_id)[10],
						(uint32_t)((const uint8_t *)chunk_id)[11],
						(uint32_t)((const uint8_t *)chunk_id)[12],
						(uint32_t)((const uint8_t *)chunk_id)[13],
						(uint32_t)((const uint8_t *)chunk_id)[14],
						(uint32_t)((const uint8_t *)chunk_id)[15]
620
					);
621
622
				if(e->treat_warnings_as_errors)
					return false;
623
			}
624

625
			/* chunk size */
626
627
628
629
630
631
632
633
634
635
636
637
			if(e->format != FORMAT_WAVE64) {
				if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
					return false;
				skip = xx;
				skip += skip & 1;
			}
			else { /* Wave64 */
				if(!read_uint64(e->fin, /*big_endian=*/false, &skip, e->inbasefilename))
					return false;
				skip = (skip+7) & (~(FLAC__uint64)7);
				/* subtract size of header */
				if (skip < 16+8) {
638
					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 chunk has length = 0x00000000%08X\n", e->inbasefilename, (uint32_t)skip);
639
640
641
642
643
					return false;
				}
				skip -= (16+8);
			}
			if(skip) {
644
645
646
				if(!fskip_ahead(e->fin, skip)) {
					flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename);
					return false;
647
				}
648
			}
Josh Coalson's avatar
Josh Coalson committed
649
650
651
		}
	}

652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
	if(!got_fmt_chunk) {
		flac__utils_printf(stderr, 1, "%s: ERROR: didn't find fmt chunk\n", e->inbasefilename);
		return false;
	}
	if(!got_data_chunk) {
		flac__utils_printf(stderr, 1, "%s: ERROR: didn't find data chunk\n", e->inbasefilename);
		return false;
	}

	e->info.sample_rate = sample_rate;
	e->info.channels = channels;
	e->info.bits_per_sample = bps;
	e->info.shift = shift;
	e->info.channel_mask = channel_mask;

	return true;
Josh Coalson's avatar
Josh Coalson committed
668
669
}

670
static FLAC__bool get_sample_info_aiff(EncoderSession *e, encode_options_t options)
Josh Coalson's avatar
Josh Coalson committed
671
{
672
	FLAC__bool got_comm_chunk = false, got_ssnd_chunk = false;
673
	uint32_t sample_rate = 0, channels = 0, bps = 0, shift = 0;
Josh Coalson's avatar
Josh Coalson committed
674
	FLAC__uint64 sample_frames = 0;
675
676
677
678
	FLAC__uint32 channel_mask = 0;

	e->info.is_unsigned_samples = false;
	e->info.is_big_endian = true;
Josh Coalson's avatar
Josh Coalson committed
679

680
	/*
681
	 * lookahead[] already has "FORMxxxxAIFF", do chunks
682
	 */
683
684
685
686
687
688
689
690
	while(!feof(e->fin) && !got_ssnd_chunk) {
		char chunk_id[5] = { '\0', '\0', '\0', '\0', '\0' }; /* one extra byte for terminating NUL so we can also treat it like a C string */
		if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, 4, /*eof_ok=*/true, e->inbasefilename)) {
			flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename);
			return false;
		}
		if(feof(e->fin))
			break;
691

692
693
694
		if(!memcmp(chunk_id, "COMM", 4)) { /* common chunk */
			FLAC__uint16 x;
			FLAC__uint32 xx;
695
			uint64_t skip;
696
			const FLAC__bool is_aifc = e->format == FORMAT_AIFF_C;
697
			const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18);
698

699
700
701
702
			if(got_comm_chunk) {
				flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'COMM' chunks\n", e->inbasefilename);
				return false;
			}
Josh Coalson's avatar
Josh Coalson committed
703

704
705
706
707
			/* COMM chunk size */
			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
				return false;
			else if(xx < minimum_comm_size) {
708
				flac__utils_printf(stderr, 1, "%s: ERROR: non-standard %s 'COMM' chunk has length = %u\n", e->inbasefilename, is_aifc? "AIFF-C" : "AIFF", (uint32_t)xx);
709
710
711
				return false;
			}
			else if(!is_aifc && xx != minimum_comm_size) {
712
				flac__utils_printf(stderr, 1, "%s: WARNING: non-standard %s 'COMM' chunk has length = %u, expected %u\n", e->inbasefilename, is_aifc? "AIFF-C" : "AIFF", (uint32_t)xx, minimum_comm_size);
713
714
715
716
				if(e->treat_warnings_as_errors)
					return false;
			}
			skip = (xx-minimum_comm_size)+(xx & 1);
717

718
719
720
			/* number of channels */
			if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
				return false;
721
			channels = (uint32_t)x;
722
			if(channels > 2 && !options.channel_map_none) {
Josh Coalson's avatar
Josh Coalson committed
723
				flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
724
				return false;
725
			}
Josh Coalson's avatar
Josh Coalson committed
726

727
728
729
730
			/* number of sample frames */
			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
				return false;
			sample_frames = xx;
Josh Coalson's avatar
Josh Coalson committed
731

732
733
734
			/* bits per sample */
			if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
				return false;
735
			bps = (uint32_t)x;
736
737
			shift = (bps%8)? 8-(bps%8) : 0; /* SSND data is always byte-aligned, left-justified but format_input() will double-check */
			bps += shift;
738

739
740
741
742
			/* sample rate */
			if(!read_sane_extended(e->fin, &xx, e->inbasefilename))
				return false;
			sample_rate = xx;
743

744
745
746
747
748
749
750
751
752
753
754
			/* check compression type for AIFF-C */
			if(is_aifc) {
				if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
					return false;
				if(xx == 0x736F7774) /* "sowt" */
					e->info.is_big_endian = false;
				else if(xx == 0x4E4F4E45) /* "NONE" */
					; /* nothing to do, we already default to big-endian */
				else {
					flac__utils_printf(stderr, 1, "%s: ERROR: can't handle AIFF-C compression type \"%c%c%c%c\"\n", e->inbasefilename, (char)(xx>>24), (char)((xx>>16)&8), (char)((xx>>8)&8), (char)(xx&8));
					return false;
755
				}
756
757
			}

758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
			/* set channel mapping */
			/* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
			/* front left, front right, center, LFE, back left, back right, surround left, surround right */
			/* specs say the channel ordering is:
			 *                             1     2   3   4   5   6
			 * ___________________________________________________
			 * 2         stereo            l     r
			 * 3                           l     r   c
			 * 4                           l     c   r   S
			 * quad (ambiguous with 4ch)  Fl    Fr   Bl  Br
			 * 5                          Fl     Fr  Fc  Sl  Sr
			 * 6                           l     lc  c   r   rc  S
			 * l:left r:right c:center Fl:front-left Fr:front-right Bl:back-left Br:back-right Lc:left-center Rc:right-center S:surround
			 * so we only have unambiguous mappings for 2, 3, and 5 channels
			 */
			if(
				options.channel_map_none ||
				channels == 1 || /* 1 channel: (mono) */
				channels == 2 || /* 2 channels: left, right */
				channels == 3 || /* 3 channels: left, right, center */
				channels == 5    /* 5 channels: front left, front right, center, surround left, surround right */
			) {
				/* keep default channel order */
Josh Coalson's avatar
Josh Coalson committed
781
			}
782
			else {
Josh Coalson's avatar
Josh Coalson committed
783
				flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
784
785
				return false;
			}
786

787
788
789
790
791
792
			e->info.bytes_per_wide_sample = channels * (bps / 8);

			/* skip any extra data in the COMM chunk */
			if(!fskip_ahead(e->fin, skip)) {
				flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra COMM data\n", e->inbasefilename);
				return false;
793
			}
794
795

			got_comm_chunk = true;
Josh Coalson's avatar
Josh Coalson committed
796
		}
797
798
		else if(!memcmp(chunk_id, "SSND", 4) && !got_ssnd_chunk) { /* sound data chunk */
			FLAC__uint32 xx;
Josh Coalson's avatar
Josh Coalson committed
799
			FLAC__uint64 data_bytes;
800
			uint32_t offset = 0;
801
802
803
804

			if(!got_comm_chunk) {
				flac__utils_printf(stderr, 1, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", e->inbasefilename);
				return false;
805
			}
806

807
808
809
			/* SSND chunk size */
			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
				return false;
Josh Coalson's avatar
Josh Coalson committed
810
			data_bytes = xx;
811
812
			if(options.ignore_chunk_sizes) {
				FLAC__ASSERT(!options.sector_align);
Josh Coalson's avatar
Josh Coalson committed
813
814
				if(data_bytes) {
					flac__utils_printf(stderr, 1, "%s: WARNING: 'SSND' chunk has non-zero size, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id);
815
816
					if(e->treat_warnings_as_errors)
						return false;
817
				}
Josh Coalson's avatar
Josh Coalson committed
818
819
820
821
822
				data_bytes = (FLAC__uint64)0 - (FLAC__uint64)e->info.bytes_per_wide_sample; /* max out data_bytes; we'll use EOF as signal to stop reading */
			}
			else if(data_bytes <= 8) {
				flac__utils_printf(stderr, 1, "%s: ERROR: 'SSND' chunk has size <= 8\n", e->inbasefilename);
				return false;
823
824
			}
			else {
825
826
				data_bytes -= 8; /* discount the offset and block size fields */
			}
827

828
829
830
831
832
833
834
835
836
			/* offset */
			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
				return false;
			offset = xx;
			data_bytes -= offset;

			/* block size */
			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
				return false;
837
838
839
840
841
842
843
844
			if(xx && !options.ignore_chunk_sizes)
				data_bytes -= (xx - (data_bytes % xx));
			if(options.ignore_chunk_sizes) {
				if(xx) {
					flac__utils_printf(stderr, 1, "%s: WARNING: 'SSND' chunk has non-zero blocksize, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id);
					if(e->treat_warnings_as_errors)
						return false;
				}
845
846
847
848
849
850
851
			}

			/* skip any SSND offset bytes */
			if(!fskip_ahead(e->fin, offset)) {
				flac__utils_printf(stderr, 1, "%s: ERROR: skipping offset in SSND chunk\n", e->inbasefilename);
				return false;
			}
Josh Coalson's avatar
Josh Coalson committed
852

853
854
855
			e->fmt.iff.data_bytes = data_bytes;

			got_ssnd_chunk = true;
856
857
		}
		else {
858
859
860
861
862
863
864
865
866
867
868
			FLAC__uint32 xx;
			if(!options.format_options.iff.foreign_metadata) {
				flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id);
				if(e->treat_warnings_as_errors)
					return false;
			}

			/* chunk size */
			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
				return false;
			else {
869
				uint64_t skip = xx + (xx & 1);
870
871
872
873
874

				FLAC__ASSERT(skip <= LONG_MAX);
				if(!fskip_ahead(e->fin, skip)) {
					flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename);
					return false;
875
876
877
878
879
				}
			}
		}
	}

880
881
882
883
884
885
886
887
	if(!got_comm_chunk) {
		flac__utils_printf(stderr, 1, "%s: ERROR: didn't find COMM chunk\n", e->inbasefilename);
		return false;
	}
	if(!got_ssnd_chunk && sample_frames) {
		flac__utils_printf(stderr, 1, "%s: ERROR: didn't find SSND chunk\n", e->inbasefilename);
		return false;
	}
888

889
890
891
892
893
	e->info.sample_rate = sample_rate;
	e->info.channels = channels;
	e->info.bits_per_sample = bps;
	e->info.shift = shift;
	e->info.channel_mask = channel_mask;
894

895
896
	return true;
}
897

898
static FLAC__bool get_sample_info_flac(EncoderSession *e)
899
{
900
	if (!(
901
902
		FLAC__stream_decoder_set_md5_checking(e->fmt.flac.decoder, false) &&
		FLAC__stream_decoder_set_metadata_respond_all(e->fmt.flac.decoder)
903
	)) {
904
905
		flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", e->inbasefilename);
		return false;
906
907
	}

908
	if (e->format == FORMAT_OGGFLAC) {
909
910
911
		if (FLAC__stream_decoder_init_ogg_stream(e->fmt.flac.decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/e) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
			flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for Ogg FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder));
			return false;
912
913
		}
	}
914
915
916
	else if (FLAC__stream_decoder_init_stream(e->fmt.flac.decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/e) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
		flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder));
		return false;
917
918
	}

919
920
921
	if (!FLAC__stream_decoder_process_until_end_of_metadata(e->fmt.flac.decoder) || e->fmt.flac.client_data.fatal_error) {
		if (e->fmt.flac.client_data.fatal_error)
			flac__utils_printf(stderr, 1, "%s: ERROR: out of memory or too many metadata blocks while reading metadata in FLAC input\n", e->inbasefilename);
922
		else
923
924
			flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder));
		return false;
925
926
	}

927
928
929
	if (e->fmt.flac.client_data.num_metadata_blocks == 0) {
		flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, got no metadata blocks\n", e->inbasefilename);
		return false;
930
	}
931
932
933
	else if (e->fmt.flac.client_data.metadata_blocks[0]->type != FLAC__METADATA_TYPE_STREAMINFO) {
		flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, first metadata block is not STREAMINFO\n", e->inbasefilename);
		return false;
934
	}
935
936
937
	else if (e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples == 0) {
		flac__utils_printf(stderr, 1, "%s: ERROR: FLAC input has STREAMINFO with unknown total samples which is not supported\n", e->inbasefilename);
		return false;
938
939
	}

940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
	e->info.sample_rate = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.sample_rate;
	e->info.channels = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.channels;
	e->info.bits_per_sample = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.bits_per_sample;
	e->info.shift = 0;
	e->info.bytes_per_wide_sample = 0;
	e->info.is_unsigned_samples = false; /* not applicable for FLAC input */
	e->info.is_big_endian = false; /* not applicable for FLAC input */
	e->info.channel_mask = 0;

	return true;
}

/*
 * public routines
 */
955
int flac__encode_file(FILE *infile, FLAC__off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, uint32_t lookahead_length, encode_options_t options)
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
{
	EncoderSession encoder_session;
	size_t channel_map[FLAC__MAX_CHANNELS];
	int info_align_carry = -1, info_align_zero = -1;

	if(!EncoderSession_construct(&encoder_session, options, infilesize, infile, infilename, outfilename, lookahead, lookahead_length))
		return 1;

	/* initialize default channel map that preserves channel order */
	{
		size_t i;
		for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++)
			channel_map[i] = i;
	}

	/* read foreign metadata if requested */
972
	if(EncoderSession_format_is_iff(&encoder_session) && options.format_options.iff.foreign_metadata) {
973
974
		const char *error;
		if(!(
Josh Coalson's avatar
Josh Coalson committed
975
			options.format == FORMAT_WAVE || options.format == FORMAT_RF64?
976
				flac__foreign_metadata_read_from_wave(options.format_options.iff.foreign_metadata, infilename, &error) :
977
978
			options.format == FORMAT_WAVE64?
				flac__foreign_metadata_read_from_wave64(options.format_options.iff.foreign_metadata, infilename, &error) :
979
980
981
982
983
984
985
986
987
988
989
990
991
992
				flac__foreign_metadata_read_from_aiff(options.format_options.iff.foreign_metadata, infilename, &error)
		)) {
			flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", encoder_session.inbasefilename, error);
			return EncoderSession_finish_error(&encoder_session);
		}
	}

	/* initialize encoder session with info about the audio (channels/bps/resolution/endianness/etc) */
	switch(options.format) {
		case FORMAT_RAW:
			if(!get_sample_info_raw(&encoder_session, options))
				return EncoderSession_finish_error(&encoder_session);
			break;
		case FORMAT_WAVE:
993
		case FORMAT_WAVE64:
Josh Coalson's avatar
Josh Coalson committed
994
		case FORMAT_RF64:
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
			if(!get_sample_info_wave(&encoder_session, options))
				return EncoderSession_finish_error(&encoder_session);
			break;
		case FORMAT_AIFF:
		case FORMAT_AIFF_C:
			if(!get_sample_info_aiff(&encoder_session, options))
				return EncoderSession_finish_error(&encoder_session);
			break;
		case FORMAT_FLAC:
		case FORMAT_OGGFLAC:
			/*
			 * set up FLAC decoder for the input
			 */
			if (0 == (encoder_session.fmt.flac.decoder = FLAC__stream_decoder_new())) {
				flac__utils_printf(stderr, 1, "%s: ERROR: creating decoder for FLAC input\n", encoder_session.inbasefilename);
				return EncoderSession_finish_error(&encoder_session);
			}
1012
			if(!get_sample_info_flac(&encoder_session))
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
				return EncoderSession_finish_error(&encoder_session);
			break;
		default:
			FLAC__ASSERT(0);
			/* double protection */
			return EncoderSession_finish_error(&encoder_session);
	}

	/* some more checks */
	if(encoder_session.info.channels == 0 || encoder_session.info.channels > FLAC__MAX_CHANNELS) {
		flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u\n", encoder_session.inbasefilename, encoder_session.info.channels);
		return EncoderSession_finish_error(&encoder_session);
	}
	if(!FLAC__format_sample_rate_is_valid(encoder_session.info.sample_rate)) {
		flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, encoder_session.info.sample_rate);
		return EncoderSession_finish_error(&encoder_session);
	}
	if(encoder_session.info.bits_per_sample-encoder_session.info.shift < 4 || encoder_session.info.bits_per_sample-encoder_session.info.shift > 24) {
		flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, encoder_session.info.bits_per_sample-encoder_session.info.shift);
		return EncoderSession_finish_error(&encoder_session);
	}
	if(options.sector_align) {
		if(encoder_session.info.channels != 2) {
			flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.channels);
			return EncoderSession_finish_error(&encoder_session);
		}
		if(encoder_session.info.sample_rate != 44100) {
			flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.sample_rate);
			return EncoderSession_finish_error(&encoder_session);
		}
		if(encoder_session.info.bits_per_sample-encoder_session.info.shift != 16) {
			flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits-per-sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.bits_per_sample-encoder_session.info.shift);
			return EncoderSession_finish_error(&encoder_session);
		}
	}