encode.c 115 KB
Newer Older
Josh Coalson's avatar
Josh Coalson committed
1
/* flac - Command-line FLAC encoder/decoder
Josh Coalson's avatar
Josh Coalson committed
2
 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009  Josh Coalson
Josh Coalson's avatar
Josh Coalson committed
3 4 5 6 7 8 9 10 11 12 13
 *
 * 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
14 15 16
 * 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
17 18
 */

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

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

Josh Coalson's avatar
Josh Coalson committed
35 36 37 38
#ifdef min
#undef min
#endif
#define min(x,y) ((x)<(y)?(x):(y))
39 40 41 42
#ifdef max
#undef max
#endif
#define max(x,y) ((x)>(y)?(x):(y))
Josh Coalson's avatar
Josh Coalson committed
43

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

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
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 {
	off_t filesize;
	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
70
typedef struct {
71
#if FLAC__HAS_OGG
Josh Coalson's avatar
Josh Coalson committed
72 73
	FLAC__bool use_ogg;
#endif
Josh Coalson's avatar
Josh Coalson committed
74
	FLAC__bool verify;
75
	FLAC__bool is_stdout;
76
	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
77
	const char *inbasefilename;
78
	const char *infilename;
Josh Coalson's avatar
Josh Coalson committed
79 80
	const char *outfilename;

81
	FLAC__bool treat_warnings_as_errors;
82
	FLAC__bool continue_through_decode_errors;
83
	FLAC__bool replay_gain;
84 85
	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
86 87
	FLAC__uint64 bytes_written;
	FLAC__uint64 samples_written;
Josh Coalson's avatar
Josh Coalson committed
88
	unsigned stats_mask;
Josh Coalson's avatar
Josh Coalson committed
89

90 91 92 93 94
	SampleInfo info;

	FileFormat format;
	union {
		struct {
Josh Coalson's avatar
Josh Coalson committed
95
			FLAC__uint64 data_bytes;
96 97 98 99 100 101 102
		} iff;
		struct {
			FLAC__StreamDecoder *decoder;
			FLACDecoderData client_data;
		} flac;
	} fmt;

103
	FLAC__StreamEncoder *encoder;
Josh Coalson's avatar
Josh Coalson committed
104 105 106 107

	FILE *fin;
	FLAC__StreamMetadata *seek_table_template;
} EncoderSession;
Josh Coalson's avatar
Josh Coalson committed
108

109
const int FLAC_ENCODE__DEFAULT_PADDING = 8192;
Josh Coalson's avatar
Josh Coalson committed
110

111
static FLAC__bool is_big_endian_host_;
Josh Coalson's avatar
Josh Coalson committed
112

113 114 115 116
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
117

118 119 120 121
static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
static FLAC__int32 *input_[FLAC__MAX_CHANNELS];


122 123 124 125 126 127
/*
 * unpublished debug routines from the FLAC libs
 */
extern FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
extern FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
extern FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
Josh Coalson's avatar
Josh Coalson committed
128
extern FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value);
129

130 131 132
/*
 * local routines
 */
133
static FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length);
134
static void EncoderSession_destroy(EncoderSession *e);
135
static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero, foreign_metadata_t *foreign_metadata);
136
static int EncoderSession_finish_error(EncoderSession *e);
137
static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options);
138
static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
139
static FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e);
140
static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
141
static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
142
static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata);
143
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);
144
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);
145
static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
146 147 148 149 150 151 152
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);
153
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
154
static void print_stats(const EncoderSession *encoder_session);
155
static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
156 157
static void print_error_with_state(const EncoderSession *e, const char *message);
static void print_verify_error(EncoderSession *e);
158 159 160
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
161
static FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn);
162
static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn);
163
static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
164
static unsigned count_channel_mask_bits(FLAC__uint32 mask);
Josh Coalson's avatar
Josh Coalson committed
165
#if 0
Josh Coalson's avatar
Josh Coalson committed
166
static FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels);
Josh Coalson's avatar
Josh Coalson committed
167
#endif
Josh Coalson's avatar
Josh Coalson committed
168

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

180 181
	return true;
}
182

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

190 191
	e->info.is_unsigned_samples = false;
	e->info.is_big_endian = false;
192

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

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

216
		if(e->format == FORMAT_RF64 && !memcmp(chunk_id, "ds64", 4)) { /* RF64 64-bit sizes chunk */
Josh Coalson's avatar
Josh Coalson committed
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 256 257 258
			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;
		}
259 260 261 262
		else if(
			!memcmp(chunk_id, "fmt ", 4) &&
			(e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "fmt \xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 16))
		) { /* format chunk */
263
			FLAC__uint16 x;
Josh Coalson's avatar
Josh Coalson committed
264
			FLAC__uint32 xx, data_bytes;
265
			FLAC__uint16 wFormatTag; /* wFormatTag word from the 'fmt ' chunk */
266

267 268 269
			if(got_fmt_chunk) {
				flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'fmt ' chunks\n", e->inbasefilename);
				return false;
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 298 299 300
			/* 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.
301
			 */
302

303 304 305 306
			/* fmt chunk size */
			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
				return false;
			data_bytes = xx;
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
			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);
			}
322 323 324
			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;
325
			}
326 327 328 329 330 331 332
			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 */
			}
333

334 335 336 337 338 339
			/* 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;
340
			}
341

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

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

352 353 354 355 356 357
			/* 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
358

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

364
			e->info.is_unsigned_samples = (bps <= 8);
365

366 367 368 369 370 371 372 373 374 375 376 377 378
			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;
					}
379
				}
380 381 382 383 384 385 386 387 388 389 390 391
#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;
392 393
				}
				else {
394 395
					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;
396
				}
397 398 399
#else
				shift = 0;
#endif
400 401 402
				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;
403
				}
404 405
				FLAC__ASSERT(data_bytes >= 16);
				data_bytes -= 16;
406
			}
407 408
			else {
				if(data_bytes < 40) {
409 410
					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with size %u\n", e->inbasefilename, (unsigned)data_bytes);
					return false;
411 412
				}
				/* cbSize */
413 414
				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
					return false;
415
				if(x < 22) {
416 417
					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with cbSize %u\n", e->inbasefilename, (unsigned)x);
					return false;
418 419
				}
				/* valid bps */
420 421
				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
					return false;
422
				if((unsigned)x > bps) {
423 424
					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", e->inbasefilename, (unsigned)x, bps);
					return false;
425 426 427
				}
				shift = bps - (unsigned)x;
				/* channel mask */
428 429
				if(!read_uint32(e->fin, /*big_endian=*/false, &channel_mask, e->inbasefilename))
					return false;
430 431 432 433 434 435 436
				/* 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;
				}
437 438 439 440 441 442 443
				/* 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(
444
					options.channel_map_none ||
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
					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 */
					channel_mask == 0x060f    /* 6 channels: front left, front right, front center, LFE, side left, side right */
				) {
					/* 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(
474
					options.channel_map_none ||
475 476 477 478 479 480 481 482 483 484 485
					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 */
					channel_mask == 0x060f    /* 6 channels: front left, front right, front center, LFE, side left, side right */
				) {
					/* keep default channel order */
486
				}
487 488
#endif
				else {
489 490
					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;
491
				}
492
				if(!options.channel_map_none) {
493
					if(count_channel_mask_bits(channel_mask) < channels) {
494 495
						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;
496 497 498 499 500 501 502 503 504 505
					}
#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) {
506 507
						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;
508 509 510
					}
#endif
				}
511
				/* first part of GUID */
512 513
				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
					return false;
514
				if(x != 1) {
515 516
					flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE chunk with non-PCM format %u\n", e->inbasefilename, (unsigned)x);
					return false;
517 518 519 520
				}
				data_bytes -= 26;
			}

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

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

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

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

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

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

583
			got_data_chunk = true;
584
			break;
585 586
		}
		else {
587
			FLAC__uint32 xx;
588
			FLAC__uint64 skip;
589
			if(!options.format_options.iff.foreign_metadata) {
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
				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]
					);
612 613
				if(e->treat_warnings_as_errors)
					return false;
614
			}
615

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

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

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

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

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

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

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

695 696 697 698 699 700 701 702 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) {
				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);
708

709 710 711 712 713
			/* 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
714
				flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
715
				return false;
716
			}
Josh Coalson's avatar
Josh Coalson committed
717

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

723 724 725 726 727 728
			/* 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;
729

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

735 736 737 738 739 740 741 742 743 744 745
			/* 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;
746
				}
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
			/* 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
772
			}
773
			else {
Josh Coalson's avatar
Josh Coalson committed
774
				flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
775 776
				return false;
			}
777

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

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

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

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

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

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

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

			got_ssnd_chunk = true;
847 848
		}
		else {
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
			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;
866 867 868 869 870
				}
			}
		}
	}

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

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

886 887
	return true;
}
888

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

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

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

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

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
	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
 */
int flac__encode_file(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, encode_options_t options)
{
	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 */
963
	if(EncoderSession_format_is_iff(&encoder_session) && options.format_options.iff.foreign_metadata) {
964 965
		const char *error;
		if(!(
Josh Coalson's avatar
Josh Coalson committed
966
			options.format == FORMAT_WAVE || options.format == FORMAT_RF64?
967
				flac__foreign_metadata_read_from_wave(options.format_options.iff.foreign_metadata, infilename, &error) :
968 969
			options.format == FORMAT_WAVE64?
				flac__foreign_metadata_read_from_wave64(options.format_options.iff.foreign_metadata, infilename, &error) :
970 971 972 973 974 975 976 977 978 979 980 981 982 983
				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: