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