xref: /aosp_15_r20/external/flac/src/flac/encode.c (revision 600f14f40d737144c998e2ec7a483122d3776fbc)
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000-2009  Josh Coalson
3  * Copyright (C) 2011-2023  Xiph.Org Foundation
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
20 #ifdef HAVE_CONFIG_H
21 #  include <config.h>
22 #endif
23 
24 #include <errno.h>
25 #include <limits.h> /* for LONG_MAX */
26 #include <math.h> /* for floor() */
27 #include <stdio.h> /* for FILE etc. */
28 #include <stdlib.h> /* for malloc */
29 #include <string.h> /* for strcmp(), strerror() */
30 #include <time.h> /* for clock() */
31 #include <sys/stat.h>
32 #include "FLAC/all.h"
33 #include "share/alloc.h"
34 #include "share/grabbag.h"
35 #include "share/compat.h"
36 #include "share/private.h"
37 #include "share/safe_str.h"
38 #include "share/endswap.h"
39 #include "encode.h"
40 
41 #ifdef min
42 #undef min
43 #endif
44 #define min(x,y) ((x)<(y)?(x):(y))
45 #ifdef max
46 #undef max
47 #endif
48 #define max(x,y) ((x)>(y)?(x):(y))
49 
50 /* this MUST be < 2^sizeof(size_t) / ( FLAC__MAX_CHANNELS * (FLAC__MAX_BITS_PER_SAMPLE/8) ) */
51 #define CHUNK_OF_SAMPLES 2048
52 
53 typedef struct {
54 	uint32_t sample_rate;
55 	uint32_t channels;
56 	uint32_t bits_per_sample; /* width of sample point, including 'shift' bits, valid bps is bits_per_sample-shift */
57 	uint32_t shift; /* # of LSBs samples have been shifted left by */
58 	uint32_t bytes_per_wide_sample; /* for convenience, always == channels*((bps+7)/8), or 0 if N/A to input format (like FLAC) */
59 	FLAC__bool is_unsigned_samples;
60 	FLAC__bool is_big_endian;
61 	FLAC__uint32 channel_mask;
62 } SampleInfo;
63 
64 /* this is the client_data attached to the FLAC decoder when encoding from a FLAC file */
65 typedef struct {
66 	FLAC__off_t filesize;
67 	const FLAC__byte *lookahead;
68 	uint32_t lookahead_length;
69 	size_t num_metadata_blocks;
70 	FLAC__StreamMetadata *metadata_blocks[1024]; /*@@@ BAD MAGIC number */
71 	FLAC__uint64 samples_left_to_process;
72 	FLAC__bool fatal_error;
73 } FLACDecoderData;
74 
75 typedef struct {
76 #if FLAC__HAS_OGG
77 	FLAC__bool use_ogg;
78 #endif
79 	FLAC__bool verify;
80 	FLAC__bool is_stdout;
81 	FLAC__bool outputfile_opened; /* true if we successfully opened the output file and we want it to be deleted if there is an error */
82 	const char *inbasefilename;
83 	const char *infilename;
84 	const char *outfilename;
85 
86 	FLAC__bool treat_warnings_as_errors;
87 	FLAC__bool continue_through_decode_errors;
88 	FLAC__bool replay_gain;
89 	FLAC__uint64 total_samples_to_encode; /* (i.e. "wide samples" aka "sample frames") WATCHOUT: may be 0 to mean 'unknown' */
90 	FLAC__uint64 unencoded_size; /* an estimate of the input size, only used in the progress indicator */
91 	FLAC__uint64 bytes_written;
92 	FLAC__uint64 samples_written;
93 #if 0 /* in case time.h with clock() isn't available for some reason */
94 	uint32_t stats_frames_interval;
95 	uint32_t old_frames_written;
96 #else
97 	clock_t old_clock_t;
98 #endif
99 
100 	SampleInfo info;
101 
102 	FileFormat format;
103 	union {
104 		struct {
105 			FLAC__uint64 data_bytes;
106 		} iff;
107 		struct {
108 			FLAC__StreamDecoder *decoder;
109 			FLACDecoderData client_data;
110 		} flac;
111 	} fmt;
112 
113 	FLAC__StreamEncoder *encoder;
114 
115 	FILE *fin;
116 	FLAC__StreamMetadata *seek_table_template;
117 	double progress, compression_ratio;
118 } EncoderSession;
119 
120 const int FLAC_ENCODE__DEFAULT_PADDING = 8192;
121 
122 static FLAC__bool is_big_endian_host_;
123 
124 #define UBUFFER_INT8_SIZE 0x10000
125 
126 static union {
127 	FLAC__int8 s8[UBUFFER_INT8_SIZE];
128 	FLAC__uint8 u8[UBUFFER_INT8_SIZE];
129 	FLAC__int16 s16[UBUFFER_INT8_SIZE/2];
130 	FLAC__uint16 u16[UBUFFER_INT8_SIZE/2];
131 	FLAC__int32 s32[UBUFFER_INT8_SIZE/4];
132 	FLAC__uint32 u32[UBUFFER_INT8_SIZE/4];
133 } ubuffer;
134 
135 
136 static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
137 static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
138 
139 
140 /*
141  * local routines
142  */
143 static FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, FLAC__off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, uint32_t lookahead_length);
144 static void EncoderSession_destroy(EncoderSession *e);
145 static int EncoderSession_finish_ok(EncoderSession *e, foreign_metadata_t *foreign_metadata, FLAC__bool error_on_compression_fail);
146 static int EncoderSession_finish_error(EncoderSession *e);
147 static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options);
148 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], uint32_t samples);
149 static FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e);
150 static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
151 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, uint32_t sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
152 static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, uint32_t num_metadata);
153 static FLAC__bool format_input(FLAC__int32 *dest[], uint32_t wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, uint32_t channels, uint32_t bps, uint32_t shift, size_t *channel_map);
154 static void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, uint32_t frames_written, uint32_t total_frames_estimate, void *client_data);
155 static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
156 static FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
157 static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
158 static FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
159 static FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data);
160 static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
161 static void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
162 static void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
163 static FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, uint32_t sample_rate, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors);
164 static void print_stats(const EncoderSession *encoder_session);
165 static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
166 static void print_error_with_state(const EncoderSession *e, const char *message);
167 static void print_verify_error(EncoderSession *e);
168 static FLAC__bool read_bytes(FILE *f, FLAC__byte *buf, size_t n, FLAC__bool eof_ok, const char *fn);
169 static FLAC__bool read_uint16(FILE *f, FLAC__bool big_endian, FLAC__uint16 *val, const char *fn);
170 static FLAC__bool read_uint32(FILE *f, FLAC__bool big_endian, FLAC__uint32 *val, const char *fn);
171 static FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn);
172 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn);
173 static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
174 static uint32_t count_channel_mask_bits(FLAC__uint32 mask);
175 
get_sample_info_raw(EncoderSession * e,encode_options_t options)176 static FLAC__bool get_sample_info_raw(EncoderSession *e, encode_options_t options)
177 {
178 	e->info.sample_rate = options.format_options.raw.sample_rate;
179 	e->info.channels = options.format_options.raw.channels;
180 	e->info.bits_per_sample = options.format_options.raw.bps;
181 	e->info.shift = 0;
182 	e->info.bytes_per_wide_sample = options.format_options.raw.channels * ((options.format_options.raw.bps+7)/8);
183 	e->info.is_unsigned_samples = options.format_options.raw.is_unsigned_samples;
184 	e->info.is_big_endian = options.format_options.raw.is_big_endian;
185 	e->info.channel_mask = 0;
186 
187 	return true;
188 }
189 
get_sample_info_wave(EncoderSession * e,encode_options_t options)190 static FLAC__bool get_sample_info_wave(EncoderSession *e, encode_options_t options)
191 {
192 	FLAC__bool got_fmt_chunk = false, got_data_chunk = false, got_ds64_chunk = false;
193 	uint32_t sample_rate = 0, channels = 0, bps = 0, shift = 0, block_align = 0;
194 	FLAC__uint32 channel_mask = 0;
195 	FLAC__uint64 ds64_data_size = 0;
196 
197 	e->info.is_unsigned_samples = false;
198 	e->info.is_big_endian = false;
199 
200 	if(e->format == FORMAT_WAVE64) {
201 		/*
202 		 * lookahead[] already has "riff\x2E\x91\xCF\x11\xA5\xD6\x28\xDB", skip over remaining header
203 		 */
204 		if(!fskip_ahead(e->fin, 16+8+16-12)) { /* riff GUID + riff size + WAVE GUID - lookahead */
205 			flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over remaining \"riff\" header\n", e->inbasefilename);
206 			return false;
207 		}
208 	}
209 	/* else lookahead[] already has "RIFFxxxxWAVE" or "RF64xxxxWAVE" */
210 
211 	while(!feof(e->fin) && !got_data_chunk) {
212 		/* chunk IDs are 4 bytes for WAVE/RF64, 16 for Wave64 */
213 		/* for WAVE/RF64 we want the 5th char zeroed so we can treat it like a C string */
214 		char chunk_id[16] = { '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' };
215 
216 		if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, e->format==FORMAT_WAVE64?16:4, /*eof_ok=*/true, e->inbasefilename)) {
217 			flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename);
218 			return false;
219 		}
220 		if(feof(e->fin))
221 			break;
222 
223 		if(e->format == FORMAT_RF64 && !memcmp(chunk_id, "ds64", 4)) { /* RF64 64-bit sizes chunk */
224 			FLAC__uint32 xx, data_bytes;
225 
226 			if(got_ds64_chunk) {
227 				flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'ds64' chunks\n", e->inbasefilename);
228 				return false;
229 			}
230 			if(got_fmt_chunk) {
231 				flac__utils_printf(stderr, 1, "%s: ERROR: 'ds64' chunk appears after 'fmt ' or 'data' chunk\n", e->inbasefilename);
232 				return false;
233 			}
234 
235 			/* ds64 chunk size */
236 			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
237 				return false;
238 			data_bytes = xx;
239 			if(data_bytes < 28) {
240 				flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'ds64' chunk has length = %u\n", e->inbasefilename, (uint32_t)data_bytes);
241 				return false;
242 			}
243 			if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */
244 				data_bytes++;
245 
246 			/* RIFF 64-bit size, lo/hi */
247 			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
248 				return false;
249 			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
250 				return false;
251 
252 			/* 'data' 64-bit size */
253 			if(!read_uint64(e->fin, /*big_endian=*/false, &ds64_data_size, e->inbasefilename))
254 				return false;
255 
256 			data_bytes -= 16;
257 
258 			/* skip any extra data in the ds64 chunk */
259 			if(!fskip_ahead(e->fin, data_bytes)) {
260 				flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'ds64' data\n", e->inbasefilename);
261 				return false;
262 			}
263 
264 			got_ds64_chunk = true;
265 		}
266 		else if(
267 			!memcmp(chunk_id, "fmt ", 4) &&
268 			(e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "fmt \xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 16))
269 		) { /* format chunk */
270 			FLAC__uint16 x;
271 			FLAC__uint32 xx, data_bytes;
272 			FLAC__uint16 wFormatTag; /* wFormatTag word from the 'fmt ' chunk */
273 
274 			if(got_fmt_chunk) {
275 				flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'fmt ' chunks\n", e->inbasefilename);
276 				return false;
277 			}
278 
279 			/* see
280 			 *   http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
281 			 *   http://windowssdk.msdn.microsoft.com/en-us/library/ms713497.aspx
282 			 *   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
283 			 *
284 			 * WAVEFORMAT is
285 			 * 4 byte: chunk size
286 			 * 2 byte: format type: 1 for WAVE_FORMAT_PCM, 65534 for WAVE_FORMAT_EXTENSIBLE
287 			 * 2 byte: # channels
288 			 * 4 byte: sample rate (Hz)
289 			 * 4 byte: avg bytes per sec
290 			 * 2 byte: block align
291 			 * 2 byte: bits per sample (not necessarily all significant)
292 			 * WAVEFORMATEX adds
293 			 * 2 byte: extension size in bytes (usually 0 for WAVEFORMATEX and 22 for WAVEFORMATEXTENSIBLE with PCM)
294 			 * WAVEFORMATEXTENSIBLE adds
295 			 * 2 byte: valid bits per sample
296 			 * 4 byte: channel mask
297 			 * 16 byte: subformat GUID, first 2 bytes have format type, 1 being PCM
298 			 *
299 			 * Current spec says WAVEFORMATEX with PCM must have bps == 8 or 16, or any multiple of 8 for WAVEFORMATEXTENSIBLE.
300 			 * 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.
301 			 *
302 			 * Block align for WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE is also supposed to be channels*bps/8
303 			 *
304 			 * If the channel mask has more set bits than # of channels, the extra MSBs are ignored.
305 			 * If the channel mask has less set bits than # of channels, the extra channels are unassigned to any speaker.
306 			 *
307 			 * Data is supposed to be uint32_t for bps <= 8 else signed.
308 			 */
309 
310 			/* fmt chunk size */
311 			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
312 				return false;
313 			data_bytes = xx;
314 			if(e->format == FORMAT_WAVE64) {
315 				/* other half of the size field should be 0 */
316 				if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
317 					return false;
318 				if(xx) {
319 					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly large Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (uint32_t)xx, (uint32_t)data_bytes);
320 					return false;
321 				}
322 				/* subtract size of header */
323 				if (data_bytes < 16+8) {
324 					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (uint32_t)xx, (uint32_t)data_bytes);
325 					return false;
326 				}
327 				data_bytes -= (16+8);
328 			}
329 			if(data_bytes < 16 || data_bytes > (UINT32_MAX-8)) {
330 				flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'fmt ' chunk has length = %u\n", e->inbasefilename, (uint32_t)data_bytes);
331 				return false;
332 			}
333 			if(e->format != FORMAT_WAVE64) {
334 				if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */
335 					data_bytes++;
336 			}
337 			else { /* Wave64 */
338 				data_bytes = (data_bytes+7) & (~7u); /* should never happen, but enforce Wave64 alignment rules */
339 			}
340 
341 			/* format code */
342 			if(!read_uint16(e->fin, /*big_endian=*/false, &wFormatTag, e->inbasefilename))
343 				return false;
344 			if(wFormatTag != 1 /*WAVE_FORMAT_PCM*/ && wFormatTag != 65534 /*WAVE_FORMAT_EXTENSIBLE*/) {
345 				flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", e->inbasefilename, (uint32_t)wFormatTag);
346 				return false;
347 			}
348 
349 			/* number of channels */
350 			if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
351 				return false;
352 			channels = (uint32_t)x;
353 
354 			/* sample rate */
355 			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
356 				return false;
357 			sample_rate = xx;
358 
359 			/* avg bytes per second (ignored) */
360 			if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
361 				return false;
362 			/* block align */
363 			if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
364 				return false;
365 			block_align = x;
366 			/* bits per sample */
367 			if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
368 				return false;
369 			bps = (uint32_t)x;
370 
371 			e->info.is_unsigned_samples = (bps <= 8);
372 
373 			if(wFormatTag == 1) {
374 				if(bps != 8 && bps != 16) {
375 					if(bps == 24 || bps == 32) {
376 						/* let these slide with a warning since they're unambiguous */
377 						flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (uint32_t)wFormatTag, bps);
378 						if(e->treat_warnings_as_errors)
379 							return false;
380 					}
381 					else {
382 						/* @@@ we could add an option to specify left- or right-justified blocks so we knew how to set 'shift' */
383 						flac__utils_printf(stderr, 1, "%s: ERROR: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (uint32_t)wFormatTag, bps);
384 						return false;
385 					}
386 				}
387 				if((bps+7)/8 * channels != block_align) {
388 					flac__utils_printf(stderr, 1, "%s: ERROR: legacy WAVE file has block alignment=%u, bits-per-sample=%u, channels=%u\n", e->inbasefilename, (uint32_t)wFormatTag, block_align, bps, channels);
389 					return false;
390 				}
391 				if(channels > 2 && !options.channel_map_none) {
392 					flac__utils_printf(stderr, 1, "%s: ERROR: WAVE has >2 channels but is not WAVE_FORMAT_EXTENSIBLE; cannot assign channels\n", e->inbasefilename);
393 					return false;
394 				}
395 				FLAC__ASSERT(data_bytes >= 16);
396 				data_bytes -= 16;
397 			}
398 			else {
399 				if(data_bytes < 40) {
400 					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with size %u\n", e->inbasefilename, (uint32_t)data_bytes);
401 					return false;
402 				}
403 				/* cbSize */
404 				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
405 					return false;
406 				if(x < 22) {
407 					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with cbSize %u\n", e->inbasefilename, (uint32_t)x);
408 					return false;
409 				}
410 				/* valid bps */
411 				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
412 					return false;
413 				if((uint32_t)x > bps) {
414 					flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", e->inbasefilename, (uint32_t)x, bps);
415 					return false;
416 				}
417 				shift = bps - (uint32_t)x;
418 				/* channel mask */
419 				if(!read_uint32(e->fin, /*big_endian=*/false, &channel_mask, e->inbasefilename))
420 					return false;
421 
422 				if(count_channel_mask_bits(channel_mask) > channels) {
423 					flac__utils_printf(stderr, 1, "%s: WARNING: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has extra bits for non-existant channels (#channels=%u)\n", e->inbasefilename, (uint32_t)channel_mask, channels);
424 					if(e->treat_warnings_as_errors)
425 						return false;
426 				}
427 				/* first part of GUID */
428 				if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
429 					return false;
430 				if(x != 1) {
431 					flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE chunk with non-PCM format %u\n", e->inbasefilename, (uint32_t)x);
432 					return false;
433 				}
434 				data_bytes -= 26;
435 			}
436 
437 			e->info.bytes_per_wide_sample = channels * (bps / 8);
438 
439 			/* skip any extra data in the fmt chunk */
440 			if(!fskip_ahead(e->fin, data_bytes)) {
441 				flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'fmt' data\n", e->inbasefilename);
442 				return false;
443 			}
444 
445 			got_fmt_chunk = true;
446 		}
447 		else if(
448 			!memcmp(chunk_id, "data", 4) &&
449 			(e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "data\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 16))
450 		) { /* data chunk */
451 			FLAC__uint32 xx;
452 			FLAC__uint64 data_bytes;
453 
454 			if(!got_fmt_chunk) {
455 				flac__utils_printf(stderr, 1, "%s: ERROR: got 'data' chunk before 'fmt' chunk\n", e->inbasefilename);
456 				return false;
457 			}
458 
459 			/* data size */
460 			if(e->format != FORMAT_WAVE64) {
461 				if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
462 					return false;
463 				data_bytes = xx;
464 			}
465 			else { /* Wave64 */
466 				if(!read_uint64(e->fin, /*big_endian=*/false, &data_bytes, e->inbasefilename))
467 					return false;
468 				/* subtract size of header */
469 				if (data_bytes < 16+8) {
470 					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'data' chunk has length = 0x00000000%08X\n", e->inbasefilename, (uint32_t)data_bytes);
471 					return false;
472 				}
473 				data_bytes -= (16+8);
474 			}
475 			if(e->format == FORMAT_RF64) {
476 				if(!got_ds64_chunk) {
477 					flac__utils_printf(stderr, 1, "%s: ERROR: RF64 file has no 'ds64' chunk before 'data' chunk\n", e->inbasefilename);
478 					return false;
479 				}
480 				if(data_bytes == 0xffffffff)
481 					data_bytes = ds64_data_size;
482 			}
483 			if(options.ignore_chunk_sizes) {
484 				if(data_bytes) {
485 					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);
486 					if(e->treat_warnings_as_errors)
487 						return false;
488 				}
489 				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 */
490 			}
491 			else if(0 == data_bytes) {
492 				flac__utils_printf(stderr, 1, "%s: ERROR: 'data' chunk has size of 0\n", e->inbasefilename);
493 				return false;
494 			}
495 
496 			e->fmt.iff.data_bytes = data_bytes;
497 
498 			got_data_chunk = true;
499 			break;
500 		}
501 		else {
502 			FLAC__uint32 xx;
503 			FLAC__uint64 skip;
504 			if(!options.format_options.iff.foreign_metadata) {
505 				if(e->format != FORMAT_WAVE64)
506 					flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id);
507 				else
508 					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",
509 						e->inbasefilename,
510 						(uint32_t)((const uint8_t *)chunk_id)[3],
511 						(uint32_t)((const uint8_t *)chunk_id)[2],
512 						(uint32_t)((const uint8_t *)chunk_id)[1],
513 						(uint32_t)((const uint8_t *)chunk_id)[0],
514 						(uint32_t)((const uint8_t *)chunk_id)[5],
515 						(uint32_t)((const uint8_t *)chunk_id)[4],
516 						(uint32_t)((const uint8_t *)chunk_id)[7],
517 						(uint32_t)((const uint8_t *)chunk_id)[6],
518 						(uint32_t)((const uint8_t *)chunk_id)[9],
519 						(uint32_t)((const uint8_t *)chunk_id)[8],
520 						(uint32_t)((const uint8_t *)chunk_id)[10],
521 						(uint32_t)((const uint8_t *)chunk_id)[11],
522 						(uint32_t)((const uint8_t *)chunk_id)[12],
523 						(uint32_t)((const uint8_t *)chunk_id)[13],
524 						(uint32_t)((const uint8_t *)chunk_id)[14],
525 						(uint32_t)((const uint8_t *)chunk_id)[15]
526 					);
527 				if(e->treat_warnings_as_errors)
528 					return false;
529 			}
530 
531 			/* chunk size */
532 			if(e->format != FORMAT_WAVE64) {
533 				if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
534 					return false;
535 				skip = xx;
536 				skip += skip & 1;
537 			}
538 			else { /* Wave64 */
539 				if(!read_uint64(e->fin, /*big_endian=*/false, &skip, e->inbasefilename))
540 					return false;
541 				skip = (skip+7) & (~(FLAC__uint64)7);
542 				/* subtract size of header */
543 				if (skip < 16+8) {
544 					flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 chunk has length = 0x00000000%08X\n", e->inbasefilename, (uint32_t)skip);
545 					return false;
546 				}
547 				skip -= (16+8);
548 			}
549 			if(skip) {
550 				if(!fskip_ahead(e->fin, skip)) {
551 					flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename);
552 					return false;
553 				}
554 			}
555 		}
556 	}
557 
558 	if(!got_fmt_chunk) {
559 		flac__utils_printf(stderr, 1, "%s: ERROR: didn't find fmt chunk\n", e->inbasefilename);
560 		return false;
561 	}
562 	if(!got_data_chunk) {
563 		flac__utils_printf(stderr, 1, "%s: ERROR: didn't find data chunk\n", e->inbasefilename);
564 		return false;
565 	}
566 
567 	e->info.sample_rate = sample_rate;
568 	e->info.channels = channels;
569 	e->info.bits_per_sample = bps;
570 	e->info.shift = shift;
571 	e->info.channel_mask = channel_mask;
572 
573 	return true;
574 }
575 
get_sample_info_aiff(EncoderSession * e,encode_options_t options)576 static FLAC__bool get_sample_info_aiff(EncoderSession *e, encode_options_t options)
577 {
578 	FLAC__bool got_comm_chunk = false, got_ssnd_chunk = false;
579 	uint32_t sample_rate = 0, channels = 0, bps = 0, shift = 0;
580 	FLAC__uint64 sample_frames = 0;
581 	FLAC__uint32 channel_mask = 0;
582 
583 	e->info.is_unsigned_samples = false;
584 	e->info.is_big_endian = true;
585 
586 	/*
587 	 * lookahead[] already has "FORMxxxxAIFF", do chunks
588 	 */
589 	while(!feof(e->fin) && !got_ssnd_chunk) {
590 		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 */
591 		if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, 4, /*eof_ok=*/true, e->inbasefilename)) {
592 			flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename);
593 			return false;
594 		}
595 		if(feof(e->fin))
596 			break;
597 
598 		if(!memcmp(chunk_id, "COMM", 4)) { /* common chunk */
599 			FLAC__uint16 x;
600 			FLAC__uint32 xx;
601 			uint64_t skip;
602 			const FLAC__bool is_aifc = e->format == FORMAT_AIFF_C;
603 			const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18);
604 
605 			if(got_comm_chunk) {
606 				flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'COMM' chunks\n", e->inbasefilename);
607 				return false;
608 			}
609 
610 			/* COMM chunk size */
611 			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
612 				return false;
613 			else if(xx < minimum_comm_size) {
614 				flac__utils_printf(stderr, 1, "%s: ERROR: non-standard %s 'COMM' chunk has length = %u\n", e->inbasefilename, is_aifc? "AIFF-C" : "AIFF", (uint32_t)xx);
615 				return false;
616 			}
617 			else if(!is_aifc && xx != minimum_comm_size) {
618 				flac__utils_printf(stderr, 1, "%s: WARNING: non-standard %s 'COMM' chunk has length = %u, expected %u\n", e->inbasefilename, is_aifc? "AIFF-C" : "AIFF", (uint32_t)xx, minimum_comm_size);
619 				if(e->treat_warnings_as_errors)
620 					return false;
621 			}
622 			skip = (xx-minimum_comm_size)+(xx & 1);
623 
624 			/* number of channels */
625 			if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
626 				return false;
627 			channels = (uint32_t)x;
628 			if(channels > 2 && !options.channel_map_none) {
629 				flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
630 				return false;
631 			}
632 
633 			/* number of sample frames */
634 			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
635 				return false;
636 			sample_frames = xx;
637 
638 			/* bits per sample */
639 			if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
640 				return false;
641 			bps = (uint32_t)x;
642 			shift = (bps%8)? 8-(bps%8) : 0; /* SSND data is always byte-aligned, left-justified but format_input() will double-check */
643 			bps += shift;
644 
645 			/* sample rate */
646 			if(!read_sane_extended(e->fin, &xx, e->inbasefilename))
647 				return false;
648 			sample_rate = xx;
649 
650 			/* check compression type for AIFF-C */
651 			if(is_aifc) {
652 				if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
653 					return false;
654 				if(xx == 0x736F7774) /* "sowt" */
655 					e->info.is_big_endian = false;
656 				else if(xx == 0x4E4F4E45) /* "NONE" */
657 					; /* nothing to do, we already default to big-endian */
658 				else {
659 					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));
660 					return false;
661 				}
662 			}
663 
664 			/* set channel mapping */
665 			/* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
666 			/* front left, front right, center, LFE, back left, back right, surround left, surround right */
667 			/* specs say the channel ordering is:
668 			 *                             1     2   3   4   5   6
669 			 * ___________________________________________________
670 			 * 2         stereo            l     r
671 			 * 3                           l     r   c
672 			 * 4                           l     c   r   S
673 			 * quad (ambiguous with 4ch)  Fl    Fr   Bl  Br
674 			 * 5                          Fl     Fr  Fc  Sl  Sr
675 			 * 6                           l     lc  c   r   rc  S
676 			 * 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
677 			 * so we only have unambiguous mappings for 2, 3, and 5 channels
678 			 */
679 			if(
680 				options.channel_map_none ||
681 				channels == 1 || /* 1 channel: (mono) */
682 				channels == 2 || /* 2 channels: left, right */
683 				channels == 3 || /* 3 channels: left, right, center */
684 				channels == 5    /* 5 channels: front left, front right, center, surround left, surround right */
685 			) {
686 				/* keep default channel order */
687 			}
688 			else {
689 				flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
690 				return false;
691 			}
692 
693 			e->info.bytes_per_wide_sample = channels * (bps / 8);
694 
695 			/* skip any extra data in the COMM chunk */
696 			if(!fskip_ahead(e->fin, skip)) {
697 				flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra COMM data\n", e->inbasefilename);
698 				return false;
699 			}
700 
701 			got_comm_chunk = true;
702 		}
703 		else if(!memcmp(chunk_id, "SSND", 4) && !got_ssnd_chunk) { /* sound data chunk */
704 			FLAC__uint32 xx;
705 			FLAC__uint64 data_bytes;
706 			uint32_t offset = 0;
707 
708 			if(!got_comm_chunk) {
709 				flac__utils_printf(stderr, 1, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", e->inbasefilename);
710 				return false;
711 			}
712 
713 			/* SSND chunk size */
714 			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
715 				return false;
716 			data_bytes = xx;
717 			if(options.ignore_chunk_sizes) {
718 				if(data_bytes) {
719 					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);
720 					if(e->treat_warnings_as_errors)
721 						return false;
722 				}
723 				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 */
724 			}
725 			else if(data_bytes <= 8) {
726 				flac__utils_printf(stderr, 1, "%s: ERROR: 'SSND' chunk has size <= 8\n", e->inbasefilename);
727 				return false;
728 			}
729 			else {
730 				data_bytes -= 8; /* discount the offset and block size fields */
731 			}
732 
733 			/* offset */
734 			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
735 				return false;
736 			offset = xx;
737 			data_bytes -= offset;
738 
739 			/* block size */
740 			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
741 				return false;
742 			if(xx && !options.ignore_chunk_sizes)
743 				data_bytes -= (xx - (data_bytes % xx));
744 			if(options.ignore_chunk_sizes) {
745 				if(xx) {
746 					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);
747 					if(e->treat_warnings_as_errors)
748 						return false;
749 				}
750 			}
751 
752 			/* skip any SSND offset bytes */
753 			if(!fskip_ahead(e->fin, offset)) {
754 				flac__utils_printf(stderr, 1, "%s: ERROR: skipping offset in SSND chunk\n", e->inbasefilename);
755 				return false;
756 			}
757 
758 			e->fmt.iff.data_bytes = data_bytes;
759 
760 			got_ssnd_chunk = true;
761 		}
762 		else {
763 			FLAC__uint32 xx;
764 			if(!options.format_options.iff.foreign_metadata) {
765 				flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id);
766 				if(e->treat_warnings_as_errors)
767 					return false;
768 			}
769 
770 			/* chunk size */
771 			if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
772 				return false;
773 			else {
774 				uint64_t skip = xx + (xx & 1);
775 
776 				FLAC__ASSERT(skip <= LONG_MAX);
777 				if(!fskip_ahead(e->fin, skip)) {
778 					flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename);
779 					return false;
780 				}
781 			}
782 		}
783 	}
784 
785 	if(!got_comm_chunk) {
786 		flac__utils_printf(stderr, 1, "%s: ERROR: didn't find COMM chunk\n", e->inbasefilename);
787 		return false;
788 	}
789 	if(!got_ssnd_chunk && sample_frames) {
790 		flac__utils_printf(stderr, 1, "%s: ERROR: didn't find SSND chunk\n", e->inbasefilename);
791 		return false;
792 	}
793 
794 	e->info.sample_rate = sample_rate;
795 	e->info.channels = channels;
796 	e->info.bits_per_sample = bps;
797 	e->info.shift = shift;
798 	e->info.channel_mask = channel_mask;
799 
800 	return true;
801 }
802 
get_sample_info_flac(EncoderSession * e)803 static FLAC__bool get_sample_info_flac(EncoderSession *e)
804 {
805 	if (!(
806 		FLAC__stream_decoder_set_md5_checking(e->fmt.flac.decoder, false) &&
807 		FLAC__stream_decoder_set_metadata_respond_all(e->fmt.flac.decoder)
808 	)) {
809 		flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", e->inbasefilename);
810 		return false;
811 	}
812 
813 	if (e->format == FORMAT_OGGFLAC) {
814 		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) {
815 			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));
816 			return false;
817 		}
818 	}
819 	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) {
820 		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));
821 		return false;
822 	}
823 
824 	if (!FLAC__stream_decoder_process_until_end_of_metadata(e->fmt.flac.decoder) || e->fmt.flac.client_data.fatal_error) {
825 		if (e->fmt.flac.client_data.fatal_error)
826 			flac__utils_printf(stderr, 1, "%s: ERROR: out of memory or too many metadata blocks while reading metadata in FLAC input\n", e->inbasefilename);
827 		else
828 			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));
829 		return false;
830 	}
831 
832 	if (e->fmt.flac.client_data.num_metadata_blocks == 0) {
833 		flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, got no metadata blocks\n", e->inbasefilename);
834 		return false;
835 	}
836 	else if (e->fmt.flac.client_data.metadata_blocks[0]->type != FLAC__METADATA_TYPE_STREAMINFO) {
837 		flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, first metadata block is not STREAMINFO\n", e->inbasefilename);
838 		return false;
839 	}
840 	else if (e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples == 0) {
841 		flac__utils_printf(stderr, 1, "%s: ERROR: FLAC input has STREAMINFO with unknown total samples which is not supported\n", e->inbasefilename);
842 		return false;
843 	}
844 
845 	e->info.sample_rate = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.sample_rate;
846 	e->info.channels = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.channels;
847 	e->info.bits_per_sample = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.bits_per_sample;
848 	e->info.shift = 0;
849 	e->info.bytes_per_wide_sample = 0;
850 	e->info.is_unsigned_samples = false; /* not applicable for FLAC input */
851 	e->info.is_big_endian = false; /* not applicable for FLAC input */
852 	e->info.channel_mask = 0;
853 
854 	return true;
855 }
856 
857 /*
858  * public routines
859  */
flac__encode_file(FILE * infile,FLAC__off_t infilesize,const char * infilename,const char * outfilename,const FLAC__byte * lookahead,uint32_t lookahead_length,encode_options_t options)860 int flac__encode_file(FILE *infile, FLAC__off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, uint32_t lookahead_length, encode_options_t options)
861 {
862 	EncoderSession encoder_session;
863 	size_t channel_map[FLAC__MAX_CHANNELS];
864 
865 	if(!EncoderSession_construct(&encoder_session, options, infilesize, infile, infilename, outfilename, lookahead, lookahead_length))
866 		return 1;
867 
868 	/* initialize default channel map that preserves channel order */
869 	{
870 		size_t i;
871 		for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++)
872 			channel_map[i] = i;
873 	}
874 
875 	/* read foreign metadata if requested */
876 	if(EncoderSession_format_is_iff(&encoder_session) && options.format_options.iff.foreign_metadata) {
877 		const char *error;
878 		if(!(
879 			options.format == FORMAT_WAVE || options.format == FORMAT_RF64?
880 				flac__foreign_metadata_read_from_wave(options.format_options.iff.foreign_metadata, infilename, &error) :
881 			options.format == FORMAT_WAVE64?
882 				flac__foreign_metadata_read_from_wave64(options.format_options.iff.foreign_metadata, infilename, &error) :
883 				flac__foreign_metadata_read_from_aiff(options.format_options.iff.foreign_metadata, infilename, &error)
884 		)) {
885 			if(options.relaxed_foreign_metadata_handling) {
886 				flac__utils_printf(stderr, 1, "%s: WARNING reading foreign metadata: %s\n", encoder_session.inbasefilename, error);
887 				if(encoder_session.treat_warnings_as_errors)
888 					return EncoderSession_finish_error(&encoder_session);
889 			}
890 			else {
891 				flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", encoder_session.inbasefilename, error);
892 				return EncoderSession_finish_error(&encoder_session);
893 			}
894 		}
895 	}
896 
897 	/* initialize encoder session with info about the audio (channels/bps/resolution/endianness/etc) */
898 	switch(options.format) {
899 		case FORMAT_RAW:
900 			if(!get_sample_info_raw(&encoder_session, options))
901 				return EncoderSession_finish_error(&encoder_session);
902 			break;
903 		case FORMAT_WAVE:
904 		case FORMAT_WAVE64:
905 		case FORMAT_RF64:
906 			if(!get_sample_info_wave(&encoder_session, options))
907 				return EncoderSession_finish_error(&encoder_session);
908 			break;
909 		case FORMAT_AIFF:
910 		case FORMAT_AIFF_C:
911 			if(!get_sample_info_aiff(&encoder_session, options))
912 				return EncoderSession_finish_error(&encoder_session);
913 			break;
914 		case FORMAT_FLAC:
915 		case FORMAT_OGGFLAC:
916 			/*
917 			 * set up FLAC decoder for the input
918 			 */
919 			if (0 == (encoder_session.fmt.flac.decoder = FLAC__stream_decoder_new())) {
920 				flac__utils_printf(stderr, 1, "%s: ERROR: creating decoder for FLAC input\n", encoder_session.inbasefilename);
921 				return EncoderSession_finish_error(&encoder_session);
922 			}
923 			if(!get_sample_info_flac(&encoder_session))
924 				return EncoderSession_finish_error(&encoder_session);
925 			break;
926 		default:
927 			FLAC__ASSERT(0);
928 			/* double protection */
929 			return EncoderSession_finish_error(&encoder_session);
930 	}
931 
932 	/* some more checks */
933 	if(encoder_session.info.channels == 0 || encoder_session.info.channels > FLAC__MAX_CHANNELS) {
934 		flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u\n", encoder_session.inbasefilename, encoder_session.info.channels);
935 		return EncoderSession_finish_error(&encoder_session);
936 	}
937 	if(!FLAC__format_sample_rate_is_valid(encoder_session.info.sample_rate)) {
938 		flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, encoder_session.info.sample_rate);
939 		return EncoderSession_finish_error(&encoder_session);
940 	}
941 	if(encoder_session.info.bits_per_sample-encoder_session.info.shift < 4 || encoder_session.info.bits_per_sample-encoder_session.info.shift > 32) {
942 		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);
943 		return EncoderSession_finish_error(&encoder_session);
944 	}
945 
946 	{
947 		FLAC__uint64 total_samples_in_input; /* WATCHOUT: may be 0 to mean "unknown" */
948 		FLAC__uint64 skip;
949 		FLAC__uint64 until; /* a value of 0 mean end-of-stream (i.e. --until=-0) */
950 		uint32_t consecutive_eos_count = 0;
951 
952 		switch(options.format) {
953 			case FORMAT_RAW:
954 				if(infilesize < 0)
955 					total_samples_in_input = 0;
956 				else
957 					total_samples_in_input = (FLAC__uint64)infilesize / encoder_session.info.bytes_per_wide_sample;
958 				break;
959 			case FORMAT_WAVE:
960 			case FORMAT_WAVE64:
961 			case FORMAT_RF64:
962 			case FORMAT_AIFF:
963 			case FORMAT_AIFF_C:
964 				/* truncation in the division removes any padding byte that was counted in encoder_session.fmt.iff.data_bytes */
965 				total_samples_in_input = encoder_session.fmt.iff.data_bytes / encoder_session.info.bytes_per_wide_sample;
966 
967 				/* check for chunks trailing the audio data */
968 				if(!options.ignore_chunk_sizes && !options.format_options.iff.foreign_metadata
969 				   && infilesize != (FLAC__off_t)(-1)) {
970 					FLAC__off_t current_position = ftello(encoder_session.fin);
971 					if(current_position > 0) {
972 						FLAC__uint64 end_of_data_chunk = current_position + encoder_session.fmt.iff.data_bytes;
973 						if(end_of_data_chunk < (FLAC__uint64)infilesize) {
974 							flac__utils_printf(stderr, 1, "%s: WARNING: there is data trailing the audio data. Use --keep-foreign-metadata or --ignore-chunk-sizes to keep it\n", encoder_session.inbasefilename);
975 							if(encoder_session.treat_warnings_as_errors)
976 								return EncoderSession_finish_error(&encoder_session);
977 						}
978 						else if(end_of_data_chunk > (FLAC__uint64)infilesize) {
979 							flac__utils_printf(stderr, 1, "%s: WARNING: the length of the data chunk overruns the end of the file. Please consult the manual on the --ignore-chunk-sizes option\n", encoder_session.inbasefilename);
980 							if(encoder_session.treat_warnings_as_errors)
981 								return EncoderSession_finish_error(&encoder_session);
982 						}
983 					}
984 				}
985 				break;
986 			case FORMAT_FLAC:
987 			case FORMAT_OGGFLAC:
988 				total_samples_in_input = encoder_session.fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples;
989 				break;
990 			default:
991 				FLAC__ASSERT(0);
992 				/* double protection */
993 				return EncoderSession_finish_error(&encoder_session);
994 		}
995 
996 		/*
997 		 * now that we know the sample rate, canonicalize the
998 		 * --skip string to an absolute sample number:
999 		 */
1000 		if(!flac__utils_canonicalize_skip_until_specification(&options.skip_specification, encoder_session.info.sample_rate)) {
1001 			flac__utils_printf(stderr, 1, "%s: ERROR: value of --skip is too large\n", encoder_session.inbasefilename, encoder_session.info.bits_per_sample-encoder_session.info.shift);
1002 			return EncoderSession_finish_error(&encoder_session);
1003 		}
1004 		FLAC__ASSERT(options.skip_specification.value.samples >= 0);
1005 		skip = (FLAC__uint64)options.skip_specification.value.samples;
1006 
1007 		/*
1008 		 * now that we possibly know the input size, canonicalize the
1009 		 * --until string to an absolute sample number:
1010 		 */
1011 		if(!canonicalize_until_specification(&options.until_specification, encoder_session.inbasefilename, encoder_session.info.sample_rate, skip, total_samples_in_input))
1012 			return EncoderSession_finish_error(&encoder_session);
1013 		until = (FLAC__uint64)options.until_specification.value.samples;
1014 
1015 		/* adjust encoding parameters based on skip and until values */
1016 		switch(options.format) {
1017 			case FORMAT_RAW:
1018 				FLAC__ASSERT(sizeof(FLAC__off_t) == 8);
1019 				if(skip >= INT64_MAX / encoder_session.info.bytes_per_wide_sample) {
1020 					flac__utils_printf(stderr, 1, "%s: ERROR: value of --skip is too large\n", encoder_session.inbasefilename, encoder_session.info.bits_per_sample-encoder_session.info.shift);
1021 					return EncoderSession_finish_error(&encoder_session);
1022 				}
1023 				infilesize -= (FLAC__off_t)skip * encoder_session.info.bytes_per_wide_sample;
1024 				encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1025 				break;
1026 			case FORMAT_WAVE:
1027 			case FORMAT_WAVE64:
1028 			case FORMAT_RF64:
1029 			case FORMAT_AIFF:
1030 			case FORMAT_AIFF_C:
1031 				FLAC__ASSERT(sizeof(FLAC__off_t) == 8);
1032 				if(skip >= INT64_MAX / encoder_session.info.bytes_per_wide_sample) {
1033 					flac__utils_printf(stderr, 1, "%s: ERROR: value of --skip is too large\n", encoder_session.inbasefilename, encoder_session.info.bits_per_sample-encoder_session.info.shift);
1034 					return EncoderSession_finish_error(&encoder_session);
1035 				}
1036 				encoder_session.fmt.iff.data_bytes -= skip * encoder_session.info.bytes_per_wide_sample;
1037 				if(options.ignore_chunk_sizes) {
1038 					encoder_session.total_samples_to_encode = 0;
1039 					FLAC__ASSERT(0 == until);
1040 				}
1041 				else {
1042 					encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1043 				}
1044 				break;
1045 			case FORMAT_FLAC:
1046 			case FORMAT_OGGFLAC:
1047 				encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1048 				break;
1049 			default:
1050 				FLAC__ASSERT(0);
1051 				/* double protection */
1052 				return EncoderSession_finish_error(&encoder_session);
1053 		}
1054 		if(until > 0) {
1055 			const FLAC__uint64 trim = total_samples_in_input - until;
1056 			FLAC__ASSERT(total_samples_in_input > 0);
1057 			if(options.format == FORMAT_RAW)
1058 				infilesize -= (FLAC__off_t)trim * encoder_session.info.bytes_per_wide_sample;
1059 			else if(EncoderSession_format_is_iff(&encoder_session))
1060 				encoder_session.fmt.iff.data_bytes -= trim * encoder_session.info.bytes_per_wide_sample;
1061 			encoder_session.total_samples_to_encode -= trim;
1062 		}
1063 		switch(options.format) {
1064 			case FORMAT_RAW:
1065 				encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample;
1066 				break;
1067 			case FORMAT_WAVE:
1068 				/* +44 for the size of the WAVE headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1069 				encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 44;
1070 				break;
1071 			case FORMAT_WAVE64:
1072 				/* +44 for the size of the WAVE headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1073 				encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 104;
1074 				break;
1075 			case FORMAT_RF64:
1076 				/* +72 for the size of the RF64 headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1077 				encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 80;
1078 				break;
1079 			case FORMAT_AIFF:
1080 			case FORMAT_AIFF_C:
1081 				/* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1082 				encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 54;
1083 				break;
1084 			case FORMAT_FLAC:
1085 			case FORMAT_OGGFLAC:
1086 				if(infilesize < 0)
1087 					/* if we don't know, use 0 as hint to progress indicator (which is the only place this is used): */
1088 					encoder_session.unencoded_size = 0;
1089 				else if(skip == 0 && until == 0)
1090 					encoder_session.unencoded_size = (FLAC__uint64)infilesize;
1091 				else if(total_samples_in_input)
1092 					encoder_session.unencoded_size = (FLAC__uint64)infilesize * encoder_session.total_samples_to_encode / total_samples_in_input;
1093 				else
1094 					encoder_session.unencoded_size = (FLAC__uint64)infilesize;
1095 				break;
1096 			default:
1097 				FLAC__ASSERT(0);
1098 				/* double protection */
1099 				return EncoderSession_finish_error(&encoder_session);
1100 		}
1101 
1102 		if(encoder_session.total_samples_to_encode == 0) {
1103 			encoder_session.unencoded_size = 0;
1104 			flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n");
1105 		}
1106 
1107 		if(options.format == FORMAT_FLAC || options.format == FORMAT_OGGFLAC)
1108 			encoder_session.fmt.flac.client_data.samples_left_to_process = encoder_session.total_samples_to_encode;
1109 
1110 		stats_new_file();
1111 		/* init the encoder */
1112 		if(!EncoderSession_init_encoder(&encoder_session, options))
1113 			return EncoderSession_finish_error(&encoder_session);
1114 
1115 		/* skip over any samples as requested */
1116 		if(skip > 0) {
1117 			switch(options.format) {
1118 				case FORMAT_RAW:
1119 					{
1120 						uint32_t skip_bytes = encoder_session.info.bytes_per_wide_sample * (uint32_t)skip;
1121 						if(skip_bytes > lookahead_length) {
1122 							skip_bytes -= lookahead_length;
1123 							lookahead_length = 0;
1124 							if(!fskip_ahead(encoder_session.fin, skip_bytes)) {
1125 								flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1126 								return EncoderSession_finish_error(&encoder_session);
1127 							}
1128 						}
1129 						else {
1130 							lookahead += skip_bytes;
1131 							lookahead_length -= skip_bytes;
1132 						}
1133 					}
1134 					break;
1135 				case FORMAT_WAVE:
1136 				case FORMAT_WAVE64:
1137 				case FORMAT_RF64:
1138 				case FORMAT_AIFF:
1139 				case FORMAT_AIFF_C:
1140 					if(!fskip_ahead(encoder_session.fin, skip * encoder_session.info.bytes_per_wide_sample)) {
1141 						flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1142 						return EncoderSession_finish_error(&encoder_session);
1143 					}
1144 					break;
1145 				case FORMAT_FLAC:
1146 				case FORMAT_OGGFLAC:
1147 					/*
1148 					 * have to wait until the FLAC encoder is set up for writing
1149 					 * before any seeking in the input FLAC file, because the seek
1150 					 * itself will usually call the decoder's write callback, and
1151 					 * our decoder's write callback passes samples to our FLAC
1152 					 * encoder
1153 					 */
1154 					if(!FLAC__stream_decoder_seek_absolute(encoder_session.fmt.flac.decoder, skip)) {
1155 						flac__utils_printf(stderr, 1, "%s: ERROR while skipping samples, FLAC decoder state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(encoder_session.fmt.flac.decoder));
1156 						return EncoderSession_finish_error(&encoder_session);
1157 					}
1158 					break;
1159 				default:
1160 					FLAC__ASSERT(0);
1161 					/* double protection */
1162 					return EncoderSession_finish_error(&encoder_session);
1163 			}
1164 		}
1165 
1166 		/*
1167 		 * now do samples from the file
1168 		 */
1169 		switch(options.format) {
1170 			case FORMAT_RAW:
1171 				if(infilesize < 0) {
1172 					size_t bytes_read;
1173 					while(!feof(infile)) {
1174 						if(lookahead_length > 0) {
1175 							FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample);
1176 							memcpy(ubuffer.u8, lookahead, lookahead_length);
1177 							bytes_read = fread(ubuffer.u8+lookahead_length, sizeof(uint8_t), CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
1178 							if(ferror(infile)) {
1179 								flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1180 								return EncoderSession_finish_error(&encoder_session);
1181 							}
1182 							lookahead_length = 0;
1183 						}
1184 						else
1185 							bytes_read = fread(ubuffer.u8, sizeof(uint8_t), CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample, infile);
1186 
1187 						if(bytes_read == 0) {
1188 							if(ferror(infile)) {
1189 								flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1190 								return EncoderSession_finish_error(&encoder_session);
1191 							}
1192 						}
1193 						else if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1194 							flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1195 							return EncoderSession_finish_error(&encoder_session);
1196 						}
1197 						else {
1198 							uint32_t wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1199 							if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map))
1200 								return EncoderSession_finish_error(&encoder_session);
1201 
1202 							if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1203 								print_error_with_state(&encoder_session, "ERROR during encoding");
1204 								return EncoderSession_finish_error(&encoder_session);
1205 							}
1206 						}
1207 					}
1208 				}
1209 				else {
1210 					size_t bytes_read;
1211 					const FLAC__uint64 max_input_bytes = infilesize;
1212 					FLAC__uint64 total_input_bytes_read = 0;
1213 					while(total_input_bytes_read < max_input_bytes) {
1214 						{
1215 							size_t wanted = (CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample);
1216 							wanted = (size_t) min((FLAC__uint64)wanted, max_input_bytes - total_input_bytes_read);
1217 
1218 							if(lookahead_length > 0) {
1219 								if(lookahead_length <= wanted) {
1220 									memcpy(ubuffer.u8, lookahead, lookahead_length);
1221 									wanted -= lookahead_length;
1222 									bytes_read = lookahead_length;
1223 								}
1224 								else {
1225 									/* This happens when --until is used on a very short file */
1226 									FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample);
1227 									memcpy(ubuffer.u8, lookahead, wanted);
1228 									wanted = 0;
1229 									bytes_read = wanted;
1230 								}
1231 								if(wanted > 0) {
1232 									bytes_read += fread(ubuffer.u8+lookahead_length, sizeof(uint8_t), wanted, infile);
1233 									if(ferror(infile)) {
1234 										flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1235 										return EncoderSession_finish_error(&encoder_session);
1236 									}
1237 								}
1238 								lookahead_length = 0;
1239 							}
1240 							else
1241 								bytes_read = fread(ubuffer.u8, sizeof(uint8_t), wanted, infile);
1242 						}
1243 
1244 						if(bytes_read == 0) {
1245 							if(ferror(infile)) {
1246 								flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1247 								return EncoderSession_finish_error(&encoder_session);
1248 							}
1249 							else if(feof(infile)) {
1250 								flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %" PRIu64 " samples, got %" PRIu64 " samples\n", encoder_session.inbasefilename, encoder_session.total_samples_to_encode, encoder_session.samples_written);
1251 								if(encoder_session.treat_warnings_as_errors)
1252 									return EncoderSession_finish_error(&encoder_session);
1253 								total_input_bytes_read = max_input_bytes;
1254 							}
1255 						}
1256 						else {
1257 							if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1258 								flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1259 								return EncoderSession_finish_error(&encoder_session);
1260 							}
1261 							else {
1262 								uint32_t wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1263 								if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map))
1264 									return EncoderSession_finish_error(&encoder_session);
1265 
1266 								if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1267 									print_error_with_state(&encoder_session, "ERROR during encoding");
1268 									return EncoderSession_finish_error(&encoder_session);
1269 								}
1270 								total_input_bytes_read += bytes_read;
1271 							}
1272 						}
1273 					}
1274 				}
1275 				break;
1276 			case FORMAT_WAVE:
1277 			case FORMAT_WAVE64:
1278 			case FORMAT_RF64:
1279 			case FORMAT_AIFF:
1280 			case FORMAT_AIFF_C:
1281 				while(encoder_session.fmt.iff.data_bytes > 0) {
1282 					const size_t bytes_to_read =
1283 						(size_t) min (sizeof (ubuffer.u8),
1284 							min (encoder_session.fmt.iff.data_bytes,
1285 								CHUNK_OF_SAMPLES * (uint64_t) encoder_session.info.bytes_per_wide_sample));
1286 					size_t bytes_read = fread(ubuffer.u8, sizeof(uint8_t), bytes_to_read, infile);
1287 					if(bytes_read == 0) {
1288 						if(ferror(infile)) {
1289 							flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1290 							return EncoderSession_finish_error(&encoder_session);
1291 						}
1292 						else if(feof(infile)) {
1293 							if(options.ignore_chunk_sizes) {
1294 								flac__utils_printf(stderr, 1, "%s: INFO: hit EOF with --ignore-chunk-sizes, got %" PRIu64 " samples\n", encoder_session.inbasefilename, encoder_session.samples_written);
1295 							}
1296 							else {
1297 								flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %" PRIu64 " samples, got %" PRIu64 " samples\n", encoder_session.inbasefilename, encoder_session.total_samples_to_encode, encoder_session.samples_written);
1298 								if(encoder_session.treat_warnings_as_errors)
1299 									return EncoderSession_finish_error(&encoder_session);
1300 							}
1301 							encoder_session.fmt.iff.data_bytes = 0;
1302 						}
1303 					}
1304 					else {
1305 						if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1306 							flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1307 							return EncoderSession_finish_error(&encoder_session);
1308 						}
1309 						else {
1310 							uint32_t wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1311 							if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map))
1312 								return EncoderSession_finish_error(&encoder_session);
1313 
1314 							if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1315 								print_error_with_state(&encoder_session, "ERROR during encoding");
1316 								return EncoderSession_finish_error(&encoder_session);
1317 							}
1318 							encoder_session.fmt.iff.data_bytes -= bytes_read;
1319 						}
1320 					}
1321 				}
1322 				break;
1323 			case FORMAT_FLAC:
1324 			case FORMAT_OGGFLAC:
1325 				consecutive_eos_count = 0;
1326 				while(!encoder_session.fmt.flac.client_data.fatal_error && encoder_session.fmt.flac.client_data.samples_left_to_process > 0) {
1327 					FLAC__StreamDecoderState decoder_state;
1328 					/* We can also hit the end of stream without samples_left_to_process
1329 					 * going to 0 if there are errors and continue_through_decode_errors
1330 					 * is on, so we want to break in that case too:
1331 					 */
1332 					decoder_state = FLAC__stream_decoder_get_state(encoder_session.fmt.flac.decoder);
1333 					if(encoder_session.continue_through_decode_errors && decoder_state == FLAC__STREAM_DECODER_END_OF_STREAM)
1334 						break;
1335 
1336 					consecutive_eos_count = decoder_state == FLAC__STREAM_DECODER_END_OF_STREAM ? consecutive_eos_count + 1 : 0;
1337 
1338 					/* Exit loop if we get two or more consecutive FLAC__STREAM_DECODER_END_OF_STREAM events. */
1339 					if(consecutive_eos_count >= 2) {
1340 						flac__utils_printf(stderr, 1, "%s: ERROR: %d consecutive FLAC__STREAM_DECODER_END_OF_STREAM events.\n", encoder_session.inbasefilename, consecutive_eos_count);
1341 						break;
1342 					}
1343 
1344 					if(decoder_state == FLAC__STREAM_DECODER_ABORTED || !FLAC__stream_decoder_process_single(encoder_session.fmt.flac.decoder)) {
1345 						flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(encoder_session.fmt.flac.decoder));
1346 						return EncoderSession_finish_error(&encoder_session);
1347 					}
1348 				}
1349 				if(encoder_session.fmt.flac.client_data.fatal_error) {
1350 					flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(encoder_session.fmt.flac.decoder));
1351 					return EncoderSession_finish_error(&encoder_session);
1352 				}
1353 				break;
1354 			default:
1355 				FLAC__ASSERT(0);
1356 				/* double protection */
1357 				return EncoderSession_finish_error(&encoder_session);
1358 		}
1359 
1360 	}
1361 
1362 	return EncoderSession_finish_ok(
1363 		&encoder_session,
1364 		EncoderSession_format_is_iff(&encoder_session)? options.format_options.iff.foreign_metadata : 0,
1365 		options.error_on_compression_fail
1366 	);
1367 }
1368 
EncoderSession_construct(EncoderSession * e,encode_options_t options,FLAC__off_t infilesize,FILE * infile,const char * infilename,const char * outfilename,const FLAC__byte * lookahead,uint32_t lookahead_length)1369 FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, FLAC__off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, uint32_t lookahead_length)
1370 {
1371 	uint32_t i;
1372 	FLAC__uint32 test = 1;
1373 
1374 	/*
1375 	 * initialize globals
1376 	 */
1377 
1378 	is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
1379 
1380 	for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1381 		input_[i] = &(in_[i][0]);
1382 
1383 
1384 	/*
1385 	 * initialize instance
1386 	 */
1387 
1388 #if FLAC__HAS_OGG
1389 	e->use_ogg = options.use_ogg;
1390 #endif
1391 	e->verify = options.verify;
1392 	e->treat_warnings_as_errors = options.treat_warnings_as_errors;
1393 	e->continue_through_decode_errors = options.continue_through_decode_errors;
1394 
1395 	e->is_stdout = (0 == strcmp(outfilename, "-"));
1396 	e->outputfile_opened = false;
1397 
1398 	e->inbasefilename = grabbag__file_get_basename(infilename);
1399 	e->infilename = infilename;
1400 	e->outfilename = outfilename;
1401 
1402 	e->total_samples_to_encode = 0;
1403 	e->unencoded_size = 0;
1404 	e->bytes_written = 0;
1405 	e->samples_written = 0;
1406 #if 0 /* in case time.h with clock() isn't available for some reason */
1407 	e->stats_frames_interval = 0;
1408 	e->old_frames_written = 0;
1409 #else
1410 	e->old_clock_t = 0;
1411 #endif
1412 	e->compression_ratio = 0.0;
1413 
1414 	memset(&e->info, 0, sizeof(e->info));
1415 
1416 	e->format = options.format;
1417 
1418 	switch(options.format) {
1419 		case FORMAT_RAW:
1420 			break;
1421 		case FORMAT_WAVE:
1422 		case FORMAT_WAVE64:
1423 		case FORMAT_RF64:
1424 		case FORMAT_AIFF:
1425 		case FORMAT_AIFF_C:
1426 			e->fmt.iff.data_bytes = 0;
1427 			break;
1428 		case FORMAT_FLAC:
1429 		case FORMAT_OGGFLAC:
1430 			e->fmt.flac.decoder = 0;
1431 			e->fmt.flac.client_data.filesize = infilesize;
1432 			e->fmt.flac.client_data.lookahead = lookahead;
1433 			e->fmt.flac.client_data.lookahead_length = lookahead_length;
1434 			e->fmt.flac.client_data.num_metadata_blocks = 0;
1435 			e->fmt.flac.client_data.samples_left_to_process = 0;
1436 			e->fmt.flac.client_data.fatal_error = false;
1437 			break;
1438 		default:
1439 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1440 			FLAC__ASSERT(0);
1441 #endif
1442 			/* double protection */
1443 			return false;
1444 	}
1445 
1446 	e->encoder = 0;
1447 
1448 	e->fin = infile;
1449 	e->seek_table_template = 0;
1450 
1451 	if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1452 		flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1453 		return false;
1454 	}
1455 
1456 	e->encoder = FLAC__stream_encoder_new();
1457 	if(0 == e->encoder) {
1458 		flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1459 		EncoderSession_destroy(e);
1460 		return false;
1461 	}
1462 
1463 	return true;
1464 }
1465 
EncoderSession_destroy(EncoderSession * e)1466 void EncoderSession_destroy(EncoderSession *e)
1467 {
1468 	if(e->format == FORMAT_FLAC || e->format == FORMAT_OGGFLAC) {
1469 		size_t i;
1470 		if(e->fmt.flac.decoder)
1471 			FLAC__stream_decoder_delete(e->fmt.flac.decoder);
1472 		e->fmt.flac.decoder = 0;
1473 		for(i = 0; i < e->fmt.flac.client_data.num_metadata_blocks; i++)
1474 			FLAC__metadata_object_delete(e->fmt.flac.client_data.metadata_blocks[i]);
1475 		e->fmt.flac.client_data.num_metadata_blocks = 0;
1476 	}
1477 
1478 	if(e->fin != stdin)
1479 		fclose(e->fin);
1480 
1481 	if(0 != e->encoder) {
1482 		FLAC__stream_encoder_delete(e->encoder);
1483 		e->encoder = 0;
1484 	}
1485 
1486 	if(0 != e->seek_table_template) {
1487 		FLAC__metadata_object_delete(e->seek_table_template);
1488 		e->seek_table_template = 0;
1489 	}
1490 }
1491 
EncoderSession_finish_ok(EncoderSession * e,foreign_metadata_t * foreign_metadata,FLAC__bool error_on_compression_fail)1492 int EncoderSession_finish_ok(EncoderSession *e, foreign_metadata_t *foreign_metadata, FLAC__bool error_on_compression_fail)
1493 {
1494 	FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1495 	int ret = 0;
1496 	FLAC__bool verify_error = false;
1497 
1498 	if(e->encoder) {
1499 		fse_state = FLAC__stream_encoder_get_state(e->encoder);
1500 		ret = FLAC__stream_encoder_finish(e->encoder)? 0 : 1;
1501 		verify_error =
1502 			fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA ||
1503 			FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA
1504 		;
1505 	}
1506 	/* all errors except verify errors should interrupt the stats */
1507 	if(ret && !verify_error)
1508 		print_error_with_state(e, "ERROR during encoding");
1509 	else if(e->total_samples_to_encode > 0) {
1510 		print_stats(e);
1511 		flac__utils_printf(stderr, 2, "\n");
1512 	}
1513 
1514 	if(verify_error) {
1515 		print_verify_error(e);
1516 		ret = 1;
1517 	}
1518 
1519 	/*@@@@@@ should this go here or somewhere else? */
1520 	if(ret == 0 && foreign_metadata) {
1521 		const char *error;
1522 		if(!flac__foreign_metadata_write_to_flac(foreign_metadata, e->infilename, e->outfilename, &error)) {
1523 			flac__utils_printf(stderr, 1, "%s: ERROR: updating foreign metadata in FLAC file: %s\n", e->inbasefilename, error);
1524 			ret = 1;
1525 		}
1526 	}
1527 
1528 	if (e->compression_ratio >= 1.0 && error_on_compression_fail) {
1529 		flac__utils_printf(stderr, 1,
1530 			"FAILURE: Compression failed (ratio %0.3f, should be < 1.0).\n"
1531 			"This happens for some files for one or more of the following reasons:\n"
1532 			" * Recompressing an existing FLAC from a higher to a lower compression setting.\n"
1533 			" * Insufficient input data  (e.g. very short files, < 10000 frames).\n"
1534 			" * The audio data is not compressible (e.g. a full range white noise signal).\n"
1535 			, e->compression_ratio);
1536 		ret = 1;
1537 	}
1538 
1539 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1540         /* Always delete output file when fuzzing */
1541 	flac_unlink(e->outfilename);
1542 #endif
1543 
1544 	EncoderSession_destroy(e);
1545 
1546 	return ret;
1547 }
1548 
EncoderSession_finish_error(EncoderSession * e)1549 int EncoderSession_finish_error(EncoderSession *e)
1550 {
1551 	FLAC__ASSERT(e->encoder);
1552 
1553 	if(e->total_samples_to_encode > 0)
1554 		flac__utils_printf(stderr, 2, "\n");
1555 
1556 	if(FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) {
1557 		print_verify_error(e);
1558 		EncoderSession_destroy(e);
1559 	}
1560 	else if(e->outputfile_opened) {
1561 		/* only want to delete the file if we opened it; otherwise it could be an existing file and our overwrite failed */
1562 		/* Windows cannot unlink an open file, so close it first */
1563 		EncoderSession_destroy(e);
1564 		flac_unlink(e->outfilename);
1565 	}
1566 	else
1567 		EncoderSession_destroy(e);
1568 
1569 	return 1;
1570 }
1571 
1572 typedef struct {
1573 	uint32_t num_metadata;
1574 	FLAC__bool *needs_delete;
1575 	FLAC__StreamMetadata **metadata;
1576 	FLAC__StreamMetadata *cuesheet; /* always needs to be deleted */
1577 } static_metadata_t;
1578 
static_metadata_init(static_metadata_t * m)1579 static void static_metadata_init(static_metadata_t *m)
1580 {
1581 	m->num_metadata = 0;
1582 	m->needs_delete = 0;
1583 	m->metadata = 0;
1584 	m->cuesheet = 0;
1585 }
1586 
static_metadata_clear(static_metadata_t * m)1587 static void static_metadata_clear(static_metadata_t *m)
1588 {
1589 	uint32_t i;
1590 	for(i = 0; i < m->num_metadata; i++)
1591 		if(m->needs_delete[i])
1592 			FLAC__metadata_object_delete(m->metadata[i]);
1593 	if(m->metadata)
1594 		free(m->metadata);
1595 	if(m->needs_delete)
1596 		free(m->needs_delete);
1597 	if(m->cuesheet)
1598 		FLAC__metadata_object_delete(m->cuesheet);
1599 	static_metadata_init(m);
1600 }
1601 
static_metadata_append(static_metadata_t * m,FLAC__StreamMetadata * d,FLAC__bool needs_delete)1602 static FLAC__bool static_metadata_append(static_metadata_t *m, FLAC__StreamMetadata *d, FLAC__bool needs_delete)
1603 {
1604 	void *x;
1605 	if(0 == (x = safe_realloc_nofree_muladd2_(m->metadata, sizeof(*m->metadata), /*times (*/m->num_metadata, /*+*/1/*)*/)))
1606 		return false;
1607 	m->metadata = (FLAC__StreamMetadata**)x;
1608 	if(0 == (x = safe_realloc_nofree_muladd2_(m->needs_delete, sizeof(*m->needs_delete), /*times (*/m->num_metadata, /*+*/1/*)*/)))
1609 		return false;
1610 	m->needs_delete = (FLAC__bool*)x;
1611 	m->metadata[m->num_metadata] = d;
1612 	m->needs_delete[m->num_metadata] = needs_delete;
1613 	m->num_metadata++;
1614 	return true;
1615 }
1616 
EncoderSession_init_encoder(EncoderSession * e,encode_options_t options)1617 FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options)
1618 {
1619 	const uint32_t channels = e->info.channels;
1620 	const uint32_t bps = e->info.bits_per_sample - e->info.shift;
1621 	const uint32_t sample_rate = e->info.sample_rate;
1622 	FLACDecoderData *flac_decoder_data = (e->format == FORMAT_FLAC || e->format == FORMAT_OGGFLAC)? &e->fmt.flac.client_data : 0;
1623 	FLAC__StreamMetadata padding;
1624 	FLAC__StreamMetadata **metadata = 0;
1625 	static_metadata_t static_metadata;
1626 	uint32_t num_metadata = 0, ic;
1627 	FLAC__StreamEncoderInitStatus init_status;
1628 	const FLAC__bool is_cdda = (channels == 1 || channels == 2) && (bps == 16) && (sample_rate == 44100);
1629 	char apodizations[2000];
1630 
1631 	FLAC__ASSERT(sizeof(options.pictures)/sizeof(options.pictures[0]) <= 64);
1632 
1633 	static_metadata_init(&static_metadata);
1634 
1635 	e->replay_gain = options.replay_gain;
1636 
1637 	apodizations[0] = '\0';
1638 
1639 	if(e->replay_gain) {
1640 		if(channels != 1 && channels != 2) {
1641 			flac__utils_printf(stderr, 1, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
1642 			return false;
1643 		}
1644 		if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) {
1645 			flac__utils_printf(stderr, 1, "%s: ERROR, invalid sample rate (%u) for --replay-gain\n", e->inbasefilename, sample_rate);
1646 			return false;
1647 		}
1648 		if(options.is_first_file) {
1649 			if(!grabbag__replaygain_init(sample_rate)) {
1650 				flac__utils_printf(stderr, 1, "%s: ERROR initializing ReplayGain stage\n", e->inbasefilename);
1651 				return false;
1652 			}
1653 		}
1654 	}
1655 
1656 	if(!parse_cuesheet(&static_metadata.cuesheet, options.cuesheet_filename, e->inbasefilename, sample_rate, is_cdda, e->total_samples_to_encode, e->treat_warnings_as_errors))
1657 		return false;
1658 
1659 	if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? static_metadata.cuesheet : 0, e)) {
1660 		flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1661 		static_metadata_clear(&static_metadata);
1662 		return false;
1663 	}
1664 
1665 	/* build metadata */
1666 	if(flac_decoder_data) {
1667 		/*
1668 		 * we're encoding from FLAC so we will use the FLAC file's
1669 		 * metadata as the basis for the encoded file
1670 		 */
1671 		{
1672 			uint32_t i;
1673 			/*
1674 			 * first handle pictures: simple append any --pictures
1675 			 * specified.
1676 			 */
1677 			for(i = 0; i < options.num_pictures; i++) {
1678 				FLAC__StreamMetadata *pic = FLAC__metadata_object_clone(options.pictures[i]);
1679 				if(0 == pic) {
1680 					flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PICTURE block\n", e->inbasefilename);
1681 					static_metadata_clear(&static_metadata);
1682 					return false;
1683 				}
1684 				flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks++] = pic;
1685 			}
1686 		}
1687 		{
1688 			/*
1689 			 * next handle vorbis comment: if any tags were specified
1690 			 * or there is no existing vorbis comment, we create a
1691 			 * new vorbis comment (discarding any existing one); else
1692 			 * we keep the existing one.  also need to make sure to
1693 			 * propagate any channel mask tag.
1694 			 */
1695 			/* @@@ change to append -T values from options.vorbis_comment if input has VC already? */
1696 			size_t i, j;
1697 			FLAC__bool vc_found = false;
1698 			for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1699 				if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
1700 					vc_found = true;
1701 				if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT && options.vorbis_comment->data.vorbis_comment.num_comments > 0) {
1702 					(void) flac__utils_get_channel_mask_tag(flac_decoder_data->metadata_blocks[i], &e->info.channel_mask);
1703 					flac__utils_printf(stderr, 1, "%s: WARNING, replacing tags from input FLAC file with those given on the command-line\n", e->inbasefilename);
1704 					if(e->treat_warnings_as_errors) {
1705 						static_metadata_clear(&static_metadata);
1706 						return false;
1707 					}
1708 					FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1709 					flac_decoder_data->metadata_blocks[i] = 0;
1710 				}
1711 				else
1712 					flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1713 			}
1714 			flac_decoder_data->num_metadata_blocks = j;
1715 			if((!vc_found || options.vorbis_comment->data.vorbis_comment.num_comments > 0) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1716 				/* prepend ours */
1717 				FLAC__StreamMetadata *vc = FLAC__metadata_object_clone(options.vorbis_comment);
1718 				if(0 == vc || (e->info.channel_mask && !flac__utils_set_channel_mask_tag(vc, e->info.channel_mask))) {
1719 					flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for VORBIS_COMMENT block\n", e->inbasefilename);
1720 					static_metadata_clear(&static_metadata);
1721 					return false;
1722 				}
1723 				for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1724 					flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1725 				flac_decoder_data->metadata_blocks[1] = vc;
1726 				flac_decoder_data->num_metadata_blocks++;
1727 			}
1728 		}
1729 		{
1730 			/*
1731 			 * next handle cuesheet: if --cuesheet was specified, use
1732 			 * it; else if file has existing CUESHEET and cuesheet's
1733 			 * lead-out offset is correct, keep it; else no CUESHEET
1734 			 */
1735 			size_t i, j;
1736 			for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1737 				FLAC__bool existing_cuesheet_is_bad = false;
1738 				/* check if existing cuesheet matches the input audio */
1739 				if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && 0 == static_metadata.cuesheet) {
1740 					const FLAC__StreamMetadata_CueSheet *cs = &flac_decoder_data->metadata_blocks[i]->data.cue_sheet;
1741 					if(e->total_samples_to_encode == 0) {
1742 						flac__utils_printf(stderr, 1, "%s: WARNING, cuesheet in input FLAC file cannot be kept if input size is not known, dropping it...\n", e->inbasefilename);
1743 						if(e->treat_warnings_as_errors) {
1744 							static_metadata_clear(&static_metadata);
1745 							return false;
1746 						}
1747 						existing_cuesheet_is_bad = true;
1748 					}
1749 					else if(cs->num_tracks > 0 && e->total_samples_to_encode != cs->tracks[cs->num_tracks-1].offset) {
1750 						flac__utils_printf(stderr, 1, "%s: WARNING, lead-out offset of cuesheet in input FLAC file does not match input length, dropping existing cuesheet...\n", e->inbasefilename);
1751 						if(e->treat_warnings_as_errors) {
1752 							static_metadata_clear(&static_metadata);
1753 							return false;
1754 						}
1755 						existing_cuesheet_is_bad = true;
1756 					}
1757 				}
1758 				if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && (existing_cuesheet_is_bad || 0 != static_metadata.cuesheet)) {
1759 					if(0 != static_metadata.cuesheet) {
1760 						flac__utils_printf(stderr, 1, "%s: WARNING, replacing cuesheet in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1761 						if(e->treat_warnings_as_errors) {
1762 							static_metadata_clear(&static_metadata);
1763 							return false;
1764 						}
1765 					}
1766 					FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1767 					flac_decoder_data->metadata_blocks[i] = 0;
1768 				}
1769 				else
1770 					flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1771 			}
1772 			flac_decoder_data->num_metadata_blocks = j;
1773 			if(0 != static_metadata.cuesheet && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1774 				/* prepend ours */
1775 				FLAC__StreamMetadata *cs = FLAC__metadata_object_clone(static_metadata.cuesheet);
1776 				if(0 == cs) {
1777 					flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for CUESHEET block\n", e->inbasefilename);
1778 					static_metadata_clear(&static_metadata);
1779 					return false;
1780 				}
1781 				for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1782 					flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1783 				flac_decoder_data->metadata_blocks[1] = cs;
1784 				flac_decoder_data->num_metadata_blocks++;
1785 			}
1786 		}
1787 		{
1788 			/*
1789 			 * next handle seektable: if -S- was specified, no
1790 			 * SEEKTABLE; else if -S was specified, use it/them;
1791 			 * else if file has existing SEEKTABLE and input size is
1792 			 * preserved (no --skip/--until/etc specified), keep it;
1793 			 * else use default seektable options
1794 			 *
1795 			 * note: meanings of num_requested_seek_points:
1796 			 *  -1 : no -S option given, default to some value
1797 			 *   0 : -S- given (no seektable)
1798 			 *  >0 : one or more -S options given
1799 			 */
1800 			size_t i, j;
1801 			FLAC__bool existing_seektable = false;
1802 			for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1803 				if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE)
1804 					existing_seektable = true;
1805 				if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE && (e->total_samples_to_encode != flac_decoder_data->metadata_blocks[0]->data.stream_info.total_samples || options.num_requested_seek_points >= 0)) {
1806 					if(options.num_requested_seek_points > 0) {
1807 						flac__utils_printf(stderr, 1, "%s: WARNING, replacing seektable in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1808 						if(e->treat_warnings_as_errors) {
1809 							static_metadata_clear(&static_metadata);
1810 							return false;
1811 						}
1812 					}
1813 					else if(options.num_requested_seek_points == 0)
1814 						; /* no warning, silently delete existing SEEKTABLE since user specified --no-seektable (-S-) */
1815 					else {
1816 						flac__utils_printf(stderr, 1, "%s: WARNING, can't use existing seektable in input FLAC since the input size is changing or unknown, dropping existing SEEKTABLE block...\n", e->inbasefilename);
1817 						if(e->treat_warnings_as_errors) {
1818 							static_metadata_clear(&static_metadata);
1819 							return false;
1820 						}
1821 					}
1822 					FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1823 					flac_decoder_data->metadata_blocks[i] = 0;
1824 					existing_seektable = false;
1825 				}
1826 				else
1827 					flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1828 			}
1829 			flac_decoder_data->num_metadata_blocks = j;
1830 			if((options.num_requested_seek_points > 0 || (options.num_requested_seek_points < 0 && !existing_seektable)) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1831 				/* prepend ours */
1832 				FLAC__StreamMetadata *st = FLAC__metadata_object_clone(e->seek_table_template);
1833 				if(0 == st) {
1834 					flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for SEEKTABLE block\n", e->inbasefilename);
1835 					static_metadata_clear(&static_metadata);
1836 					return false;
1837 				}
1838 				for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1839 					flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1840 				flac_decoder_data->metadata_blocks[1] = st;
1841 				flac_decoder_data->num_metadata_blocks++;
1842 			}
1843 		}
1844 		{
1845 			/*
1846 			 * finally handle padding: if --no-padding was specified,
1847 			 * then delete all padding; else if -P was specified,
1848 			 * use that instead of existing padding (if any); else
1849 			 * if existing file has padding, move all existing
1850 			 * padding blocks to one padding block at the end; else
1851 			 * use default padding.
1852 			 */
1853 			int p = -1;
1854 			size_t i, j;
1855 			for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1856 				if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_PADDING) {
1857 					if(p < 0)
1858 						p = 0;
1859 					p += flac_decoder_data->metadata_blocks[i]->length;
1860 					FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1861 					flac_decoder_data->metadata_blocks[i] = 0;
1862 				}
1863 				else
1864 					flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1865 			}
1866 			flac_decoder_data->num_metadata_blocks = j;
1867 			if(options.padding > 0)
1868 				p = options.padding;
1869 			if(p < 0) {
1870 				if(sample_rate == 0)
1871 					p = FLAC_ENCODE__DEFAULT_PADDING;
1872 				else
1873 					p = e->total_samples_to_encode / sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8;
1874 			}
1875 			if(p > 0)
1876 				p += (e->replay_gain ? GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED : 0);
1877 			p = min(p, (int)((1u << FLAC__STREAM_METADATA_LENGTH_LEN) - 1));
1878 			if(options.padding != 0) {
1879 				if(p > 0 && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1880 					flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
1881 					if(0 == flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]) {
1882 						flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PADDING block\n", e->inbasefilename);
1883 						static_metadata_clear(&static_metadata);
1884 						return false;
1885 					}
1886 					flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->is_last = false; /* the encoder will set this for us */
1887 					flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->length = p;
1888 					flac_decoder_data->num_metadata_blocks++;
1889 				}
1890 			}
1891 		}
1892 		metadata = &flac_decoder_data->metadata_blocks[1]; /* don't include STREAMINFO */
1893 		num_metadata = flac_decoder_data->num_metadata_blocks - 1;
1894 	}
1895 	else {
1896 		/*
1897 		 * we're not encoding from FLAC so we will build the metadata
1898 		 * from scratch
1899 		 */
1900 		const foreign_metadata_t *foreign_metadata = EncoderSession_format_is_iff(e)? options.format_options.iff.foreign_metadata : 0;
1901 		uint32_t i;
1902 
1903 		if(e->seek_table_template->data.seek_table.num_points > 0) {
1904 			e->seek_table_template->is_last = false; /* the encoder will set this for us */
1905 			static_metadata_append(&static_metadata, e->seek_table_template, /*needs_delete=*/false);
1906 		}
1907 		if(0 != static_metadata.cuesheet)
1908 			static_metadata_append(&static_metadata, static_metadata.cuesheet, /*needs_delete=*/false);
1909 		if(e->info.channel_mask) {
1910 			options.vorbis_comment_with_channel_mask_tag = FLAC__metadata_object_clone(options.vorbis_comment);
1911 			if(!flac__utils_set_channel_mask_tag(options.vorbis_comment_with_channel_mask_tag, e->info.channel_mask)) {
1912 				flac__utils_printf(stderr, 1, "%s: ERROR adding channel mask tag\n", e->inbasefilename);
1913 				static_metadata_clear(&static_metadata);
1914 				return false;
1915 			}
1916 			static_metadata_append(&static_metadata, options.vorbis_comment_with_channel_mask_tag, /*needs_delete=*/true);
1917 		}
1918 		else
1919 			static_metadata_append(&static_metadata, options.vorbis_comment, /*needs_delete=*/false);
1920 		for(i = 0; i < options.num_pictures; i++)
1921 			static_metadata_append(&static_metadata, options.pictures[i], /*needs_delete=*/false);
1922 		if(foreign_metadata) {
1923 			for(i = 0; i < foreign_metadata->num_blocks; i++) {
1924 				FLAC__StreamMetadata *p = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
1925 				if(!p) {
1926 					flac__utils_printf(stderr, 1, "%s: ERROR: out of memory\n", e->inbasefilename);
1927 					static_metadata_clear(&static_metadata);
1928 					return false;
1929 				}
1930 				static_metadata_append(&static_metadata, p, /*needs_delete=*/true);
1931 				static_metadata.metadata[static_metadata.num_metadata-1]->length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8 + foreign_metadata->blocks[i].size;
1932 			}
1933 		}
1934 		if(options.padding != 0) {
1935 			padding.is_last = false; /* the encoder will set this for us */
1936 			padding.type = FLAC__METADATA_TYPE_PADDING;
1937 			if(sample_rate == 0)
1938 				padding.length = (uint32_t)(options.padding>0? options.padding : FLAC_ENCODE__DEFAULT_PADDING) + (e->replay_gain ? GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED : 0);
1939 			else
1940 				padding.length = (uint32_t)(options.padding>0? options.padding : (e->total_samples_to_encode / sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8)) + (e->replay_gain ? GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED : 0);
1941 			padding.length = min(padding.length, (1u << FLAC__STREAM_METADATA_LENGTH_LEN) - 1);
1942 			static_metadata_append(&static_metadata, &padding, /*needs_delete=*/false);
1943 		}
1944 		metadata = static_metadata.metadata;
1945 		num_metadata = static_metadata.num_metadata;
1946 	}
1947 
1948 	/* check for a few things that have not already been checked.  the
1949 	 * FLAC__stream_encoder_init*() will check it but only return
1950 	 * FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA so we check some
1951 	 * up front to give a better error message.
1952 	 */
1953 	if(!verify_metadata(e, metadata, num_metadata)) {
1954 		static_metadata_clear(&static_metadata);
1955 		return false;
1956 	}
1957 
1958 	FLAC__stream_encoder_set_verify(e->encoder, options.verify);
1959 	FLAC__stream_encoder_set_streamable_subset(e->encoder, !options.lax);
1960 	FLAC__stream_encoder_set_channels(e->encoder, channels);
1961 	FLAC__stream_encoder_set_bits_per_sample(e->encoder, bps);
1962 	FLAC__stream_encoder_set_sample_rate(e->encoder, sample_rate);
1963 	for(ic = 0; ic < options.num_compression_settings; ic++) {
1964 		switch(options.compression_settings[ic].type) {
1965 			case CST_BLOCKSIZE:
1966 				FLAC__stream_encoder_set_blocksize(e->encoder, options.compression_settings[ic].value.t_unsigned);
1967 				break;
1968 			case CST_COMPRESSION_LEVEL:
1969 				FLAC__stream_encoder_set_compression_level(e->encoder, options.compression_settings[ic].value.t_unsigned);
1970 				apodizations[0] = '\0';
1971 				break;
1972 			case CST_DO_MID_SIDE:
1973 				FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder, options.compression_settings[ic].value.t_bool);
1974 				break;
1975 			case CST_LOOSE_MID_SIDE:
1976 				FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder, options.compression_settings[ic].value.t_bool);
1977 				break;
1978 			case CST_APODIZATION:
1979 				if(strlen(apodizations)+strlen(options.compression_settings[ic].value.t_string)+2 >= sizeof(apodizations)) {
1980 					flac__utils_printf(stderr, 1, "%s: ERROR: too many apodization functions requested\n", e->inbasefilename);
1981 					static_metadata_clear(&static_metadata);
1982 					return false;
1983 				}
1984 				else {
1985 					safe_strncat(apodizations, options.compression_settings[ic].value.t_string, sizeof(apodizations));
1986 					safe_strncat(apodizations, ";", sizeof(apodizations));
1987 				}
1988 				break;
1989 			case CST_MAX_LPC_ORDER:
1990 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1991 				FLAC__stream_encoder_set_max_lpc_order(e->encoder, options.compression_settings[ic].value.t_unsigned);
1992 #endif
1993 				break;
1994 			case CST_QLP_COEFF_PRECISION:
1995 				FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder, options.compression_settings[ic].value.t_unsigned);
1996 				break;
1997 			case CST_DO_QLP_COEFF_PREC_SEARCH:
1998 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1999 				FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder, options.compression_settings[ic].value.t_bool);
2000 #endif
2001 				break;
2002 			case CST_DO_ESCAPE_CODING:
2003 				FLAC__stream_encoder_set_do_escape_coding(e->encoder, options.compression_settings[ic].value.t_bool);
2004 				break;
2005 			case CST_DO_EXHAUSTIVE_MODEL_SEARCH:
2006 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2007 				FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder, options.compression_settings[ic].value.t_bool);
2008 #endif
2009 				break;
2010 			case CST_MIN_RESIDUAL_PARTITION_ORDER:
2011 				FLAC__stream_encoder_set_min_residual_partition_order(e->encoder, options.compression_settings[ic].value.t_unsigned);
2012 				break;
2013 			case CST_MAX_RESIDUAL_PARTITION_ORDER:
2014 				FLAC__stream_encoder_set_max_residual_partition_order(e->encoder, options.compression_settings[ic].value.t_unsigned);
2015 				break;
2016 			case CST_RICE_PARAMETER_SEARCH_DIST:
2017 				FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder, options.compression_settings[ic].value.t_unsigned);
2018 				break;
2019 		}
2020 	}
2021 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2022 	if(*apodizations)
2023 		FLAC__stream_encoder_set_apodization(e->encoder, apodizations);
2024 #endif
2025 	FLAC__stream_encoder_set_total_samples_estimate(e->encoder, e->total_samples_to_encode);
2026 	FLAC__stream_encoder_set_metadata(e->encoder, (num_metadata > 0)? metadata : 0, num_metadata);
2027 	FLAC__stream_encoder_set_limit_min_bitrate(e->encoder, options.limit_min_bitrate);
2028 
2029 	FLAC__stream_encoder_disable_constant_subframes(e->encoder, options.debug.disable_constant_subframes);
2030 	FLAC__stream_encoder_disable_fixed_subframes(e->encoder, options.debug.disable_fixed_subframes);
2031 	FLAC__stream_encoder_disable_verbatim_subframes(e->encoder, options.debug.disable_verbatim_subframes);
2032 	if(!options.debug.do_md5) {
2033 		flac__utils_printf(stderr, 1, "%s: WARNING, MD5 computation disabled, resulting file will not have MD5 sum\n", e->inbasefilename);
2034 		if(e->treat_warnings_as_errors) {
2035 			static_metadata_clear(&static_metadata);
2036 			return false;
2037 		}
2038 		FLAC__stream_encoder_set_do_md5(e->encoder, false);
2039 	}
2040 	else if(e->is_stdout) {
2041 		flac__utils_printf(stderr, 1, "%s: WARNING, cannot write back MD5 sum when encoding to stdout\n", e->inbasefilename);
2042 		if(e->treat_warnings_as_errors) {
2043 			static_metadata_clear(&static_metadata);
2044 			return false;
2045 		}
2046 	}
2047 
2048 #if FLAC__HAS_OGG
2049 	if(e->use_ogg) {
2050 		FLAC__stream_encoder_set_ogg_serial_number(e->encoder, options.serial_number);
2051 
2052 		init_status = FLAC__stream_encoder_init_ogg_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
2053 	}
2054 	else
2055 #endif
2056 	{
2057 		init_status = FLAC__stream_encoder_init_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
2058 	}
2059 
2060 	if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
2061 		print_error_with_init_status(e, "ERROR initializing encoder", init_status);
2062 		if(FLAC__stream_encoder_get_state(e->encoder) != FLAC__STREAM_ENCODER_IO_ERROR)
2063 			e->outputfile_opened = true;
2064 		static_metadata_clear(&static_metadata);
2065 		return false;
2066 	}
2067 	else
2068 		e->outputfile_opened = true;
2069 
2070 #if 0 /* in case time.h with clock() isn't available for some reason */
2071 	e->stats_frames_interval =
2072 		(FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) && FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x1f :
2073 		(FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x3f :
2074 		0xff;
2075 #endif
2076 
2077 	static_metadata_clear(&static_metadata);
2078 
2079 	return true;
2080 }
2081 
EncoderSession_process(EncoderSession * e,const FLAC__int32 * const buffer[],uint32_t samples)2082 FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], uint32_t samples)
2083 {
2084 	if(e->replay_gain) {
2085 		if(!grabbag__replaygain_analyze(buffer, e->info.channels==2, e->info.bits_per_sample, samples)) {
2086 			flac__utils_printf(stderr, 1, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename);
2087 			if(e->treat_warnings_as_errors)
2088 				return false;
2089 		}
2090 	}
2091 
2092 	return FLAC__stream_encoder_process(e->encoder, buffer, samples);
2093 }
2094 
EncoderSession_format_is_iff(const EncoderSession * e)2095 FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e)
2096 {
2097 	return
2098 		e->format == FORMAT_WAVE ||
2099 		e->format == FORMAT_WAVE64 ||
2100 		e->format == FORMAT_RF64 ||
2101 		e->format == FORMAT_AIFF ||
2102 		e->format == FORMAT_AIFF_C;
2103 }
2104 
convert_to_seek_table_template(const char * requested_seek_points,int num_requested_seek_points,FLAC__StreamMetadata * cuesheet,EncoderSession * e)2105 FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e)
2106 {
2107 	const FLAC__bool only_placeholders = e->is_stdout;
2108 	FLAC__bool has_real_points;
2109 
2110 	if(num_requested_seek_points == 0 && 0 == cuesheet)
2111 		return true;
2112 
2113 #if FLAC__HAS_OGG
2114 	if(e->use_ogg)
2115 		return true;
2116 #endif
2117 
2118 	if(num_requested_seek_points < 0) {
2119 		requested_seek_points = "10s;";
2120 		num_requested_seek_points = 1;
2121 	}
2122 
2123 	if(num_requested_seek_points > 0) {
2124 		if(!grabbag__seektable_convert_specification_to_template(requested_seek_points, only_placeholders, e->total_samples_to_encode, e->info.sample_rate, e->seek_table_template, &has_real_points))
2125 			return false;
2126 	}
2127 
2128 	if(0 != cuesheet) {
2129 		uint32_t i, j;
2130 		const FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet;
2131 		for(i = 0; i < cs->num_tracks; i++) {
2132 			const FLAC__StreamMetadata_CueSheet_Track *tr = cs->tracks+i;
2133 			for(j = 0; j < tr->num_indices; j++) {
2134 				if(!FLAC__metadata_object_seektable_template_append_point(e->seek_table_template, tr->offset + tr->indices[j].offset))
2135 					return false;
2136 				has_real_points = true;
2137 			}
2138 		}
2139 		if(has_real_points)
2140 			if(!FLAC__metadata_object_seektable_template_sort(e->seek_table_template, /*compact=*/true))
2141 				return false;
2142 	}
2143 
2144 	if(has_real_points) {
2145 		if(e->is_stdout) {
2146 			flac__utils_printf(stderr, 1, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename);
2147 			if(e->treat_warnings_as_errors)
2148 				return false;
2149 		}
2150 	}
2151 
2152 	return true;
2153 }
2154 
canonicalize_until_specification(utils__SkipUntilSpecification * spec,const char * inbasefilename,uint32_t sample_rate,FLAC__uint64 skip,FLAC__uint64 total_samples_in_input)2155 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, uint32_t sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
2156 {
2157 	/* convert from mm:ss.sss to sample number if necessary */
2158 	if(!flac__utils_canonicalize_skip_until_specification(spec, sample_rate)) {
2159 		flac__utils_printf(stderr, 1, "%s: ERROR, value of --until is too large\n", inbasefilename);
2160 		return false;
2161 	}
2162 
2163 	/* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
2164 	if(spec->is_relative && spec->value.samples == 0) {
2165 		spec->is_relative = false;
2166 		return true;
2167 	}
2168 
2169 	/* in any other case the total samples in the input must be known */
2170 	if(total_samples_in_input == 0) {
2171 		flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when input length is unknown\n", inbasefilename);
2172 		return false;
2173 	}
2174 
2175 	FLAC__ASSERT(spec->value_is_samples);
2176 
2177 	/* convert relative specifications to absolute */
2178 	if(spec->is_relative) {
2179 		if(spec->value.samples <= 0)
2180 			spec->value.samples += (FLAC__int64)total_samples_in_input;
2181 		else
2182 			spec->value.samples += skip;
2183 		spec->is_relative = false;
2184 	}
2185 
2186 	/* error check */
2187 	if(spec->value.samples < 0) {
2188 		flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
2189 		return false;
2190 	}
2191 	if((FLAC__uint64)spec->value.samples <= skip) {
2192 		flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
2193 		return false;
2194 	}
2195 	if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
2196 		flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
2197 		return false;
2198 	}
2199 
2200 	return true;
2201 }
2202 
verify_metadata(const EncoderSession * e,FLAC__StreamMetadata ** metadata,uint32_t num_metadata)2203 FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, uint32_t num_metadata)
2204 {
2205 	FLAC__bool metadata_picture_has_type1 = false;
2206 	FLAC__bool metadata_picture_has_type2 = false;
2207 	uint32_t i;
2208 
2209 	FLAC__ASSERT(0 != metadata);
2210 	for(i = 0; i < num_metadata; i++) {
2211 		const FLAC__StreamMetadata *m = metadata[i];
2212 		if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
2213 			if(!FLAC__format_seektable_is_legal(&m->data.seek_table)) {
2214 				flac__utils_printf(stderr, 1, "%s: ERROR: SEEKTABLE metadata block is invalid\n", e->inbasefilename);
2215 				return false;
2216 			}
2217 		}
2218 		else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
2219 			if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0)) {
2220 				flac__utils_printf(stderr, 1, "%s: ERROR: CUESHEET metadata block is invalid\n", e->inbasefilename);
2221 				return false;
2222 			}
2223 		}
2224 		else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
2225 			const char *error = 0;
2226 			if(!FLAC__format_picture_is_legal(&m->data.picture, &error)) {
2227 				flac__utils_printf(stderr, 1, "%s: ERROR: PICTURE metadata block is invalid: %s\n", e->inbasefilename, error);
2228 				return false;
2229 			}
2230 			if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
2231 				if(metadata_picture_has_type1) {
2232 					flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 1 (32x32 icon) in the file\n", e->inbasefilename);
2233 					return false;
2234 				}
2235 				metadata_picture_has_type1 = true;
2236 			}
2237 			else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
2238 				if(metadata_picture_has_type2) {
2239 					flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 2 (icon) in the file\n", e->inbasefilename);
2240 					return false;
2241 				}
2242 				metadata_picture_has_type2 = true;
2243 			}
2244 		}
2245 	}
2246 
2247 	return true;
2248 }
2249 
format_input(FLAC__int32 * dest[],uint32_t wide_samples,FLAC__bool is_big_endian,FLAC__bool is_unsigned_samples,uint32_t channels,uint32_t bps,uint32_t shift,size_t * channel_map)2250 FLAC__bool format_input(FLAC__int32 *dest[], uint32_t wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, uint32_t channels, uint32_t bps, uint32_t shift, size_t *channel_map)
2251 {
2252 	uint32_t wide_sample, sample, channel;
2253 	FLAC__int32 *out[FLAC__MAX_CHANNELS];
2254 
2255 	if(0 == channel_map) {
2256 		for(channel = 0; channel < channels; channel++)
2257 			out[channel] = dest[channel];
2258 	}
2259 	else {
2260 		for(channel = 0; channel < channels; channel++)
2261 			out[channel] = dest[channel_map[channel]];
2262 	}
2263 
2264 	if(bps == 8) {
2265 		if(is_unsigned_samples) {
2266 			for(channel = 0; channel < channels; channel++)
2267 				for(sample = channel, wide_sample = 0; wide_sample < wide_samples; wide_sample++, sample+=channels)
2268 					out[channel][wide_sample] = (FLAC__int32)ubuffer.u8[sample] - 0x80;
2269 		}
2270 		else {
2271 			for(channel = 0; channel < channels; channel++)
2272 				for(sample = channel, wide_sample = 0; wide_sample < wide_samples; wide_sample++, sample+=channels)
2273 					out[channel][wide_sample] = (FLAC__int32)ubuffer.s8[sample];
2274 		}
2275 	}
2276 	else if(bps == 16) {
2277 		if(is_unsigned_samples) {
2278 			if(is_big_endian != is_big_endian_host_) {
2279 				for(channel = 0; channel < channels; channel++)
2280 					for(sample = channel, wide_sample = 0; wide_sample < wide_samples; wide_sample++, sample+=channels)
2281 						out[channel][wide_sample] = (FLAC__int32)(ENDSWAP_16(ubuffer.u16[sample])) - 0x8000;
2282 			}
2283 			else {
2284 				for(channel = 0; channel < channels; channel++)
2285 					for(sample = channel, wide_sample = 0; wide_sample < wide_samples; wide_sample++, sample+=channels)
2286 						out[channel][wide_sample] = (FLAC__int32)ubuffer.u16[sample] - 0x8000;
2287 			}
2288 		}
2289 		else {
2290 			if(is_big_endian != is_big_endian_host_) {
2291 				for(channel = 0; channel < channels; channel++)
2292 					for(sample = channel, wide_sample = 0; wide_sample < wide_samples; wide_sample++, sample+=channels)
2293 						out[channel][wide_sample] = (int16_t)(ENDSWAP_16(ubuffer.s16[sample]));
2294 
2295 			}
2296 			else {
2297 				for(channel = 0; channel < channels; channel++)
2298 					for(sample = channel, wide_sample = 0; wide_sample < wide_samples; wide_sample++, sample+=channels)
2299 						out[channel][wide_sample] = ubuffer.s16[sample];
2300 			}
2301 		}
2302 	}
2303 	else if(bps == 24) {
2304 		if(!is_big_endian) {
2305 			if(is_unsigned_samples) {
2306 				for(channel = 0; channel < channels; channel++) {
2307 					uint32_t b = 3*channel;
2308 					for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
2309 						uint32_t t;
2310 						t  = ubuffer.u8[b];
2311 						t |= (uint32_t)(ubuffer.u8[b+1]) << 8;
2312 						t |= (uint32_t)(ubuffer.u8[b+2]) << 16;
2313 						out[channel][wide_sample] = (FLAC__int32)t - 0x800000;
2314 						b += 3*channels;
2315 					}
2316 				}
2317 			}
2318 			else {
2319 				for(channel = 0; channel < channels; channel++) {
2320 					uint32_t b = 3*channel;
2321 					for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
2322 						uint32_t t;
2323 						t  = ubuffer.u8[b];
2324 						t |= (uint32_t)(ubuffer.u8[b+1]) << 8;
2325 						t |= (uint32_t)((int32_t)(ubuffer.s8[b+2])) << 16;
2326 						out[channel][wide_sample] = t;
2327 						b += 3*channels;
2328 					}
2329 				}
2330 			}
2331 		}
2332 		else {
2333 			if(is_unsigned_samples) {
2334 				for(channel = 0; channel < channels; channel++) {
2335 					uint32_t b = 3*channel;
2336 					for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
2337 						uint32_t t;
2338 						t  = ubuffer.u8[b]; t <<= 8;
2339 						t |= ubuffer.u8[b+1]; t <<= 8;
2340 						t |= ubuffer.u8[b+2];
2341 						out[channel][wide_sample] = (FLAC__int32)t - 0x800000;
2342 						b += 3*channels;
2343 					}
2344 				}
2345 			}
2346 			else {
2347 				for(channel = 0; channel < channels; channel++) {
2348 					uint32_t b = 3*channel;
2349 					for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
2350 						uint32_t t;
2351 						t  = ubuffer.s8[b]; t <<= 8;
2352 						t |= ubuffer.u8[b+1]; t <<= 8;
2353 						t |= ubuffer.u8[b+2];
2354 						out[channel][wide_sample] = t;
2355 						b += 3*channels;
2356 					}
2357 				}
2358 			}
2359 		}
2360 	}
2361 	else if(bps == 32) {
2362 		if(is_unsigned_samples) {
2363 			if(is_big_endian != is_big_endian_host_) {
2364 				for(channel = 0; channel < channels; channel++)
2365 					for(sample = channel, wide_sample = 0; wide_sample < wide_samples; wide_sample++, sample+=channels)
2366 						out[channel][wide_sample] = ENDSWAP_32(ubuffer.u32[sample]) - 0x80000000;
2367 			}
2368 			else {
2369 				for(channel = 0; channel < channels; channel++)
2370 					for(sample = channel, wide_sample = 0; wide_sample < wide_samples; wide_sample++, sample+=channels)
2371 						out[channel][wide_sample] = ubuffer.u32[sample] - 0x80000000;
2372 			}
2373 		}
2374 		else {
2375 			if(is_big_endian != is_big_endian_host_) {
2376 				for(channel = 0; channel < channels; channel++)
2377 					for(sample = channel, wide_sample = 0; wide_sample < wide_samples; wide_sample++, sample+=channels)
2378 						out[channel][wide_sample] = ENDSWAP_32(ubuffer.s32[sample]);
2379 			}
2380 			else {
2381 				for(channel = 0; channel < channels; channel++)
2382 					for(sample = channel, wide_sample = 0; wide_sample < wide_samples; wide_sample++, sample+=channels)
2383 						out[channel][wide_sample] = ubuffer.s32[sample];
2384 			}
2385 		}
2386 	}
2387 	else {
2388 		flac__utils_printf(stderr, 1, "ERROR: unsupported input format\n");
2389 		return false;
2390 	}
2391 	if(shift > 0) {
2392 		FLAC__int32 mask = (1<<shift)-1;
2393 		for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2394 			for(channel = 0; channel < channels; channel++) {
2395 				if(out[channel][wide_sample] & mask) {
2396 					flac__utils_printf(stderr, 1, "ERROR during read, sample data (channel#%u sample#%u = %d) has non-zero least-significant bits\n  WAVE/AIFF header said the last %u bits are not significant and should be zero.\n", channel, wide_sample, out[channel][wide_sample], shift);
2397 					return false;
2398 				}
2399 				out[channel][wide_sample] >>= shift;
2400 			}
2401 	}
2402 	return true;
2403 }
2404 
encoder_progress_callback(const FLAC__StreamEncoder * encoder,FLAC__uint64 bytes_written,FLAC__uint64 samples_written,uint32_t frames_written,uint32_t total_frames_estimate,void * client_data)2405 void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, uint32_t frames_written, uint32_t total_frames_estimate, void *client_data)
2406 {
2407 	EncoderSession *e = (EncoderSession*)client_data;
2408 
2409 	const FLAC__uint64 uesize = e->unencoded_size;
2410 
2411 	(void)encoder, (void)total_frames_estimate, (void) frames_written;
2412 
2413 	e->bytes_written = bytes_written;
2414 	e->samples_written = samples_written;
2415 
2416 	e->progress = e->total_samples_to_encode ? (double)samples_written / (double)e->total_samples_to_encode : 0;
2417 	e->compression_ratio = (e->progress && uesize) ? (double)e->bytes_written / ((double)uesize * min(1.0, e->progress)) : 0;
2418 
2419 #if 0 /* in case time.h with clock() isn't available for some reason */
2420 	if(e->total_samples_to_encode > 0 && frames_written - e->old_frames_written > e->stats_frames_interval) {
2421 		print_stats(e);
2422 		e->old_frames_written = frames_written;
2423 	}
2424 #else
2425 	if(e->total_samples_to_encode > 0 && (clock() - e->old_clock_t) > (CLOCKS_PER_SEC/4)) {
2426 		print_stats(e);
2427 		e->old_clock_t = clock();
2428 	}
2429 
2430 #endif
2431 }
2432 
flac_decoder_read_callback(const FLAC__StreamDecoder * decoder,FLAC__byte buffer[],size_t * bytes,void * client_data)2433 FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
2434 {
2435 	size_t n = 0;
2436 	EncoderSession *e = (EncoderSession*)client_data;
2437 	FLACDecoderData *data = &e->fmt.flac.client_data;
2438 
2439 	(void)decoder;
2440 
2441 	if (data->fatal_error)
2442 		return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2443 
2444 	/* use up lookahead first */
2445 	if (data->lookahead_length) {
2446 		n = min(data->lookahead_length, *bytes);
2447 		memcpy(buffer, data->lookahead, n);
2448 		buffer += n;
2449 		data->lookahead += n;
2450 		data->lookahead_length -= n;
2451 	}
2452 
2453 	/* get the rest from file */
2454 	if (*bytes > n) {
2455 		*bytes = n + fread(buffer, 1, *bytes-n, e->fin);
2456 		if(ferror(e->fin))
2457 			return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2458 		else if(0 == *bytes)
2459 			return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2460 		else
2461 			return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2462 	}
2463 	else
2464 		return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2465 }
2466 
flac_decoder_seek_callback(const FLAC__StreamDecoder * decoder,FLAC__uint64 absolute_byte_offset,void * client_data)2467 FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2468 {
2469 	EncoderSession *e = (EncoderSession*)client_data;
2470 	(void)decoder;
2471 
2472 	if(fseeko(e->fin, (FLAC__off_t)absolute_byte_offset, SEEK_SET) < 0)
2473 		return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
2474 	else
2475 		return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2476 }
2477 
flac_decoder_tell_callback(const FLAC__StreamDecoder * decoder,FLAC__uint64 * absolute_byte_offset,void * client_data)2478 FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2479 {
2480 	EncoderSession *e = (EncoderSession*)client_data;
2481 	FLAC__off_t pos;
2482 	(void)decoder;
2483 
2484 	if((pos = ftello(e->fin)) < 0)
2485 		return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
2486 	else {
2487 		*absolute_byte_offset = (FLAC__uint64)pos;
2488 		return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2489 	}
2490 }
2491 
flac_decoder_length_callback(const FLAC__StreamDecoder * decoder,FLAC__uint64 * stream_length,void * client_data)2492 FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2493 {
2494 	const EncoderSession *e = (EncoderSession*)client_data;
2495 	const FLACDecoderData *data = &e->fmt.flac.client_data;
2496 	(void)decoder;
2497 
2498 	if(data->filesize < 0)
2499 		return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
2500 	else {
2501 		*stream_length = (FLAC__uint64)data->filesize;
2502 		return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2503 	}
2504 }
2505 
flac_decoder_eof_callback(const FLAC__StreamDecoder * decoder,void * client_data)2506 FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data)
2507 {
2508 	EncoderSession *e = (EncoderSession*)client_data;
2509 	(void)decoder;
2510 
2511 	return feof(e->fin)? true : false;
2512 }
2513 
flac_decoder_write_callback(const FLAC__StreamDecoder * decoder,const FLAC__Frame * frame,const FLAC__int32 * const buffer[],void * client_data)2514 FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
2515 {
2516 	EncoderSession *e = (EncoderSession*)client_data;
2517 	FLACDecoderData *data = &e->fmt.flac.client_data;
2518 	FLAC__uint64 n = min(data->samples_left_to_process, frame->header.blocksize);
2519 	(void)decoder;
2520 
2521 	/* Do some checks */
2522 	if(frame->header.channels != e->info.channels) {
2523 		print_error_with_state(e, "ERROR: number of channels of input changed mid-stream");
2524 		data->fatal_error = true;
2525 		return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2526 	}
2527 	if(frame->header.bits_per_sample > e->info.bits_per_sample) {
2528 		print_error_with_state(e, "ERROR: bits-per-sample of input changed mid-stream");
2529 		data->fatal_error = true;
2530 		return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2531 	}
2532 
2533 	if(!EncoderSession_process(e, buffer, (uint32_t)n)) {
2534 		print_error_with_state(e, "ERROR during encoding");
2535 		data->fatal_error = true;
2536 		return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2537 	}
2538 
2539 	data->samples_left_to_process -= n;
2540 	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2541 }
2542 
flac_decoder_metadata_callback(const FLAC__StreamDecoder * decoder,const FLAC__StreamMetadata * metadata,void * client_data)2543 void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
2544 {
2545 	EncoderSession *e = (EncoderSession*)client_data;
2546 	FLACDecoderData *data = &e->fmt.flac.client_data;
2547 	(void)decoder;
2548 
2549 	if (data->fatal_error)
2550 		return;
2551 
2552 	if (
2553 		data->num_metadata_blocks == sizeof(data->metadata_blocks)/sizeof(data->metadata_blocks[0]) ||
2554 		0 == (data->metadata_blocks[data->num_metadata_blocks] = FLAC__metadata_object_clone(metadata))
2555 	)
2556 		data->fatal_error = true;
2557 	else
2558 		data->num_metadata_blocks++;
2559 }
2560 
flac_decoder_error_callback(const FLAC__StreamDecoder * decoder,FLAC__StreamDecoderErrorStatus status,void * client_data)2561 void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
2562 {
2563 	EncoderSession *e = (EncoderSession*)client_data;
2564 	FLACDecoderData *data = &e->fmt.flac.client_data;
2565 	(void)decoder;
2566 
2567 	stats_print_name(1, e->inbasefilename);
2568 	flac__utils_printf(stderr, 1, "ERROR got %s while decoding FLAC input\n", FLAC__StreamDecoderErrorStatusString[status]);
2569 	if(!e->continue_through_decode_errors)
2570 		data->fatal_error = true;
2571 }
2572 
parse_cuesheet(FLAC__StreamMetadata ** cuesheet,const char * cuesheet_filename,const char * inbasefilename,uint32_t sample_rate,FLAC__bool is_cdda,FLAC__uint64 lead_out_offset,FLAC__bool treat_warnings_as_errors)2573 FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, uint32_t sample_rate, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors)
2574 {
2575 	FILE *f;
2576 	uint32_t last_line_read;
2577 	const char *error_message;
2578 
2579 	if(0 == cuesheet_filename)
2580 		return true;
2581 
2582 	if(lead_out_offset == 0) {
2583 		flac__utils_printf(stderr, 1, "%s: ERROR cannot import cuesheet when the number of input samples to encode is unknown\n", inbasefilename);
2584 		return false;
2585 	}
2586 
2587 	if(0 == (f = flac_fopen(cuesheet_filename, "r"))) {
2588 		flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading: %s\n", inbasefilename, cuesheet_filename, strerror(errno));
2589 		return false;
2590 	}
2591 
2592 	*cuesheet = grabbag__cuesheet_parse(f, &error_message, &last_line_read, sample_rate, is_cdda, lead_out_offset);
2593 
2594 	fclose(f);
2595 
2596 	if(0 == *cuesheet) {
2597 		flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\" on line %u: %s\n", inbasefilename, cuesheet_filename, last_line_read, error_message);
2598 		return false;
2599 	}
2600 
2601 	if(!FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/false, &error_message)) {
2602 		flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\": %s\n", inbasefilename, cuesheet_filename, error_message);
2603 		return false;
2604 	}
2605 
2606 	/* if we're expecting CDDA, warn about non-compliance */
2607 	if(is_cdda && !FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/true, &error_message)) {
2608 		flac__utils_printf(stderr, 1, "%s: WARNING cuesheet \"%s\" is not audio CD compliant: %s\n", inbasefilename, cuesheet_filename, error_message);
2609 		if(treat_warnings_as_errors)
2610 			return false;
2611 		(*cuesheet)->data.cue_sheet.is_cd = false;
2612 	}
2613 
2614 	return true;
2615 }
2616 
print_stats(const EncoderSession * encoder_session)2617 static void print_stats(const EncoderSession *encoder_session)
2618 {
2619 	if(flac__utils_verbosity_ >= 2) {
2620 		char ratiostr[16];
2621 
2622 		FLAC__ASSERT(encoder_session->total_samples_to_encode > 0);
2623 
2624 		if (encoder_session->compression_ratio > 0.0)
2625 			flac_snprintf(ratiostr, sizeof(ratiostr), "%0.3f", encoder_session->compression_ratio);
2626 		else
2627 			flac_snprintf(ratiostr, sizeof(ratiostr), "N/A");
2628 
2629 		if(encoder_session->samples_written == encoder_session->total_samples_to_encode) {
2630 			stats_print_name(2, encoder_session->inbasefilename);
2631 			stats_print_info(2, "%swrote %" PRIu64 " bytes, ratio=%s",
2632 				encoder_session->verify? "Verify OK, " : "",
2633 				encoder_session->bytes_written,
2634 				ratiostr
2635 			);
2636 		}
2637 		else {
2638 			stats_print_name(2, encoder_session->inbasefilename);
2639 			stats_print_info(2, "%u%% complete, ratio=%s", (uint32_t)floor(encoder_session->progress * 100.0 + 0.5), ratiostr);
2640 		}
2641 	}
2642 }
2643 
print_error_with_init_status(const EncoderSession * e,const char * message,FLAC__StreamEncoderInitStatus init_status)2644 void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status)
2645 {
2646 	const int ilen = strlen(e->inbasefilename) + 1;
2647 	const char *state_string = "";
2648 
2649 	flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2650 
2651 	flac__utils_printf(stderr, 1, "%*s init_status = %s\n", ilen, "", FLAC__StreamEncoderInitStatusString[init_status]);
2652 
2653 	if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR) {
2654 		state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
2655 
2656 		flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2657 
2658 		/* print out some more info for some errors: */
2659 		if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
2660 			flac__utils_printf(stderr, 1,
2661 				"\n"
2662 				"An error occurred while writing; the most common cause is that the disk is full.\n"
2663 			);
2664 		}
2665 		else if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_IO_ERROR])) {
2666 			flac__utils_printf(stderr, 1,
2667 				"\n"
2668 				"An error occurred opening the output file; it is likely that the output\n"
2669 				"directory does not exist or is not writable, the output file already exists and\n"
2670 #ifdef _WIN32
2671 				"is not writeable, the disk is full or the file has a filename that exceeds the\n"
2672 				"path length limit.\n"
2673 #else
2674 				"is not writable, or the disk is full.\n"
2675 #endif
2676 			);
2677 		}
2678 	}
2679 	else if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE) {
2680 		flac__utils_printf(stderr, 1,
2681 			"\n"
2682 			"The encoding parameters specified do not conform to the FLAC Subset and may not\n"
2683 			"be streamable or playable in hardware devices.  If you really understand the\n"
2684 			"consequences, you can add --lax to the command-line options to encode with\n"
2685 			"these parameters anyway.  See http://xiph.org/flac/format.html#subset\n"
2686 		);
2687 	}
2688 }
2689 
print_error_with_state(const EncoderSession * e,const char * message)2690 void print_error_with_state(const EncoderSession *e, const char *message)
2691 {
2692 	const int ilen = strlen(e->inbasefilename) + 1;
2693 	const char *state_string;
2694 
2695 	flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2696 
2697 	state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
2698 
2699 	flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2700 
2701 	/* print out some more info for some errors: */
2702 	if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
2703 		flac__utils_printf(stderr, 1,
2704 			"\n"
2705 			"An error occurred while writing; the most common cause is that the disk is full.\n"
2706 		);
2707 	}
2708 }
2709 
print_verify_error(EncoderSession * e)2710 void print_verify_error(EncoderSession *e)
2711 {
2712 	FLAC__uint64 absolute_sample;
2713 	uint32_t frame_number;
2714 	uint32_t channel;
2715 	uint32_t sample;
2716 	FLAC__int32 expected;
2717 	FLAC__int32 got;
2718 
2719 	FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2720 
2721 	flac__utils_printf(stderr, 1, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
2722 	flac__utils_printf(stderr, 1, "       Absolute sample=%" PRIu64 ", frame=%u, channel=%u, sample=%u, expected %d, got %d\n", absolute_sample, frame_number, channel, sample, expected, got);
2723 	flac__utils_printf(stderr, 1, "       In all known cases, verify errors are caused by hardware problems,\n");
2724 	flac__utils_printf(stderr, 1, "       usually overclocking or bad RAM.  Delete %s\n", e->outfilename);
2725 	flac__utils_printf(stderr, 1, "       and repeat the flac command exactly as before.  If it does not give a\n");
2726 	flac__utils_printf(stderr, 1, "       verify error in the exact same place each time you try it, then there is\n");
2727 	flac__utils_printf(stderr, 1, "       a problem with your hardware; please see the FAQ:\n");
2728 	flac__utils_printf(stderr, 1, "           http://xiph.org/flac/faq.html#tools__hardware_prob\n");
2729 	flac__utils_printf(stderr, 1, "       If it does fail in the exact same place every time, keep\n");
2730 	flac__utils_printf(stderr, 1, "       %s and submit a bug report to:\n", e->outfilename);
2731 	flac__utils_printf(stderr, 1, "           https://github.com/xiph/flac/issues\n");
2732 	flac__utils_printf(stderr, 1, "       Make sure to upload the FLAC file and use the \"Monitor\" feature to\n");
2733 	flac__utils_printf(stderr, 1, "       monitor the bug status.\n");
2734 	flac__utils_printf(stderr, 1, "Verify FAILED!  Do not trust %s\n", e->outfilename);
2735 }
2736 
read_bytes(FILE * f,FLAC__byte * buf,size_t n,FLAC__bool eof_ok,const char * fn)2737 FLAC__bool read_bytes(FILE *f, FLAC__byte *buf, size_t n, FLAC__bool eof_ok, const char *fn)
2738 {
2739 	size_t bytes_read = fread(buf, 1, n, f);
2740 
2741 	if(bytes_read == 0) {
2742 		if(!eof_ok) {
2743 			flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2744 			return false;
2745 		}
2746 		else
2747 			return true;
2748 	}
2749 	if(bytes_read < n) {
2750 		flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2751 		return false;
2752 	}
2753 	return true;
2754 }
2755 
read_uint16(FILE * f,FLAC__bool big_endian,FLAC__uint16 * val,const char * fn)2756 FLAC__bool read_uint16(FILE *f, FLAC__bool big_endian, FLAC__uint16 *val, const char *fn)
2757 {
2758 	if(!read_bytes(f, (FLAC__byte*)val, 2, /*eof_ok=*/false, fn))
2759 		return false;
2760 	if(is_big_endian_host_ != big_endian) {
2761 		FLAC__byte tmp, *b = (FLAC__byte*)val;
2762 		tmp = b[1]; b[1] = b[0]; b[0] = tmp;
2763 	}
2764 	return true;
2765 }
2766 
read_uint32(FILE * f,FLAC__bool big_endian,FLAC__uint32 * val,const char * fn)2767 FLAC__bool read_uint32(FILE *f, FLAC__bool big_endian, FLAC__uint32 *val, const char *fn)
2768 {
2769 	if(!read_bytes(f, (FLAC__byte*)val, 4, /*eof_ok=*/false, fn))
2770 		return false;
2771 	if(is_big_endian_host_ != big_endian) {
2772 		FLAC__byte tmp, *b = (FLAC__byte*)val;
2773 		tmp = b[3]; b[3] = b[0]; b[0] = tmp;
2774 		tmp = b[2]; b[2] = b[1]; b[1] = tmp;
2775 	}
2776 	return true;
2777 }
2778 
read_uint64(FILE * f,FLAC__bool big_endian,FLAC__uint64 * val,const char * fn)2779 FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn)
2780 {
2781 	if(!read_bytes(f, (FLAC__byte*)val, 8, /*eof_ok=*/false, fn))
2782 		return false;
2783 	if(is_big_endian_host_ != big_endian) {
2784 		FLAC__byte tmp, *b = (FLAC__byte*)val;
2785 		tmp = b[7]; b[7] = b[0]; b[0] = tmp;
2786 		tmp = b[6]; b[6] = b[1]; b[1] = tmp;
2787 		tmp = b[5]; b[5] = b[2]; b[2] = tmp;
2788 		tmp = b[4]; b[4] = b[3]; b[3] = tmp;
2789 	}
2790 	return true;
2791 }
2792 
read_sane_extended(FILE * f,FLAC__uint32 * val,const char * fn)2793 FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn)
2794 	/* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
2795 	 * convert it into an integral value and store in 'val'.  Return false if only
2796 	 * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f', or if the
2797 	 * value is negative, between zero and one, or too large to be represented by
2798 	 * 'val'; return true otherwise.
2799 	 */
2800 {
2801 	uint32_t i;
2802 	FLAC__byte buf[10];
2803 	FLAC__uint64 p = 0;
2804 	FLAC__int16 e;
2805 	FLAC__int16 shift;
2806 
2807 	if(!read_bytes(f, buf, sizeof(buf), /*eof_ok=*/false, fn))
2808 		return false;
2809 	e = ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
2810 	shift = 63-e;
2811 	if((buf[0]>>7)==1U || e<0 || e>=63) {
2812 		flac__utils_printf(stderr, 1, "%s: ERROR: invalid floating-point value\n", fn);
2813 		return false;
2814 	}
2815 
2816 	for(i = 0; i < 8; ++i)
2817 		p |= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
2818 	*val = (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1));
2819 
2820 	return true;
2821 }
2822 
fskip_ahead(FILE * f,FLAC__uint64 offset)2823 FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset)
2824 {
2825 	static uint8_t dump[8192];
2826 	struct flac_stat_s stb;
2827 
2828 	if(flac_fstat(fileno(f), &stb) == 0 && (stb.st_mode & S_IFMT) == S_IFREG)
2829 	{
2830 		if(fseeko(f, offset, SEEK_CUR) == 0)
2831 			return true;
2832 	}
2833 	while(offset > 0) {
2834 		const long need = (long)min(offset, sizeof(dump));
2835 		if((long)fread(dump, 1, need, f) < need)
2836 			return false;
2837 		offset -= need;
2838 	}
2839 	return true;
2840 }
2841 
count_channel_mask_bits(FLAC__uint32 mask)2842 uint32_t count_channel_mask_bits(FLAC__uint32 mask)
2843 {
2844 	uint32_t count = 0;
2845 	while(mask) {
2846 		if(mask & 1)
2847 			count++;
2848 		mask >>= 1;
2849 	}
2850 	return count;
2851 }
2852 
2853