encode.c 116 KB
Newer Older
Josh Coalson's avatar
Josh Coalson committed
1
/* flac - Command-line FLAC encoder/decoder
2
3
 * Copyright (C) 2000-2009  Josh Coalson
 * Copyright (C) 2011-2013  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
 */

Josh Coalson's avatar
Josh Coalson committed
20
21
22
23
24
#if HAVE_CONFIG_H
#  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
53
54
55
56
57
58
59
60
61
62
63
64
typedef struct {
	unsigned sample_rate;
	unsigned channels;
	unsigned bits_per_sample; /* width of sample point, including 'shift' bits, valid bps is bits_per_sample-shift */
	unsigned shift; /* # of LSBs samples have been shifted left by */
	unsigned bytes_per_wide_sample; /* for convenience, always == channels*((bps+7)/8), or 0 if N/A to input format (like FLAC) */
	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
67
68
69
70
71
72
73
	const FLAC__byte *lookahead;
	unsigned lookahead_length;
	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;
Josh Coalson's avatar
Josh Coalson committed
92
	unsigned stats_mask;
Josh Coalson's avatar
Josh Coalson committed
93

94
95
96
97
98
	SampleInfo info;

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

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

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

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

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

118
119
120
121
static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
static signed char *scbuffer_ = (signed char *)ucbuffer_;
static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_;
static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_;
Josh Coalson's avatar
Josh Coalson committed
122

123
124
125
126
127
128
129
static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
static FLAC__int32 *input_[FLAC__MAX_CHANNELS];


/*
 * local routines
 */
130
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, unsigned lookahead_length);
131
static void EncoderSession_destroy(EncoderSession *e);
132
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);
133
static int EncoderSession_finish_error(EncoderSession *e);
134
static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options);
135
static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
136
static FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e);
137
static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
138
static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
139
static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata);
140
static FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift, size_t *channel_map);
141
static void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
142
static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
143
144
145
146
147
148
149
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);
150
static FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, unsigned sample_rate, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors);
Josh Coalson's avatar
Josh Coalson committed
151
static void print_stats(const EncoderSession *encoder_session);
152
static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
153
154
static void print_error_with_state(const EncoderSession *e, const char *message);
static void print_verify_error(EncoderSession *e);
155
156
157
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
158
static FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn);
159
static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn);
160
static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
161
static unsigned count_channel_mask_bits(FLAC__uint32 mask);
Josh Coalson's avatar
Josh Coalson committed
162
#if 0
Josh Coalson's avatar
Josh Coalson committed
163
static FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels);
Josh Coalson's avatar
Josh Coalson committed
164
#endif
Josh Coalson's avatar
Josh Coalson committed
165

166
static FLAC__bool get_sample_info_raw(EncoderSession *e, encode_options_t options)
167
{
168
169
170
171
172
173
174
175
	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;
176

177
178
	return true;
}
179

180
181
static FLAC__bool get_sample_info_wave(EncoderSession *e, encode_options_t options)
{
Josh Coalson's avatar
Josh Coalson committed
182
	FLAC__bool got_fmt_chunk = false, got_data_chunk = false, got_ds64_chunk = false;
183
184
	unsigned sample_rate = 0, channels = 0, bps = 0, shift = 0;
	FLAC__uint32 channel_mask = 0;
Josh Coalson's avatar
Josh Coalson committed
185
	FLAC__uint64 ds64_data_size = 0;
186

187
188
	e->info.is_unsigned_samples = false;
	e->info.is_big_endian = false;
189

190
191
	if(e->format == FORMAT_WAVE64) {
		/*
192
		 * lookahead[] already has "riff\x2E\x91\xCF\x11\xA5\xD6\x28\xDB", skip over remaining header
193
194
195
196
197
198
199
200
		 */
		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" */

201
	while(!feof(e->fin) && !got_data_chunk) {
202
203
204
205
206
		/* 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)) {
207
208
			flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename);
			return false;
209
		}
210
		if(feof(e->fin))
211
			break;
212

213
		if(e->format == FORMAT_RF64 && !memcmp(chunk_id, "ds64", 4)) { /* RF64 64-bit sizes chunk */
Josh Coalson's avatar
Josh Coalson committed
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
			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;
			}
			if(got_fmt_chunk || got_data_chunk) {
				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) {
				flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'ds64' chunk has length = %u\n", e->inbasefilename, (unsigned)data_bytes);
				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;
		}
256
257
		else if(
			!memcmp(chunk_id, "fmt ", 4) &&
258
			(e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "fmt \xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 16))
259
		) { /* format chunk */
260
			FLAC__uint16 x;
Josh Coalson's avatar
Josh Coalson committed
261
			FLAC__uint32 xx, data_bytes;
262
			FLAC__uint16 wFormatTag; /* wFormatTag word from the 'fmt ' chunk */
263

264
265
266
			if(got_fmt_chunk) {
				flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'fmt ' chunks\n", e->inbasefilename);
				return false;
267
268
			}

269
270
271
272
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
			/* 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.
			 *
			 * Data is supposed to be unsigned for bps <= 8 else signed.
298
			 */
299

300
301
302
303
			/* fmt chunk size */
			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
				return false;
			data_bytes = xx;
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
			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) {
					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly large Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (unsigned)xx, (unsigned)data_bytes);
					return false;
				}
				/* subtract size of header */
				if (data_bytes < 16+8) {
					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (unsigned)xx, (unsigned)data_bytes);
					return false;
				}
				data_bytes -= (16+8);
			}
319
320
321
			if(data_bytes < 16) {
				flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'fmt ' chunk has length = %u\n", e->inbasefilename, (unsigned)data_bytes);
				return false;
322
			}
323
324
325
326
327
328
329
			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 */
			}
330

331
332
333
334
335
336
			/* 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*/) {
				flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", e->inbasefilename, (unsigned)wFormatTag);
				return false;
337
			}
338

339
340
341
342
			/* number of channels */
			if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
				return false;
			channels = (unsigned)x;
343

344
345
346
347
			/* sample rate */
			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
				return false;
			sample_rate = xx;
348

349
350
351
352
353
354
			/* 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
355

356
357
358
359
			/* bits per sample */
			if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
				return false;
			bps = (unsigned)x;
360

361
			e->info.is_unsigned_samples = (bps <= 8);
362

363
364
365
366
367
368
369
370
371
372
373
374
375
			if(wFormatTag == 1) {
				if(bps != 8 && bps != 16) {
					if(bps == 24 || bps == 32) {
						/* let these slide with a warning since they're unambiguous */
						flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (unsigned)wFormatTag, bps);
						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' */
						flac__utils_printf(stderr, 1, "%s: ERROR: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (unsigned)wFormatTag, bps);
						return false;
					}
376
				}
377
378
379
380
381
382
383
384
385
386
387
388
#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() */
						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, (unsigned)wFormatTag, block_align, bps, channels);
						if(e->treat_warnings_as_errors)
							return false;
						shift = 8 - (bps % 8);
						bps += shift;
					}
					else
						shift = 0;
389
390
				}
				else {
391
392
					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, (unsigned)wFormatTag, block_align, bps, channels);
					return false;
393
				}
394
395
396
#else
				shift = 0;
#endif
397
398
399
				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;
400
				}
401
402
				FLAC__ASSERT(data_bytes >= 16);
				data_bytes -= 16;
403
			}
404
405
			else {
				if(data_bytes < 40) {
406
407
					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with size %u\n", e->inbasefilename, (unsigned)data_bytes);
					return false;
408
409
				}
				/* cbSize */
410
411
				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
					return false;
412
				if(x < 22) {
413
414
					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with cbSize %u\n", e->inbasefilename, (unsigned)x);
					return false;
415
416
				}
				/* valid bps */
417
418
				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
					return false;
419
				if((unsigned)x > bps) {
420
421
					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", e->inbasefilename, (unsigned)x, bps);
					return false;
422
423
424
				}
				shift = bps - (unsigned)x;
				/* channel mask */
425
426
				if(!read_uint32(e->fin, /*big_endian=*/false, &channel_mask, e->inbasefilename))
					return false;
427
428
429
430
431
432
433
				/* for mono/stereo and unassigned channels, we fake the mask */
				if(channel_mask == 0) {
					if(channels == 1)
						channel_mask = 0x0001;
					else if(channels == 2)
						channel_mask = 0x0003;
				}
434
435
436
437
438
439
440
				/* 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 */
				/* the default mapping is sufficient for 1-6 channels and 7-8 are currently unspecified anyway */
#if 0
				/* @@@ example for dolby/vorbis order, for reference later in case it becomes important */
				if(
441
					options.channel_map_none ||
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
					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 */
460
461
462
					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 */
463
464
465
466
467
468
469
470
471
472
				) {
					/* 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(
473
					options.channel_map_none ||
474
475
476
477
478
479
480
481
					channel_mask == 0x0001 || /* 1 channel: (mono) */
					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 */
482
483
484
					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 */
485
486
				) {
					/* keep default channel order */
487
				}
488
489
#endif
				else {
490
491
					flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk with unsupported channel mask=0x%04X\n\nUse --channel-map=none option to store channels in current order; FLAC files\nmust also be decoded with --channel-map=none to restore correct order.\n", e->inbasefilename, (unsigned)channel_mask);
					return false;
492
				}
493
				if(!options.channel_map_none) {
494
					if(count_channel_mask_bits(channel_mask) < channels) {
495
496
						flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has unassigned channels (#channels=%u)\n", e->inbasefilename, (unsigned)channel_mask, channels);
						return false;
497
498
499
500
501
502
503
504
505
506
					}
#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) {
507
508
						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, (unsigned)channel_mask, channels);
						return false;
509
510
511
					}
#endif
				}
512
				/* first part of GUID */
513
514
				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
					return false;
515
				if(x != 1) {
516
517
					flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE chunk with non-PCM format %u\n", e->inbasefilename, (unsigned)x);
					return false;
518
519
520
521
				}
				data_bytes -= 26;
			}

522
			e->info.bytes_per_wide_sample = channels * (bps / 8);
523

524
			/* skip any extra data in the fmt chunk */
525
526
527
			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;
528
529
530
531
			}

			got_fmt_chunk = true;
		}
532
533
		else if(
			!memcmp(chunk_id, "data", 4) &&
534
			(e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "data\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 16))
535
		) { /* data chunk */
536
			FLAC__uint32 xx;
Josh Coalson's avatar
Josh Coalson committed
537
			FLAC__uint64 data_bytes;
538

539
540
541
			if(!got_fmt_chunk) {
				flac__utils_printf(stderr, 1, "%s: ERROR: got 'data' chunk before 'fmt' chunk\n", e->inbasefilename);
				return false;
542
			}
543

544
			/* data size */
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
			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) {
					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'data' chunk has length = 0x00000000%08X\n", e->inbasefilename, (unsigned)data_bytes);
					return false;
				}
				data_bytes -= (16+8);
			}
			if(e->format == FORMAT_RF64) {
Josh Coalson's avatar
Josh Coalson committed
561
562
563
564
565
566
567
				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;
			}
568
569
			if(options.ignore_chunk_sizes) {
				FLAC__ASSERT(!options.sector_align);
Josh Coalson's avatar
Josh Coalson committed
570
571
				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);
572
573
					if(e->treat_warnings_as_errors)
						return false;
574
				}
Josh Coalson's avatar
Josh Coalson committed
575
				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 */
576
			}
Josh Coalson's avatar
Josh Coalson committed
577
578
579
			else if(0 == data_bytes) {
				flac__utils_printf(stderr, 1, "%s: ERROR: 'data' chunk has size of 0\n", e->inbasefilename);
				return false;
580
			}
581

582
			e->fmt.iff.data_bytes = data_bytes;
583

584
			got_data_chunk = true;
585
			break;
586
587
		}
		else {
588
			FLAC__uint32 xx;
589
			FLAC__uint64 skip;
590
			if(!options.format_options.iff.foreign_metadata) {
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
				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,
						(unsigned)((const unsigned char *)chunk_id)[3],
						(unsigned)((const unsigned char *)chunk_id)[2],
						(unsigned)((const unsigned char *)chunk_id)[1],
						(unsigned)((const unsigned char *)chunk_id)[0],
						(unsigned)((const unsigned char *)chunk_id)[5],
						(unsigned)((const unsigned char *)chunk_id)[4],
						(unsigned)((const unsigned char *)chunk_id)[7],
						(unsigned)((const unsigned char *)chunk_id)[6],
						(unsigned)((const unsigned char *)chunk_id)[9],
						(unsigned)((const unsigned char *)chunk_id)[8],
						(unsigned)((const unsigned char *)chunk_id)[10],
						(unsigned)((const unsigned char *)chunk_id)[11],
						(unsigned)((const unsigned char *)chunk_id)[12],
						(unsigned)((const unsigned char *)chunk_id)[13],
						(unsigned)((const unsigned char *)chunk_id)[14],
						(unsigned)((const unsigned char *)chunk_id)[15]
					);
613
614
				if(e->treat_warnings_as_errors)
					return false;
615
			}
616

617
			/* chunk size */
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
			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) {
					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 chunk has length = 0x00000000%08X\n", e->inbasefilename, (unsigned)skip);
					return false;
				}
				skip -= (16+8);
			}
			if(skip) {
636
637
638
				if(!fskip_ahead(e->fin, skip)) {
					flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename);
					return false;
639
				}
640
			}
Josh Coalson's avatar
Josh Coalson committed
641
642
643
		}
	}

644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
	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
660
661
}

662
static FLAC__bool get_sample_info_aiff(EncoderSession *e, encode_options_t options)
Josh Coalson's avatar
Josh Coalson committed
663
{
664
	FLAC__bool got_comm_chunk = false, got_ssnd_chunk = false;
Josh Coalson's avatar
Josh Coalson committed
665
666
	unsigned sample_rate = 0, channels = 0, bps = 0, shift = 0;
	FLAC__uint64 sample_frames = 0;
667
668
669
670
	FLAC__uint32 channel_mask = 0;

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

672
	/*
673
	 * lookahead[] already has "FORMxxxxAIFF", do chunks
674
	 */
675
676
677
678
679
680
681
682
	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;
683

684
685
686
687
		if(!memcmp(chunk_id, "COMM", 4)) { /* common chunk */
			FLAC__uint16 x;
			FLAC__uint32 xx;
			unsigned long skip;
688
			const FLAC__bool is_aifc = e->format == FORMAT_AIFF_C;
689
			const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18);
690

691
692
693
694
			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
695

696
697
698
699
700
701
702
703
704
705
706
707
708
			/* COMM chunk size */
			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
				return false;
			else if(xx < minimum_comm_size) {
				flac__utils_printf(stderr, 1, "%s: ERROR: non-standard %s 'COMM' chunk has length = %u\n", e->inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx);
				return false;
			}
			else if(!is_aifc && xx != minimum_comm_size) {
				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", (unsigned int)xx, minimum_comm_size);
				if(e->treat_warnings_as_errors)
					return false;
			}
			skip = (xx-minimum_comm_size)+(xx & 1);
709

710
711
712
713
714
			/* number of channels */
			if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
				return false;
			channels = (unsigned)x;
			if(channels > 2 && !options.channel_map_none) {
Josh Coalson's avatar
Josh Coalson committed
715
				flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
716
				return false;
717
			}
Josh Coalson's avatar
Josh Coalson committed
718

719
720
721
722
			/* 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
723

724
725
726
727
728
729
			/* bits per sample */
			if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
				return false;
			bps = (unsigned)x;
			shift = (bps%8)? 8-(bps%8) : 0; /* SSND data is always byte-aligned, left-justified but format_input() will double-check */
			bps += shift;
730

731
732
733
734
			/* sample rate */
			if(!read_sane_extended(e->fin, &xx, e->inbasefilename))
				return false;
			sample_rate = xx;
735

736
737
738
739
740
741
742
743
744
745
746
			/* 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;
747
				}
748
749
			}

750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
			/* 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
773
			}
774
			else {
Josh Coalson's avatar
Josh Coalson committed
775
				flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
776
777
				return false;
			}
778

779
780
781
782
783
784
			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;
785
			}
786
787

			got_comm_chunk = true;
Josh Coalson's avatar
Josh Coalson committed
788
		}
789
790
		else if(!memcmp(chunk_id, "SSND", 4) && !got_ssnd_chunk) { /* sound data chunk */
			FLAC__uint32 xx;
Josh Coalson's avatar
Josh Coalson committed
791
			FLAC__uint64 data_bytes;
792
			unsigned offset = 0;
793
794
795
796

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

799
800
801
			/* SSND chunk size */
			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
				return false;
Josh Coalson's avatar
Josh Coalson committed
802
			data_bytes = xx;
803
804
			if(options.ignore_chunk_sizes) {
				FLAC__ASSERT(!options.sector_align);
Josh Coalson's avatar
Josh Coalson committed
805
806
				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);
807
808
					if(e->treat_warnings_as_errors)
						return false;
809
				}
Josh Coalson's avatar
Josh Coalson committed
810
811
812
813
814
				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;
815
816
			}
			else {
817
818
				data_bytes -= 8; /* discount the offset and block size fields */
			}
819

820
821
822
823
824
825
826
827
828
			/* 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;
829
830
831
832
833
834
835
836
			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;
				}
837
838
839
840
841
842
843
			}

			/* 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
844

845
846
847
			e->fmt.iff.data_bytes = data_bytes;

			got_ssnd_chunk = true;
848
849
		}
		else {
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
			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 {
				unsigned long skip = xx + (xx & 1);

				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;
867
868
869
870
871
				}
			}
		}
	}

872
873
874
875
876
877
878
879
	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;
	}
880

881
882
883
884
885
	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;
886

887
888
	return true;
}
889

890
static FLAC__bool get_sample_info_flac(EncoderSession *e)
891
{
892
	if (!(
893
894
		FLAC__stream_decoder_set_md5_checking(e->fmt.flac.decoder, false) &&
		FLAC__stream_decoder_set_metadata_respond_all(e->fmt.flac.decoder)
895
	)) {
896
897
		flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", e->inbasefilename);
		return false;
898
899
	}

900
	if (e->format == FORMAT_OGGFLAC) {
901
902
903
		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;
904
905
		}
	}
906
907
908
	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;
909
910
	}

911
912
913
	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);
914
		else
915
916
			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;
917
918
	}

919
920
921
	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;
922
	}
923
924
925
	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;
926
	}
927
928
929
	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;
930
931
	}

932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
	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
 */
947
int flac__encode_file(FILE *infile, FLAC__off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, encode_options_t options)
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
{
	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 */
964
	if(EncoderSession_format_is_iff(&encoder_session) && options.format_options.iff.foreign_metadata) {
965
966
		const char *error;
		if(!(
Josh Coalson's avatar
Josh Coalson committed
967
			options.format == FORMAT_WAVE || options.format == FORMAT_RF64?
968
				flac__foreign_metadata_read_from_wave(options.format_options.iff.foreign_metadata, infilename, &error) :
969
970
			options.format == FORMAT_WAVE64?
				flac__foreign_metadata_read_from_wave64(options.format_options.iff.foreign_metadata, infilename, &error) :
971
972
973
974
975
976
977
978
979
980
981
982
983
984
				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:
985
		case FORMAT_WAVE64:
Josh Coalson's avatar
Josh Coalson committed
986
		case FORMAT_RF64:
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
			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);
			}
1004
			if(!get_sample_info_flac(&encoder_session))
1005
1006
1007
1008
1009
1010
1011
1012
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
				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);
		}
	}
1040
1041

	{
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
		FLAC__uint64 total_samples_in_input; /* WATCHOUT: may be 0 to mean "unknown" */
		FLAC__uint64 skip;
		FLAC__uint64 until; /* a value of 0 mean end-of-stream (i.e. --until=-0) */
		unsigned align_remainder = 0;

		switch(options.format) {
			case FORMAT_RAW:
				if(infilesize < 0)
					total_samples_in_input = 0;
				else
					total_samples_in_input = (FLAC__uint64)infilesize / encoder_session.info.bytes_per_wide_sample + *options.align_reservoir_samples;
				break;
			case FORMAT_WAVE:
1055
			case FORMAT_WAVE64:
Josh Coalson's avatar
Josh Coalson committed
1056
			case FORMAT_RF64:
1057
1058
			case FORMAT_AIFF:
			case FORMAT_AIFF_C:
1059
				/* truncation in the division removes any padding byte that was counted in encoder_session.fmt.iff.data_bytes */
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
				total_samples_in_input = encoder_session.fmt.iff.data_bytes / encoder_session.info.bytes_per_wide_sample + *options.align_reservoir_samples;
				break;
			case FORMAT_FLAC:
			case FORMAT_OGGFLAC:
				total_samples_in_input = encoder_session.fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples + *options.align_reservoir_samples;
				break;
			default:
				FLAC__ASSERT(0);
				/* double protection */
				return EncoderSession_finish_error(&encoder_session);
		}
1071

1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
		/*
		 * now that we know the sample rate, canonicalize the
		 * --skip string to an absolute sample number:
		 */
		flac__utils_canonicalize_skip_until_specification(&options.skip_specification, encoder_session.info.sample_rate);
		FLAC__ASSERT(options.skip_specification.value.samples >= 0);
		skip = (FLAC__uint64)options.skip_specification.value.samples;
		FLAC__ASSERT(!options.sector_align || (options.format != FORMAT_FLAC && options.format != FORMAT_OGGFLAC && skip == 0));
		/* *options.align_reservoir_samples will be 0 unless --sector-align is used */
		FLAC__ASSERT(options.sector_align || *options.align_reservoir_samples == 0);
1082
1083

		/*
1084
		 * now that we possibly know the input size, canonicalize the
1085
1086
		 * --until string to an absolute sample number:
		 */
1087
1088
1089
1090
1091
1092
1093
1094
		if(!canonicalize_until_specification(&options.until_specification, encoder_session.inbasefilename, encoder_session.info.sample_rate, skip, total_samples_in_input))
			return EncoderSession_finish_error(&encoder_session);
		until = (FLAC__uint64)options.until_specification.value.samples;
		FLAC__ASSERT(!options.sector_align || until == 0);

		/* adjust encoding parameters based on skip and until values */
		switch(options.format) {
			case FORMAT_RAW:
1095
				infilesize -= (FLAC__off_t)skip * encoder_session.info.bytes_per_wide_sample;
1096
1097
1098
				encoder_session.total_samples_to_encode = total_samples_in_input - skip;
				break;
			case FORMAT_WAVE:
1099
			case FORMAT_WAVE64:
Josh Coalson's avatar
Josh Coalson committed
1100
			case FORMAT_RF64:
1101
1102
			case FORMAT_AIFF:
			case FORMAT_AIFF_C:
Josh Coalson's avatar
Josh Coalson committed
1103
				encoder_session.fmt.iff.data_bytes -= skip * encoder_session.info.bytes_per_wide_sample;
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
				if(options.ignore_chunk_sizes) {
					encoder_session.total_samples_to_encode = 0;
					flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n");
					FLAC__ASSERT(0 == until);
				}
				else {
					encoder_session.total_samples_to_encode = total_samples_in_input - skip;
				}
				break;
			case FORMAT_FLAC:
			case FORMAT_OGGFLAC:
				encoder_session.total_samples_to_encode = total_samples_in_input - skip;
				break;
			default:
				FLAC__ASSERT(0);
				/* double protection */
				return EncoderSession_finish_error(&encoder_session);
		}
		if(until > 0) {
			const FLAC__uint64 trim = total_samples_in_input - until;