xref: /aosp_15_r20/external/flac/src/flac/decode.c (revision 600f14f40d737144c998e2ec7a483122d3776fbc)
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000-2009  Josh Coalson
3  * Copyright (C) 2011-2023  Xiph.Org Foundation
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
20 #ifdef HAVE_CONFIG_H
21 #  include <config.h>
22 #endif
23 
24 #include <errno.h>
25 #include <math.h> /* for floor() */
26 #include <stdio.h> /* for FILE etc. */
27 #include <string.h> /* for strcmp(), strerror() */
28 #include <time.h> /* for clock() */
29 #include "FLAC/all.h"
30 #include "share/grabbag.h"
31 #include "share/replaygain_synthesis.h"
32 #include "share/compat.h"
33 #include "decode.h"
34 
35 typedef struct {
36 #if FLAC__HAS_OGG
37 	FLAC__bool is_ogg;
38 	FLAC__bool use_first_serial_number;
39 	long serial_number;
40 #endif
41 
42 	FileFormat format;
43 	FileSubFormat subformat;
44 	FLAC__bool treat_warnings_as_errors;
45 	FLAC__bool continue_through_decode_errors;
46 	FLAC__bool channel_map_none;
47 	FLAC__bool relaxed_foreign_metadata_handling;
48 
49 	struct {
50 		replaygain_synthesis_spec_t spec;
51 		FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */
52 		double scale;
53 		DitherContext dither_context;
54 	} replaygain;
55 
56 	FLAC__bool test_only;
57 	FLAC__bool analysis_mode;
58 	analysis_options aopts;
59 	utils__SkipUntilSpecification *skip_specification;
60 	utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
61 	utils__CueSpecification *cue_specification;
62 
63 	const char *inbasefilename;
64 	const char *infilename;
65 	const char *outfilename;
66 
67 	FLAC__uint64 samples_processed;
68 	uint32_t frame_counter;
69 	FLAC__bool abort_flag;
70 	FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
71 	FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */
72 	FLAC__bool error_callback_suppress_messages; /* turn on to prevent repeating messages from the error callback */
73 	FLAC__bool warn_user_about_foreign_metadata; /* to prevent more than one warning message per file */
74 
75 	FLAC__bool iff_headers_need_fixup;
76 
77 	FLAC__bool is_big_endian;
78 	FLAC__bool is_unsigned_samples;
79 	FLAC__bool got_stream_info;
80 	FLAC__bool has_md5sum;
81 	FLAC__uint64 total_samples;
82 	uint32_t bps;
83 	uint32_t channels;
84 	uint32_t sample_rate;
85 	FLAC__uint32 channel_mask;
86 
87 	/* these are used only in analyze mode */
88 	FLAC__uint64 decode_position;
89 
90 	FLAC__StreamDecoder *decoder;
91 
92 	FILE *fout;
93 
94 	foreign_metadata_t *foreign_metadata; /* NULL unless --keep-foreign-metadata requested */
95 	FLAC__off_t fm_offset1, fm_offset2, fm_offset3;
96 
97 	clock_t old_clock_t;
98 } DecoderSession;
99 
100 
101 static FLAC__bool is_big_endian_host_;
102 
103 
104 /*
105  * local routines
106  */
107 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool use_first_serial_number, long serial_number, FileFormat format, FileSubFormat subformat, FLAC__bool treat_warnings_as_errors, FLAC__bool continue_through_decode_errors, FLAC__bool channel_map_none, FLAC__bool relaxed_foreign_metadata_handling, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, foreign_metadata_t *foreign_metadata, const char *infilename, const char *outfilename);
108 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
109 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, const char *infilename);
110 static FLAC__bool DecoderSession_process(DecoderSession *d);
111 static int DecoderSession_finish_ok(DecoderSession *d);
112 static int DecoderSession_finish_error(DecoderSession *d);
113 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);
114 static FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples);
115 static FLAC__bool write_riff_wave_fmt_chunk_body(FILE *f, FLAC__bool is_waveformatextensible, uint32_t bps, uint32_t channels, uint32_t sample_rate, FLAC__uint32 channel_mask);
116 static FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, uint32_t bps, uint32_t channels, uint32_t sample_rate, FileFormat format, FileSubFormat subformat, FLAC__uint32 comm_length);
117 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
118 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
119 static FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val);
120 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
121 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
122 static FLAC__bool write_sane_extended(FILE *f, uint32_t val);
123 static FLAC__bool fixup_iff_headers(DecoderSession *d);
124 static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
125 static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
126 static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
127 static void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status);
128 static void print_error_with_state(const DecoderSession *d, const char *message);
129 static void print_stats(const DecoderSession *decoder_session);
130 
131 
132 /*
133  * public routines
134  */
flac__decode_file(const char * infilename,const char * outfilename,FLAC__bool analysis_mode,analysis_options aopts,decode_options_t options)135 int flac__decode_file(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, decode_options_t options)
136 {
137 	DecoderSession decoder_session;
138 
139 	FLAC__ASSERT(
140 		options.format == FORMAT_WAVE ||
141 		options.format == FORMAT_WAVE64 ||
142 		options.format == FORMAT_RF64 ||
143 		options.format == FORMAT_AIFF ||
144 		options.format == FORMAT_AIFF_C ||
145 		options.format == FORMAT_RAW
146 	);
147 
148 	if(options.format == FORMAT_RAW) {
149 		decoder_session.is_big_endian = options.format_options.raw.is_big_endian;
150 		decoder_session.is_unsigned_samples = options.format_options.raw.is_unsigned_samples;
151 	}
152 
153 	if(!
154 		DecoderSession_construct(
155 			&decoder_session,
156 #if FLAC__HAS_OGG
157 			options.is_ogg,
158 			options.use_first_serial_number,
159 			options.serial_number,
160 #else
161 			/*is_ogg=*/false,
162 			/*use_first_serial_number=*/false,
163 			/*serial_number=*/0,
164 #endif
165 			options.format,
166 			options.force_subformat,
167 			options.treat_warnings_as_errors,
168 			options.continue_through_decode_errors,
169 			options.channel_map_none,
170 			options.relaxed_foreign_metadata_handling,
171 			options.replaygain_synthesis_spec,
172 			analysis_mode,
173 			aopts,
174 			&options.skip_specification,
175 			&options.until_specification,
176 			options.has_cue_specification? &options.cue_specification : 0,
177 			options.format == FORMAT_RAW? NULL : options.format_options.iff.foreign_metadata,
178 			infilename,
179 			outfilename
180 		)
181 	)
182 		return 1;
183 
184 	stats_new_file();
185 	if(!DecoderSession_init_decoder(&decoder_session, infilename))
186 		return DecoderSession_finish_error(&decoder_session);
187 
188 	if(!DecoderSession_process(&decoder_session))
189 		return DecoderSession_finish_error(&decoder_session);
190 
191 	return DecoderSession_finish_ok(&decoder_session);
192 }
193 
DecoderSession_construct(DecoderSession * d,FLAC__bool is_ogg,FLAC__bool use_first_serial_number,long serial_number,FileFormat format,FileSubFormat subformat,FLAC__bool treat_warnings_as_errors,FLAC__bool continue_through_decode_errors,FLAC__bool channel_map_none,FLAC__bool relaxed_foreign_metadata_handling,replaygain_synthesis_spec_t replaygain_synthesis_spec,FLAC__bool analysis_mode,analysis_options aopts,utils__SkipUntilSpecification * skip_specification,utils__SkipUntilSpecification * until_specification,utils__CueSpecification * cue_specification,foreign_metadata_t * foreign_metadata,const char * infilename,const char * outfilename)194 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool use_first_serial_number, long serial_number, FileFormat format, FileSubFormat subformat, FLAC__bool treat_warnings_as_errors, FLAC__bool continue_through_decode_errors, FLAC__bool channel_map_none, FLAC__bool relaxed_foreign_metadata_handling, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, foreign_metadata_t *foreign_metadata, const char *infilename, const char *outfilename)
195 {
196 #if FLAC__HAS_OGG
197 	d->is_ogg = is_ogg;
198 	d->use_first_serial_number = use_first_serial_number;
199 	d->serial_number = serial_number;
200 #else
201 	(void)is_ogg;
202 	(void)use_first_serial_number;
203 	(void)serial_number;
204 #endif
205 
206 	d->format = format;
207 	d->subformat = subformat;
208 	d->treat_warnings_as_errors = treat_warnings_as_errors;
209 	d->continue_through_decode_errors = continue_through_decode_errors;
210 	d->channel_map_none = channel_map_none;
211 	d->relaxed_foreign_metadata_handling = relaxed_foreign_metadata_handling;
212 	d->replaygain.spec = replaygain_synthesis_spec;
213 	d->replaygain.apply = false;
214 	d->replaygain.scale = 0.0;
215 	/* d->replaygain.dither_context gets initialized later once we know the sample resolution */
216 	d->test_only = (0 == outfilename);
217 	d->analysis_mode = analysis_mode;
218 	d->aopts = aopts;
219 	d->skip_specification = skip_specification;
220 	d->until_specification = until_specification;
221 	d->cue_specification = cue_specification;
222 
223 	d->inbasefilename = grabbag__file_get_basename(infilename);
224 	d->infilename = infilename;
225 	d->outfilename = outfilename;
226 
227 	d->samples_processed = 0;
228 	d->frame_counter = 0;
229 	d->abort_flag = false;
230 	d->aborting_due_to_until = false;
231 	d->aborting_due_to_unparseable = false;
232 	d->error_callback_suppress_messages = false;
233 	if(relaxed_foreign_metadata_handling)
234 		d->warn_user_about_foreign_metadata = false;
235 	else
236 		d->warn_user_about_foreign_metadata = true;
237 
238 	d->iff_headers_need_fixup = false;
239 
240 	d->total_samples = 0;
241 	d->got_stream_info = false;
242 	d->has_md5sum = false;
243 	d->bps = 0;
244 	d->channels = 0;
245 	d->sample_rate = UINT32_MAX;
246 	d->channel_mask = 0;
247 
248 	d->decode_position = 0;
249 
250 	d->decoder = 0;
251 
252 	d->fout = 0; /* initialized with an open file later if necessary */
253 
254 	d->foreign_metadata = foreign_metadata;
255 
256 	d->old_clock_t = 0;
257 
258 	FLAC__ASSERT(!(d->test_only && d->analysis_mode));
259 
260 	if(!d->test_only) {
261 		if(0 == strcmp(outfilename, "-")) {
262 			d->fout = grabbag__file_get_binary_stdout();
263 		}
264 		else {
265 			if(0 == (d->fout = flac_fopen(outfilename, "wb"))) {
266 				flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
267 				DecoderSession_destroy(d, /*error_occurred=*/true);
268 				return false;
269 			}
270 		}
271 	}
272 
273 	if(analysis_mode)
274 		flac__analyze_init(aopts);
275 
276 	return true;
277 }
278 
DecoderSession_destroy(DecoderSession * d,FLAC__bool error_occurred)279 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
280 {
281 	if(0 != d->fout && d->fout != stdout) {
282 #if defined _WIN32 && !defined __CYGWIN__
283 		if(!error_occurred) {
284 			FLAC__off_t written_size = ftello(d->fout);
285 			if(written_size > 0) {
286 				HANDLE fh = CreateFile_utf8(d->outfilename, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
287 				if(fh != INVALID_HANDLE_VALUE) {
288 					if(GetFileType(fh) == FILE_TYPE_DISK) {
289 						LARGE_INTEGER size;
290 						size.QuadPart = written_size;
291 						if(SetFilePointerEx(fh, size, NULL, FILE_CURRENT)) /* correct the file size */
292 							SetEndOfFile(fh);
293 					}
294 					CloseHandle(fh);
295 				}
296 			}
297 		}
298 #endif
299 		fclose(d->fout);
300 
301 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
302 	/* Always delete output file when fuzzing */
303 		if(error_occurred)
304 #endif
305 			flac_unlink(d->outfilename);
306 	}
307 }
308 
DecoderSession_init_decoder(DecoderSession * decoder_session,const char * infilename)309 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, const char *infilename)
310 {
311 	FLAC__StreamDecoderInitStatus init_status;
312 	FLAC__uint32 test = 1;
313 
314 	is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
315 
316 	if(decoder_session->test_only && strcmp(infilename, "-") != 0) {
317 		/* When testing, we can be a little more pedantic, as long
318 		 * as we can seek properly */
319 		FLAC__byte buffer[3];
320 		FILE * f;
321 
322 		if(0 == (f = flac_fopen(infilename, "rb"))) {
323 			flac__utils_printf(stderr, 1, "ERROR: can't open input file %s: %s\n", infilename, strerror(errno));
324 			return false;
325 		}
326 
327 		if(fread(buffer, 1, 3, f) < 3) {
328 			flac__utils_printf(stderr, 1, "%s: ERROR checking for ID3v2 tag\n", decoder_session->inbasefilename);
329 			fclose(f);
330 			return false;
331 		}
332 		if(memcmp(buffer, "ID3", 3) == 0){
333 			flac__utils_printf(stderr, 1, "%s: WARNING, ID3v2 tag found. This is non-standard and strongly discouraged\n", decoder_session->inbasefilename);
334 			if(decoder_session->treat_warnings_as_errors) {
335 				fclose(f);
336 				return false;
337 			}
338 		}
339 		fclose(f);
340 	}
341 
342 	decoder_session->decoder = FLAC__stream_decoder_new();
343 
344 	if(0 == decoder_session->decoder) {
345 		flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
346 		return false;
347 	}
348 
349 	FLAC__stream_decoder_set_md5_checking(decoder_session->decoder, true);
350 	if (0 != decoder_session->cue_specification)
351 		FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_CUESHEET);
352 	if (decoder_session->replaygain.spec.apply || !decoder_session->channel_map_none)
353 		FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
354 
355 	if(!decoder_session->analysis_mode && !decoder_session->test_only && decoder_session->foreign_metadata == NULL) {
356 		/* Warn user if foreign metadata is found */
357 		uint32_t i;
358 		for(i = 0; i < FLAC__FOREIGN_METADATA_NUMBER_OF_RECOGNIZED_APPLICATION_IDS; i++)
359 			FLAC__stream_decoder_set_metadata_respond_application(decoder_session->decoder, (FLAC__byte *)FLAC__FOREIGN_METADATA_APPLICATION_ID[i]);
360 	}
361 
362 #if FLAC__HAS_OGG
363 	if(decoder_session->is_ogg) {
364 		if(!decoder_session->use_first_serial_number)
365 			FLAC__stream_decoder_set_ogg_serial_number(decoder_session->decoder, decoder_session->serial_number);
366 		init_status = FLAC__stream_decoder_init_ogg_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
367 	}
368 	else
369 #endif
370 	{
371 		init_status = FLAC__stream_decoder_init_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
372 	}
373 
374 	if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
375 		print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
376 		return false;
377 	}
378 
379 	return true;
380 }
381 
DecoderSession_process(DecoderSession * d)382 FLAC__bool DecoderSession_process(DecoderSession *d)
383 {
384 	if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder)) {
385 		flac__utils_printf(stderr, 2, "\n");
386 		print_error_with_state(d, "ERROR while decoding metadata");
387 		return false;
388 	}
389 	if(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM) {
390 		flac__utils_printf(stderr, 2, "\n");
391 		print_error_with_state(d, "ERROR during metadata decoding");
392 		if(!d->continue_through_decode_errors)
393 			return false;
394 	}
395 
396 	if(d->analysis_mode)
397 		FLAC__stream_decoder_get_decode_position(d->decoder, &d->decode_position);
398 
399 	if(d->abort_flag)
400 		return false;
401 
402 	/* set channel mapping */
403 	/* currently FLAC order matches SMPTE/WAVEFORMATEXTENSIBLE order, so no reordering is necessary; see encode.c */
404 	/* only the channel mask must be set if it was not already picked up from the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag */
405 	if(!d->channel_map_none && d->channel_mask == 0) {
406 		if(d->channels == 1) {
407 			d->channel_mask = 0x0004;
408 		}
409 		else if(d->channels == 2) {
410 			d->channel_mask = 0x0003;
411 		}
412 		else if(d->channels == 3) {
413 			d->channel_mask = 0x0007;
414 		}
415 		else if(d->channels == 4) {
416 			d->channel_mask = 0x0033;
417 		}
418 		else if(d->channels == 5) {
419 			d->channel_mask = 0x0607;
420 		}
421 		else if(d->channels == 6) {
422 			d->channel_mask = 0x060f;
423 		}
424 		else if(d->channels == 7) {
425 			d->channel_mask = 0x070f;
426 		}
427 		else if(d->channels == 8) {
428 			d->channel_mask = 0x063f;
429 		}
430 	}
431 
432 #if defined _WIN32 && !defined __CYGWIN__
433 	if(!d->analysis_mode && !d->test_only && d->total_samples > 0 && d->fout != stdout) {
434 		HANDLE fh = CreateFile_utf8(d->outfilename, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
435 		if(fh != INVALID_HANDLE_VALUE) {
436 			if (GetFileType(fh) == FILE_TYPE_DISK) {
437 				LARGE_INTEGER size;
438 				size.QuadPart = d->total_samples * d->channels * ((d->bps+7)/8);
439 				if(d->format != FORMAT_RAW) {
440 					size.QuadPart += 512;
441 					if(d->foreign_metadata) {
442 						size_t i;
443 						for(i = d->format==FORMAT_RF64?2:1; i < d->foreign_metadata->num_blocks; i++) {
444 							if(i != d->foreign_metadata->format_block && i != d->foreign_metadata->audio_block)
445 								size.QuadPart += d->foreign_metadata->blocks[i].size;
446 						}
447 					}
448 				}
449 
450 				if(SetFilePointerEx(fh, size, NULL, FILE_CURRENT)) /* tell filesystem the expected filesize to eliminate fragmentation */
451 					SetEndOfFile(fh);
452 			}
453 			CloseHandle(fh);
454 		}
455 	}
456 #endif
457 
458 	/* write the WAVE/AIFF headers if necessary */
459 	if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
460 		if(!write_iff_headers(d->fout, d, d->total_samples)) {
461 			d->abort_flag = true;
462 			return false;
463 		}
464 	}
465 
466 	if(d->skip_specification->value.samples > 0) {
467 		const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
468 
469 		if(!FLAC__stream_decoder_seek_absolute(d->decoder, skip)) {
470 			print_error_with_state(d, "ERROR seeking while skipping bytes");
471 			return false;
472 		}
473 	}
474 	if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder) && !d->aborting_due_to_until) {
475 		flac__utils_printf(stderr, 2, "\n");
476 		print_error_with_state(d, "ERROR while decoding data");
477 		if(!d->continue_through_decode_errors)
478 			return false;
479 	}
480 	if(
481 		(d->abort_flag && !(d->aborting_due_to_until || d->continue_through_decode_errors)) ||
482 		(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until)
483 	) {
484 		flac__utils_printf(stderr, 2, "\n");
485 		print_error_with_state(d, "ERROR during decoding");
486 		return false;
487 	}
488 
489 	/* write padding bytes for alignment if necessary */
490 	if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
491 		const FLAC__uint64 data_size = d->total_samples * d->channels * ((d->bps+7)/8);
492 		uint32_t padding;
493 		if(d->format != FORMAT_WAVE64) {
494 			padding = (uint32_t)(data_size & 1);
495 		}
496 		else {
497 			/* 8-byte alignment for Wave64 */
498 			padding = (8 - (uint32_t)(data_size & 7)) & 7;
499 		}
500 		for( ; padding > 0; --padding) {
501 			if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
502 				print_error_with_state(
503 					d,
504 					d->format == FORMAT_WAVE?   "ERROR writing pad byte to WAVE data chunk" :
505 					d->format == FORMAT_WAVE64? "ERROR writing pad bytes to WAVE64 data chunk" :
506 					d->format == FORMAT_RF64?   "ERROR writing pad byte to RF64 data chunk" :
507 					"ERROR writing pad byte to AIFF SSND chunk"
508 				);
509 				return false;
510 			}
511 		}
512 	}
513 
514 	return true;
515 }
516 
DecoderSession_finish_ok(DecoderSession * d)517 int DecoderSession_finish_ok(DecoderSession *d)
518 {
519 	FLAC__bool ok = true, md5_failure = false;
520 
521 	if(d->decoder) {
522 		md5_failure = !FLAC__stream_decoder_finish(d->decoder) && !d->aborting_due_to_until;
523 		print_stats(d);
524 		FLAC__stream_decoder_delete(d->decoder);
525 	}
526 	if(d->analysis_mode)
527 		flac__analyze_finish(d->aopts);
528 	if(md5_failure) {
529 		stats_print_name(1, d->inbasefilename);
530 		flac__utils_printf(stderr, 1, "ERROR, MD5 signature mismatch\n");
531 		ok = d->continue_through_decode_errors;
532 	}
533 	else if(d->got_stream_info && d->total_samples && (d->total_samples > d->samples_processed)){
534 		stats_print_name(1, d->inbasefilename);
535 		flac__utils_printf(stderr, 1, "ERROR, decoded number of samples is smaller than the total number of samples set in the STREAMINFO\n");
536 		ok = d->continue_through_decode_errors;
537 	}
538 	else {
539 		if(!d->got_stream_info) {
540 			stats_print_name(1, d->inbasefilename);
541 			flac__utils_printf(stderr, 1, "WARNING, cannot check MD5 signature since there was no STREAMINFO\n");
542 			ok = !d->treat_warnings_as_errors;
543 		}
544 		else if(!d->has_md5sum) {
545 			stats_print_name(1, d->inbasefilename);
546 			flac__utils_printf(stderr, 1, "WARNING, cannot check MD5 signature since it was unset in the STREAMINFO\n");
547 			ok = !d->treat_warnings_as_errors;
548 		}
549 		else if(!d->total_samples) {
550 			stats_print_name(1, d->inbasefilename);
551 			flac__utils_printf(stderr, 1, "WARNING, cannot check total number of samples since it was unset in the STREAMINFO\n");
552 			ok = !d->treat_warnings_as_errors;
553 		}
554 		stats_print_name(2, d->inbasefilename);
555 		flac__utils_printf(stderr, 2, "%s         \n", d->test_only? "ok           ":d->analysis_mode?"done           ":"done");
556 	}
557 	DecoderSession_destroy(d, /*error_occurred=*/!ok);
558 	if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
559 		if(d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))) {
560 			if(!fixup_iff_headers(d))
561 				return 1;
562 		}
563 		if(d->foreign_metadata) {
564 			const char *error;
565 			if(!flac__foreign_metadata_write_to_iff(d->foreign_metadata, d->infilename, d->outfilename, d->fm_offset1, d->fm_offset2, d->fm_offset3, &error)) {
566 				flac__utils_printf(stderr, 1, "ERROR updating foreign metadata from %s to %s: %s\n", d->infilename, d->outfilename, error);
567 				return 1;
568 			}
569 			if(!flac__foreign_metadata_compare_with_iff(d->foreign_metadata, d->infilename, d->outfilename, d->fm_offset3, &error)) {
570 				flac__utils_printf(stderr, 1, "ERROR verifying foreign metadata restore from %s to %s: %s\n", d->infilename, d->outfilename, error);
571 				return 1;
572 			}
573 		}
574 	}
575 	return ok? 0 : 1;
576 }
577 
DecoderSession_finish_error(DecoderSession * d)578 int DecoderSession_finish_error(DecoderSession *d)
579 {
580 	if(d->decoder) {
581 		(void)FLAC__stream_decoder_finish(d->decoder);
582 		FLAC__stream_decoder_delete(d->decoder);
583 	}
584 	if(d->analysis_mode)
585 		flac__analyze_finish(d->aopts);
586 	DecoderSession_destroy(d, /*error_occurred=*/true);
587 	return 1;
588 }
589 
canonicalize_until_specification(utils__SkipUntilSpecification * spec,const char * inbasefilename,uint32_t sample_rate,FLAC__uint64 skip,FLAC__uint64 total_samples_in_input)590 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, uint32_t sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
591 {
592 	/* convert from mm:ss.sss to sample number if necessary */
593 	if(!flac__utils_canonicalize_skip_until_specification(spec, sample_rate)) {
594 		flac__utils_printf(stderr, 1, "%s: ERROR, value of --until is too large\n", inbasefilename);
595 		return false;
596 	}
597 
598 	/* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
599 	if(spec->is_relative && spec->value.samples == 0) {
600 		spec->is_relative = false;
601 		return true;
602 	}
603 
604 	/* in any other case the total samples in the input must be known */
605 	if(total_samples_in_input == 0) {
606 		flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
607 		return false;
608 	}
609 
610 	FLAC__ASSERT(spec->value_is_samples);
611 
612 	/* convert relative specifications to absolute */
613 	if(spec->is_relative) {
614 		if(spec->value.samples <= 0)
615 			spec->value.samples += (FLAC__int64)total_samples_in_input;
616 		else
617 			spec->value.samples += skip;
618 		spec->is_relative = false;
619 	}
620 
621 	/* error check */
622 	if(spec->value.samples < 0) {
623 		flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
624 		return false;
625 	}
626 	if((FLAC__uint64)spec->value.samples <= skip) {
627 		flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
628 		return false;
629 	}
630 	if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
631 		flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
632 		return false;
633 	}
634 
635 	return true;
636 }
637 
write_iff_headers(FILE * f,DecoderSession * decoder_session,FLAC__uint64 samples)638 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
639 {
640 	const FileFormat format = decoder_session->format;
641 	const FileSubFormat subformat = decoder_session->subformat;
642 	const char *fmt_desc =
643 		format==FORMAT_WAVE? "WAVE" :
644 		format==FORMAT_WAVE64? "Wave64" :
645 		format==FORMAT_RF64? "RF64" :
646 		format==FORMAT_AIFF? "AIFF" :
647 		"AIFC";
648 	const FLAC__bool is_waveformatextensible =
649 		subformat == SUBFORMAT_WAVE_EXTENSIBLE || (
650 		(format == FORMAT_WAVE || format == FORMAT_WAVE64 || format == FORMAT_RF64) &&
651 		subformat != SUBFORMAT_WAVE_PCM &&
652 		(
653 			(decoder_session->channel_mask != 0 && decoder_session->channel_mask != 0x0004 && decoder_session->channel_mask != 0x0003) ||
654 			(decoder_session->bps != 8 && decoder_session->bps != 16) ||
655 			decoder_session->channels > 2
656 		));
657 	const FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
658 	const FLAC__uint64 aligned_data_size =
659 		format == FORMAT_WAVE64?
660 			(data_size+7) & (~(FLAC__uint64)7) :
661 			(data_size+1) & (~(FLAC__uint64)1);
662 
663 	FLAC__uint64 iff_size;
664 	uint32_t foreign_metadata_size = 0; /* size of all non-audio non-fmt/COMM foreign metadata chunks */
665 	foreign_metadata_t *fm = decoder_session->foreign_metadata;
666 	size_t i;
667 
668 	FLAC__ASSERT(
669 		format == FORMAT_WAVE ||
670 		format == FORMAT_WAVE64 ||
671 		format == FORMAT_RF64 ||
672 		format == FORMAT_AIFF ||
673 		format == FORMAT_AIFF_C
674 	);
675 
676 	if(samples == 0) {
677 		if(f == stdout) {
678 			flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
679 			flac__utils_printf(stderr, 1, "             Generated %s file will have a data chunk size of 0.  Try\n", fmt_desc);
680 			flac__utils_printf(stderr, 1, "             decoding directly to a file instead.\n");
681 			if(decoder_session->treat_warnings_as_errors)
682 				return false;
683 		}
684 		else {
685 			decoder_session->iff_headers_need_fixup = true;
686 		}
687 	}
688 
689 	if(fm) {
690 		FLAC__ASSERT(fm->format_block);
691 		FLAC__ASSERT(fm->audio_block);
692 		FLAC__ASSERT(fm->format_block < fm->audio_block);
693 		/* calc foreign metadata size; we always skip the first chunk, ds64 chunk, format chunk, and sound chunk since we write our own */
694 		for(i = format==FORMAT_RF64?2:1; i < fm->num_blocks; i++) {
695 			if(i != fm->format_block && i != fm->audio_block)
696 				foreign_metadata_size += fm->blocks[i].size;
697 		}
698 	}
699 
700 	if(samples == 0)
701 		iff_size = 0;
702 	else if(format == FORMAT_WAVE || format == FORMAT_RF64)
703 		/* 4 for WAVE form bytes */
704 		/* +{36,0} for ds64 chunk */
705 		/* +8+{40,16} for fmt chunk header and body */
706 		/* +8 for data chunk header */
707 		iff_size = 4 + (format==FORMAT_RF64?36:0) + 8+(is_waveformatextensible?40:16) + 8 + foreign_metadata_size + aligned_data_size;
708 	else if(format == FORMAT_WAVE64)
709 		/* 16+8 for RIFF GUID and size field */
710 		/* +16 for WAVE GUID */
711 		/* +16+8+{40,16} for fmt chunk header (GUID and size field) and body */
712 		/* +16+8 for data chunk header (GUID and size field) */
713 		iff_size = 16+8 + 16 + 16+8+(is_waveformatextensible?40:16) + 16+8 + foreign_metadata_size + aligned_data_size;
714 	else if(format == FORMAT_AIFF)
715 		iff_size = 46 + foreign_metadata_size + aligned_data_size;
716 	else /* AIFF-C */
717 		iff_size = 16 + foreign_metadata_size + aligned_data_size + (fm?fm->aifc_comm_length:0);
718 
719 	if(format != FORMAT_WAVE64 && format != FORMAT_RF64 && iff_size >= 0xFFFFFFF4) {
720 		flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file\n", decoder_session->inbasefilename, fmt_desc);
721 		return false;
722 	}
723 
724 	if(format == FORMAT_WAVE || format == FORMAT_WAVE64 || format == FORMAT_RF64) {
725 		/* RIFF header */
726 		switch(format) {
727 			case FORMAT_WAVE:
728 				if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
729 					return false;
730 				if(!write_little_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
731 					return false;
732 				if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
733 					return false;
734 				break;
735 			case FORMAT_WAVE64:
736 				/* RIFF GUID 66666972-912E-11CF-A5D6-28DB04C10000 */
737 				if(flac__utils_fwrite("\x72\x69\x66\x66\x2E\x91\xCF\x11\xA5\xD6\x28\xDB\x04\xC1\x00\x00", 1, 16, f) != 16)
738 					return false;
739 				if(!write_little_endian_uint64(f, iff_size))
740 					return false;
741 				/* WAVE GUID 65766177-ACF3-11D3-8CD1-00C04F8EDB8A */
742 				if(flac__utils_fwrite("\x77\x61\x76\x65\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
743 					return false;
744 				break;
745 			case FORMAT_RF64:
746 				if(flac__utils_fwrite("RF64", 1, 4, f) != 4)
747 					return false;
748 				if(!write_little_endian_uint32(f, 0xffffffff))
749 					return false;
750 				if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
751 					return false;
752 				break;
753 			default:
754 				return false;
755 		}
756 
757 		/* ds64 chunk for RF64 */
758 		if(format == FORMAT_RF64) {
759 			if(flac__utils_fwrite("ds64", 1, 4, f) != 4)
760 				return false;
761 
762 			if(!write_little_endian_uint32(f, 28)) /* chunk size */
763 				return false;
764 
765 			if(!write_little_endian_uint64(f, iff_size))
766 				return false;
767 
768 			if(!write_little_endian_uint64(f, data_size))
769 				return false;
770 
771 			if(!write_little_endian_uint64(f, samples)) /*@@@@@@ correct? */
772 				return false;
773 
774 			if(!write_little_endian_uint32(f, 0)) /* table size */
775 				return false;
776 		}
777 
778 		decoder_session->fm_offset1 = ftello(f);
779 
780 		if(fm) {
781 			/* seek forward to {allocate} or {skip over already-written chunks} before "fmt " */
782 			for(i = format==FORMAT_RF64?2:1; i < fm->format_block; i++) {
783 				if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
784 					flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"fmt \"\n", decoder_session->inbasefilename);
785 					return false;
786 				}
787 			}
788 		}
789 
790 		if(format != FORMAT_WAVE64) {
791 			if(flac__utils_fwrite("fmt ", 1, 4, f) != 4)
792 				return false;
793 			if(!write_little_endian_uint32(f, is_waveformatextensible? 40 : 16)) /* chunk size */
794 				return false;
795 		}
796 		else { /* Wave64 */
797 			/* fmt GUID 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A */
798 			if(flac__utils_fwrite("\x66\x6D\x74\x20\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
799 				return false;
800 			/* chunk size (+16+8 for GUID and size fields) */
801 			if(!write_little_endian_uint64(f, 16+8+(is_waveformatextensible?40:16)))
802 				return false;
803 		}
804 
805 		if(!write_riff_wave_fmt_chunk_body(f, is_waveformatextensible, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate, decoder_session->channel_mask))
806 			return false;
807 
808 		decoder_session->fm_offset2 = ftello(f);
809 
810 		if(fm) {
811 			/* seek forward to {allocate} or {skip over already-written chunks} after "fmt " but before "data" */
812 			for(i = fm->format_block+1; i < fm->audio_block; i++) {
813 				if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
814 					flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"fmt \"\n", decoder_session->inbasefilename);
815 					return false;
816 				}
817 			}
818 		}
819 
820 		if(format != FORMAT_WAVE64) {
821 			if(flac__utils_fwrite("data", 1, 4, f) != 4)
822 				return false;
823 			if(!write_little_endian_uint32(f, format==FORMAT_RF64? 0xffffffff : (FLAC__uint32)data_size))
824 				return false;
825 		}
826 		else { /* Wave64 */
827 			/* data GUID 61746164-ACF3-11D3-8CD1-00C04F8EDB8A */
828 			if(flac__utils_fwrite("\x64\x61\x74\x61\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
829 				return false;
830 			/* +16+8 for GUID and size fields */
831 			if(!write_little_endian_uint64(f, 16+8 + data_size))
832 				return false;
833 		}
834 
835 		decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
836 	}
837 	else {
838 		if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
839 			return false;
840 
841 		if(!write_big_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
842 			return false;
843 
844 		if(format == FORMAT_AIFF) {
845 			if(flac__utils_fwrite("AIFF", 1, 4, f) != 4)
846 				return false;
847 		}
848 		else
849 			if(flac__utils_fwrite("AIFC", 1, 4, f) != 4)
850 				return false;
851 
852 		decoder_session->fm_offset1 = ftello(f);
853 
854 		if(fm) {
855 			/* seek forward to {allocate} or {skip over already-written chunks} before "COMM" */
856 			for(i = 1; i < fm->format_block; i++) {
857 				if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
858 					flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"COMM\"\n", decoder_session->inbasefilename);
859 					return false;
860 				}
861 			}
862 		}
863 
864 		if(!write_aiff_form_comm_chunk(f, samples, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate, format, subformat, fm?fm->aifc_comm_length:0))
865 			return false;
866 
867 		decoder_session->fm_offset2 = ftello(f);
868 
869 		if(fm) {
870 			/* seek forward to {allocate} or {skip over already-written chunks} after "COMM" but before "SSND" */
871 			for(i = fm->format_block+1; i < fm->audio_block; i++) {
872 				if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
873 					flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"COMM\"\n", decoder_session->inbasefilename);
874 					return false;
875 				}
876 			}
877 		}
878 
879 		if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
880 			return false;
881 
882 		if(!write_big_endian_uint32(f, (FLAC__uint32)data_size + 8)) /* data size */
883 			return false;
884 
885 		if(!write_big_endian_uint32(f, 0/*offset_size*/))
886 			return false;
887 
888 		if(!write_big_endian_uint32(f, 0/*block_size*/))
889 			return false;
890 
891 		decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
892 	}
893 
894 	return true;
895 }
896 
write_riff_wave_fmt_chunk_body(FILE * f,FLAC__bool is_waveformatextensible,uint32_t bps,uint32_t channels,uint32_t sample_rate,FLAC__uint32 channel_mask)897 FLAC__bool write_riff_wave_fmt_chunk_body(FILE *f, FLAC__bool is_waveformatextensible, uint32_t bps, uint32_t channels, uint32_t sample_rate, FLAC__uint32 channel_mask)
898 {
899 	if(!write_little_endian_uint16(f, (FLAC__uint16)(is_waveformatextensible? 65534 : 1))) /* compression code */
900 		return false;
901 
902 	if(!write_little_endian_uint16(f, (FLAC__uint16)channels))
903 		return false;
904 
905 	if(!write_little_endian_uint32(f, sample_rate))
906 		return false;
907 
908 	if(!write_little_endian_uint32(f, sample_rate * channels * ((bps+7) / 8)))
909 		return false;
910 
911 	if(!write_little_endian_uint16(f, (FLAC__uint16)(channels * ((bps+7) / 8)))) /* block align */
912 		return false;
913 
914 	if(!write_little_endian_uint16(f, (FLAC__uint16)(((bps+7)/8)*8))) /* bits per sample */
915 		return false;
916 
917 	if(is_waveformatextensible) {
918 		if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */
919 			return false;
920 
921 		if(!write_little_endian_uint16(f, (FLAC__uint16)bps)) /* validBitsPerSample */
922 			return false;
923 
924 		if(!write_little_endian_uint32(f, channel_mask))
925 			return false;
926 
927 		/* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */
928 		if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16)
929 			return false;
930 	}
931 
932 	return true;
933 }
934 
write_aiff_form_comm_chunk(FILE * f,FLAC__uint64 samples,uint32_t bps,uint32_t channels,uint32_t sample_rate,FileFormat format,FileSubFormat subformat,FLAC__uint32 comm_length)935 FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, uint32_t bps, uint32_t channels, uint32_t sample_rate, FileFormat format, FileSubFormat subformat, FLAC__uint32 comm_length)
936 {
937 	FLAC__uint32 i;
938 	FLAC__ASSERT(samples <= 0xffffffff);
939 
940 	if(comm_length == 0) {
941 		if(format == FORMAT_AIFF)
942 			comm_length = 30;
943 		else
944 			comm_length = 36;
945 	}
946 
947 	if(flac__utils_fwrite("COMM", 1, 4, f) != 4)
948 		return false;
949 
950 	if(!write_big_endian_uint32(f, comm_length-12)) /* chunk size = 18 */
951 		return false;
952 
953 	if(!write_big_endian_uint16(f, (FLAC__uint16)channels))
954 		return false;
955 
956 	if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
957 		return false;
958 
959 	if(!write_big_endian_uint16(f, (FLAC__uint16)bps))
960 		return false;
961 
962 	if(!write_sane_extended(f, sample_rate))
963 		return false;
964 
965 	if(format == FORMAT_AIFF_C) {
966 		if(subformat == SUBFORMAT_AIFF_C_NONE) {
967 			if(flac__utils_fwrite("NONE", 1, 4, f) != 4)
968 				return false;
969 		}
970 		else if(subformat == SUBFORMAT_AIFF_C_SOWT) {
971 			if(flac__utils_fwrite("sowt", 1, 4, f) != 4)
972 				return false;
973 		}
974 		for(i = 34; i < comm_length; i++) {
975 			if(flac__utils_fwrite("\x00", 1, 1, f) != 1)
976 				return false;
977 		}
978 	}
979 
980 
981 
982 	return true;
983 }
984 
write_little_endian_uint16(FILE * f,FLAC__uint16 val)985 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
986 {
987 	FLAC__byte *b = (FLAC__byte*)(&val);
988 	if(is_big_endian_host_) {
989 		FLAC__byte tmp;
990 		tmp = b[1]; b[1] = b[0]; b[0] = tmp;
991 	}
992 	return flac__utils_fwrite(b, 1, 2, f) == 2;
993 }
994 
write_little_endian_uint32(FILE * f,FLAC__uint32 val)995 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
996 {
997 	FLAC__byte *b = (FLAC__byte*)(&val);
998 	if(is_big_endian_host_) {
999 		FLAC__byte tmp;
1000 		tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1001 		tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1002 	}
1003 	return flac__utils_fwrite(b, 1, 4, f) == 4;
1004 }
1005 
write_little_endian_uint64(FILE * f,FLAC__uint64 val)1006 FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val)
1007 {
1008 	FLAC__byte *b = (FLAC__byte*)(&val);
1009 	if(is_big_endian_host_) {
1010 		FLAC__byte tmp;
1011 		tmp = b[7]; b[7] = b[0]; b[0] = tmp;
1012 		tmp = b[6]; b[6] = b[1]; b[1] = tmp;
1013 		tmp = b[5]; b[5] = b[2]; b[2] = tmp;
1014 		tmp = b[4]; b[4] = b[3]; b[3] = tmp;
1015 	}
1016 	return flac__utils_fwrite(b, 1, 8, f) == 8;
1017 }
1018 
write_big_endian_uint16(FILE * f,FLAC__uint16 val)1019 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
1020 {
1021 	FLAC__byte *b = (FLAC__byte*)(&val);
1022 	if(!is_big_endian_host_) {
1023 		FLAC__byte tmp;
1024 		tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1025 	}
1026 	return flac__utils_fwrite(b, 1, 2, f) == 2;
1027 }
1028 
write_big_endian_uint32(FILE * f,FLAC__uint32 val)1029 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
1030 {
1031 	FLAC__byte *b = (FLAC__byte*)(&val);
1032 	if(!is_big_endian_host_) {
1033 		FLAC__byte tmp;
1034 		tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1035 		tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1036 	}
1037 	return flac__utils_fwrite(b, 1, 4, f) == 4;
1038 }
1039 
write_sane_extended(FILE * f,uint32_t val)1040 FLAC__bool write_sane_extended(FILE *f, uint32_t val)
1041 	/* Write to 'f' a SANE extended representation of 'val'.  Return false if
1042 	* the write succeeds; return true otherwise.
1043 	*
1044 	* SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
1045 	* of exponent, and 64 bits of significand (mantissa).  Unlike most IEEE-754
1046 	* representations, it does not imply a 1 above the MSB of the significand.
1047 	*
1048 	*/
1049 {
1050 	uint32_t shift, exponent;
1051 
1052 	if(val == 0U) {
1053 		if(!write_big_endian_uint16(f, 0))
1054 			return false;
1055 		if(!write_big_endian_uint32(f, 0))
1056 			return false;
1057 		if(!write_big_endian_uint32(f, 0))
1058 			return false;
1059 		return true;
1060 	}
1061 
1062 	for(shift= 0U; (val>>(31-shift))==0U; ++shift)
1063 		;
1064 	val<<= shift;
1065 	exponent= 63U-(shift+32U); /* add 32 for unused second word */
1066 
1067 	if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
1068 		return false;
1069 	if(!write_big_endian_uint32(f, val))
1070 		return false;
1071 	if(!write_big_endian_uint32(f, 0)) /* unused second word */
1072 		return false;
1073 
1074 	return true;
1075 }
1076 
fixup_iff_headers(DecoderSession * d)1077 FLAC__bool fixup_iff_headers(DecoderSession *d)
1078 {
1079 	const char *fmt_desc =
1080 		d->format==FORMAT_WAVE? "WAVE" :
1081 		d->format==FORMAT_WAVE64? "Wave64" :
1082 		d->format==FORMAT_RF64? "RF64" :
1083 		"AIFF";
1084 	FILE *f = flac_fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
1085 
1086 	if(0 == f) {
1087 		flac__utils_printf(stderr, 1, "ERROR, couldn't open file %s while fixing up %s chunk size: %s\n", d->outfilename, fmt_desc, strerror(errno));
1088 		return false;
1089 	}
1090 
1091 	if(!write_iff_headers(f, d, d->samples_processed)) {
1092 		fclose(f);
1093 		return false;
1094 	}
1095 
1096 	fclose(f);
1097 	return true;
1098 }
1099 
write_callback(const FLAC__StreamDecoder * decoder,const FLAC__Frame * frame,const FLAC__int32 * const buffer[],void * client_data)1100 FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
1101 {
1102 	DecoderSession *decoder_session = (DecoderSession*)client_data;
1103 	FILE *fout = decoder_session->fout;
1104 	const uint32_t bps = frame->header.bits_per_sample, channels = frame->header.channels;
1105 	const uint32_t shift = (bps%8)? 8-(bps%8): 0;
1106 	FLAC__bool is_big_endian = (
1107 		(decoder_session->format == FORMAT_AIFF || (decoder_session->format == FORMAT_AIFF_C && decoder_session->subformat == SUBFORMAT_AIFF_C_NONE)) ? true : (
1108 		decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 || (decoder_session->format == FORMAT_AIFF_C && decoder_session->subformat == SUBFORMAT_AIFF_C_SOWT) ? false :
1109 		decoder_session->is_big_endian
1110 	));
1111 	FLAC__bool is_unsigned_samples = (
1112 		decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? false : (
1113 		decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 ? bps<=8 :
1114 		decoder_session->is_unsigned_samples
1115 	));
1116 	uint32_t wide_samples = frame->header.blocksize, wide_sample, sample, channel;
1117 	FLAC__uint64 frame_bytes = 0;
1118 
1119 	static union
1120 	{	/* The arrays defined within this union are all the same size. */
1121 		FLAC__int8	 s8buffer	[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
1122 		FLAC__uint8  u8buffer	[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)];
1123 		FLAC__int16  s16buffer	[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int16)];
1124 		FLAC__uint16 u16buffer	[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int16)];
1125 		FLAC__int32  s32buffer	[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS];
1126 		FLAC__uint32 u32buffer	[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS];
1127 	} ubuf;
1128 
1129 	size_t bytes_to_write = 0;
1130 
1131 	(void)decoder;
1132 
1133 	if(decoder_session->abort_flag)
1134 		return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1135 
1136 	/* sanity-check the bits-per-sample */
1137 	if(decoder_session->bps) {
1138 		if(bps != decoder_session->bps) {
1139 			if(decoder_session->got_stream_info)
1140 				flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, bps, decoder_session->bps);
1141 			else
1142 				flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, bps, decoder_session->bps);
1143 			if(!decoder_session->continue_through_decode_errors)
1144 				return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1145 		}
1146 	}
1147 	else {
1148 		/* must not have gotten STREAMINFO, save the bps from the frame header */
1149 		FLAC__ASSERT(!decoder_session->got_stream_info);
1150 		if(decoder_session->format == FORMAT_RAW && ((decoder_session->bps % 8) != 0  || decoder_session->bps < 4)) {
1151 			flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 8/16/24/32 for raw format output\n", decoder_session->inbasefilename, decoder_session->bps);
1152 			return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1153 		}
1154 		decoder_session->bps = bps;
1155 	}
1156 
1157 	/* sanity-check the #channels */
1158 	if(decoder_session->channels) {
1159 		if(channels != decoder_session->channels) {
1160 			if(decoder_session->got_stream_info)
1161 				flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
1162 			else
1163 				flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, channels, decoder_session->channels);
1164 			if(!decoder_session->continue_through_decode_errors)
1165 				return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1166 		}
1167 	}
1168 	else {
1169 		/* must not have gotten STREAMINFO, save the #channels from the frame header */
1170 		FLAC__ASSERT(!decoder_session->got_stream_info);
1171 		decoder_session->channels = channels;
1172 	}
1173 
1174 	/* sanity-check the sample rate */
1175 	if(decoder_session->sample_rate < UINT32_MAX) {
1176 		if(frame->header.sample_rate != decoder_session->sample_rate) {
1177 			if(decoder_session->got_stream_info)
1178 				flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
1179 			else
1180 				flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
1181 			if(!decoder_session->continue_through_decode_errors)
1182 				return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1183 		}
1184 	}
1185 	else {
1186 		/* must not have gotten STREAMINFO, save the sample rate from the frame header */
1187 		FLAC__ASSERT(!decoder_session->got_stream_info);
1188 		decoder_session->sample_rate = frame->header.sample_rate;
1189 	}
1190 
1191 	/*
1192 	 * limit the number of samples to accept based on --until
1193 	 */
1194 	/* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
1195 	if(decoder_session->skip_specification->is_relative || !decoder_session->got_stream_info) {
1196 		if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
1197 			decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
1198 		else {
1199 			flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --skip because the total sample count was not found in the metadata\n", decoder_session->inbasefilename);
1200 			return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1201 		}
1202 	}
1203 	if(decoder_session->until_specification->is_relative || !decoder_session->got_stream_info) {
1204 		if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
1205 			decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
1206 		else {
1207 			flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until because the total sample count was not found in the metadata\n", decoder_session->inbasefilename);
1208 			return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1209 		}
1210 	}
1211 	FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1212 	FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1213 	if(decoder_session->until_specification->value.samples > 0) {
1214 		const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1215 		const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1216 		const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
1217 		FLAC__ASSERT(until >= input_samples_passed);
1218 		if(input_samples_passed + wide_samples > until)
1219 			wide_samples = (uint32_t)(until - input_samples_passed);
1220 		if (wide_samples == 0) {
1221 			decoder_session->abort_flag = true;
1222 			decoder_session->aborting_due_to_until = true;
1223 			return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1224 		}
1225 	}
1226 
1227 	if(decoder_session->analysis_mode) {
1228 		FLAC__uint64 dpos;
1229 		FLAC__stream_decoder_get_decode_position(decoder_session->decoder, &dpos);
1230 		frame_bytes = (dpos-decoder_session->decode_position);
1231 		decoder_session->decode_position = dpos;
1232 	}
1233 
1234 	if(wide_samples > 0) {
1235 		decoder_session->samples_processed += wide_samples;
1236 		decoder_session->frame_counter++;
1237 
1238 #if 0 /* in case time.h with clock() isn't available for some reason */
1239 		if(!(decoder_session->frame_counter & 0x1ff))
1240 			print_stats(decoder_session);
1241 #else
1242 		if((clock() - decoder_session->old_clock_t) > (CLOCKS_PER_SEC/4)) {
1243 			print_stats(decoder_session);
1244 			decoder_session->old_clock_t = clock();
1245 		}
1246 #endif
1247 
1248 
1249 		if(decoder_session->analysis_mode) {
1250 			flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->decode_position-frame_bytes, frame_bytes, decoder_session->aopts, fout);
1251 		}
1252 		else if(!decoder_session->test_only) {
1253 			if(shift && !decoder_session->replaygain.apply) {
1254 				for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1255 					for(channel = 0; channel < channels; channel++)
1256 						((uint32_t **)buffer)[channel][wide_sample] <<= shift;/*@@@@@@un-const'ing the buffer is hacky but safe*/
1257 			}
1258 			if(decoder_session->replaygain.apply) {
1259 				bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
1260 					ubuf.u8buffer,
1261 					!is_big_endian,
1262 					is_unsigned_samples,
1263 					buffer,
1264 					wide_samples,
1265 					channels,
1266 					bps, /* source_bps */
1267 					bps+shift, /* target_bps */
1268 					decoder_session->replaygain.scale,
1269 					decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
1270 					decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
1271 					&decoder_session->replaygain.dither_context
1272 				);
1273 			}
1274 			/* first some special code for common cases */
1275 			else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 2 && bps+shift == 16) {
1276 				FLAC__int16 *buf1_ = ubuf.s16buffer + 1;
1277 				if(is_big_endian)
1278 					memcpy(ubuf.s16buffer, ((FLAC__byte*)(buffer[0]))+2, sizeof(FLAC__int32) * wide_samples - 2);
1279 				else
1280 					memcpy(ubuf.s16buffer, buffer[0], sizeof(FLAC__int32) * wide_samples);
1281 				for(sample = 0; sample < wide_samples; sample++, buf1_+=2)
1282 					*buf1_ = (FLAC__int16)buffer[1][sample];
1283 				bytes_to_write = 4 * sample;
1284 			}
1285 			else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 1 && bps+shift == 16) {
1286 				FLAC__int16 *buf1_ = ubuf.s16buffer;
1287 				for(sample = 0; sample < wide_samples; sample++)
1288 					*buf1_++ = (FLAC__int16)buffer[0][sample];
1289 				bytes_to_write = 2 * sample;
1290 			}
1291 			/* generic code for the rest */
1292 			else if(bps+shift == 16) {
1293 				if(is_unsigned_samples) {
1294 					if(channels == 2) {
1295 						for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1296 							ubuf.u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1297 							ubuf.u16buffer[sample++] = (FLAC__uint16)(buffer[1][wide_sample] + 0x8000);
1298 						}
1299 					}
1300 					else if(channels == 1) {
1301 						for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1302 							ubuf.u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1303 					}
1304 					else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1305 						for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1306 							for(channel = 0; channel < channels; channel++, sample++)
1307 								ubuf.u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
1308 					}
1309 				}
1310 				else {
1311 					if(channels == 2) {
1312 						for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1313 							ubuf.s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1314 							ubuf.s16buffer[sample++] = (FLAC__int16)(buffer[1][wide_sample]);
1315 						}
1316 					}
1317 					else if(channels == 1) {
1318 						for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1319 							ubuf.s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1320 					}
1321 					else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1322 						for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1323 							for(channel = 0; channel < channels; channel++, sample++)
1324 								ubuf.s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
1325 					}
1326 				}
1327 				if(is_big_endian != is_big_endian_host_) {
1328 					uint8_t tmp;
1329 					const uint32_t bytes = sample * 2;
1330 					uint32_t b;
1331 					for(b = 0; b < bytes; b += 2) {
1332 						tmp = ubuf.u8buffer[b];
1333 						ubuf.u8buffer[b] = ubuf.u8buffer[b+1];
1334 						ubuf.u8buffer[b+1] = tmp;
1335 					}
1336 				}
1337 				bytes_to_write = 2 * sample;
1338 			}
1339 			else if(bps+shift == 24) {
1340 				if(is_unsigned_samples) {
1341 					for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1342 						for(channel = 0; channel < channels; channel++, sample++)
1343 							ubuf.u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
1344 				}
1345 				else {
1346 					for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1347 						for(channel = 0; channel < channels; channel++, sample++)
1348 							ubuf.s32buffer[sample] = buffer[channel][wide_sample];
1349 				}
1350 				if(is_big_endian != is_big_endian_host_) {
1351 					uint8_t tmp;
1352 					const uint32_t bytes = sample * 4;
1353 					uint32_t b;
1354 					for(b = 0; b < bytes; b += 4) {
1355 						tmp = ubuf.u8buffer[b];
1356 						ubuf.u8buffer[b] = ubuf.u8buffer[b+3];
1357 						ubuf.u8buffer[b+3] = tmp;
1358 						tmp = ubuf.u8buffer[b+1];
1359 						ubuf.u8buffer[b+1] = ubuf.u8buffer[b+2];
1360 						ubuf.u8buffer[b+2] = tmp;
1361 					}
1362 				}
1363 				if(is_big_endian) {
1364 					uint32_t b, lbyte;
1365 					const uint32_t bytes = sample * 4;
1366 					for(lbyte = b = 0; b < bytes; ) {
1367 						b++;
1368 						ubuf.u8buffer[lbyte++] = ubuf.u8buffer[b++];
1369 						ubuf.u8buffer[lbyte++] = ubuf.u8buffer[b++];
1370 						ubuf.u8buffer[lbyte++] = ubuf.u8buffer[b++];
1371 					}
1372 				}
1373 				else {
1374 					uint32_t b, lbyte;
1375 					const uint32_t bytes = sample * 4;
1376 					for(lbyte = b = 0; b < bytes; ) {
1377 						ubuf.u8buffer[lbyte++] = ubuf.u8buffer[b++];
1378 						ubuf.u8buffer[lbyte++] = ubuf.u8buffer[b++];
1379 						ubuf.u8buffer[lbyte++] = ubuf.u8buffer[b++];
1380 						b++;
1381 					}
1382 				}
1383 				bytes_to_write = 3 * sample;
1384 			}
1385 			else if(bps+shift == 8) {
1386 				if(is_unsigned_samples) {
1387 					for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1388 						for(channel = 0; channel < channels; channel++, sample++)
1389 							ubuf.u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
1390 				}
1391 				else {
1392 					for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1393 						for(channel = 0; channel < channels; channel++, sample++)
1394 							ubuf.s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
1395 				}
1396 				bytes_to_write = sample;
1397 			}
1398 			else if(bps+shift == 32) {
1399 				if(is_unsigned_samples) {
1400 					for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1401 						for(channel = 0; channel < channels; channel++, sample++)
1402 							ubuf.u32buffer[sample] = buffer[channel][wide_sample];
1403 				}
1404 				else {
1405 					for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1406 						for(channel = 0; channel < channels; channel++, sample++)
1407 							ubuf.s32buffer[sample] = buffer[channel][wide_sample];
1408 				}
1409 				if(is_big_endian != is_big_endian_host_) {
1410 					uint8_t tmp;
1411 					const uint32_t bytes = sample * 4;
1412 					uint32_t b;
1413 					for(b = 0; b < bytes; b += 4) {
1414 						tmp = ubuf.u8buffer[b];
1415 						ubuf.u8buffer[b] = ubuf.u8buffer[b+3];
1416 						ubuf.u8buffer[b+3] = tmp;
1417 						tmp = ubuf.u8buffer[b+1];
1418 						ubuf.u8buffer[b+1] = ubuf.u8buffer[b+2];
1419 						ubuf.u8buffer[b+2] = tmp;
1420 					}
1421 				}
1422 				bytes_to_write = 4 * sample;
1423 			}
1424 			else {
1425 				FLAC__ASSERT(0);
1426 				/* double protection */
1427 				decoder_session->abort_flag = true;
1428 				return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1429 			}
1430 		}
1431 	}
1432 	if(bytes_to_write > 0) {
1433 		if(flac__utils_fwrite(ubuf.u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
1434 			/* if a pipe closed when writing to stdout, we let it go without an error message */
1435 			if(errno == EPIPE && decoder_session->fout == stdout)
1436 				decoder_session->aborting_due_to_until = true;
1437 			decoder_session->abort_flag = true;
1438 			return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1439 		}
1440 	}
1441 	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1442 }
1443 
metadata_callback(const FLAC__StreamDecoder * decoder,const FLAC__StreamMetadata * metadata,void * client_data)1444 void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1445 {
1446 	DecoderSession *decoder_session = (DecoderSession*)client_data;
1447 
1448 	(void)decoder;
1449 
1450 	if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
1451 		FLAC__uint64 skip, until;
1452 
1453 		if(decoder_session->got_stream_info){
1454 			/* There was already a STREAMINFO received */
1455 			flac__utils_printf(stderr, 1, "%s: ERROR, more than one STREAMINFO found\n", decoder_session->inbasefilename);
1456 			if(!decoder_session->continue_through_decode_errors)
1457 				decoder_session->abort_flag = true;
1458 			return;
1459 		}
1460 
1461 		decoder_session->got_stream_info = true;
1462 		decoder_session->has_md5sum = memcmp(metadata->data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16) != 0;
1463 		decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1464 		decoder_session->channels = metadata->data.stream_info.channels;
1465 		decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1466 
1467 		if(!flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate)) {
1468 			flac__utils_printf(stderr, 1, "%s: ERROR, value of --skip is too large\n", decoder_session->inbasefilename);
1469 			decoder_session->abort_flag = true;
1470 			return;
1471 		}
1472 		FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1473 		skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1474 
1475 		/* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1476 		if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1477 			flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1478 			decoder_session->abort_flag = true;
1479 			return;
1480 		}
1481 		else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1482 			flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1483 			decoder_session->abort_flag = true;
1484 			return;
1485 		}
1486 		FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1487 		decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1488 
1489 		/* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1490 		if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1491 			decoder_session->abort_flag = true;
1492 			return;
1493 		}
1494 		FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1495 		until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1496 
1497 		if(until > 0) {
1498 			FLAC__ASSERT(decoder_session->total_samples != 0);
1499 			FLAC__ASSERT(0 == decoder_session->cue_specification);
1500 			decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1501 		}
1502 
1503 		if(decoder_session->format == FORMAT_RAW && ((decoder_session->bps % 8) != 0  || decoder_session->bps < 4)) {
1504 			flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 8/16/24/32 for raw format output\n", decoder_session->inbasefilename, decoder_session->bps);
1505 			decoder_session->abort_flag = true;
1506 			return;
1507 		}
1508 
1509 		if(decoder_session->bps < 4 || decoder_session->bps > 32) {
1510 			flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 4-32\n", decoder_session->inbasefilename, decoder_session->bps);
1511 			decoder_session->abort_flag = true;
1512 			return;
1513 		}
1514 	}
1515 	else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1516 		/* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1517 		if(decoder_session->total_samples == 0) {
1518 			flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1519 			decoder_session->abort_flag = true;
1520 			return;
1521 		}
1522 
1523 		flac__utils_canonicalize_cue_specification(decoder_session->cue_specification, &metadata->data.cue_sheet, decoder_session->total_samples, decoder_session->skip_specification, decoder_session->until_specification);
1524 
1525 		FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1526 		FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1527 
1528 		FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1529 		FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1530 
1531 		FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1532 		FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1533 		FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1534 		FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1535 
1536 		decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1537 	}
1538 	else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1539 		if (decoder_session->replaygain.spec.apply) {
1540 			double reference, gain, peak;
1541 			if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
1542 				flac__utils_printf(stderr, 1, "%s: WARNING: can't get %s (or even %s) ReplayGain tags\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", decoder_session->replaygain.spec.use_album_gain? "track":"album");
1543 				if(decoder_session->treat_warnings_as_errors) {
1544 					decoder_session->abort_flag = true;
1545 					return;
1546 				}
1547 			}
1548 			else if(decoder_session->bps == 0) {
1549 				flac__utils_printf(stderr, 1, "%s: WARNING: can't apply ReplayGain, bit-per-sample value is invalid\n", decoder_session->inbasefilename);
1550 				if(decoder_session->treat_warnings_as_errors) {
1551 					decoder_session->abort_flag = true;
1552 					return;
1553 				}
1554 			}
1555 			else {
1556 				const char *ls[] = { "no", "peak", "hard" };
1557 				const char *ns[] = { "no", "low", "medium", "high" };
1558 				decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1559 				FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1560 				FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1561 				flac__utils_printf(stderr, 1, "%s: INFO: applying %s ReplayGain (gain=%0.2fdB+preamp=%0.1fdB, %s noise shaping, %s limiting) to output\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", gain, decoder_session->replaygain.spec.preamp, ns[decoder_session->replaygain.spec.noise_shaping], ls[decoder_session->replaygain.spec.limiter]);
1562 				flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1563 				/* don't check if(decoder_session->treat_warnings_as_errors) because the user explicitly asked for it */
1564 			}
1565 		}
1566 		(void)flac__utils_get_channel_mask_tag(metadata, &decoder_session->channel_mask);
1567 	}
1568 	else if(metadata->type == FLAC__METADATA_TYPE_APPLICATION && decoder_session->warn_user_about_foreign_metadata) {
1569 		/* Foreign metadata signalling */
1570 		flac__utils_printf(stderr, 1, "%s: WARNING: found foreign metadata, use --keep-foreign-metadata to restore\n", decoder_session->inbasefilename);
1571 		decoder_session->warn_user_about_foreign_metadata = false;
1572 	}
1573 }
1574 
error_callback(const FLAC__StreamDecoder * decoder,FLAC__StreamDecoderErrorStatus status,void * client_data)1575 void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1576 {
1577 	DecoderSession *decoder_session = (DecoderSession*)client_data;
1578 	(void)decoder;
1579 	if(!decoder_session->error_callback_suppress_messages) {
1580 		stats_print_name(1, decoder_session->inbasefilename);
1581 		flac__utils_printf(stderr, 1, "*** Got error code %d:%s\n", status, FLAC__StreamDecoderErrorStatusString[status]);
1582 	}
1583 	if(!decoder_session->continue_through_decode_errors) {
1584 		/* if we got a sync error while looking for metadata, either it's not a FLAC file (more likely) or the file is corrupted */
1585 		if(
1586 			!decoder_session->error_callback_suppress_messages &&
1587 			status == FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC &&
1588 			FLAC__stream_decoder_get_state(decoder) == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
1589 		) {
1590 			flac__utils_printf(stderr, 1,
1591 				"\n"
1592 				"The input file is either not a FLAC file or is corrupted.  If you are\n"
1593 				"convinced it is a FLAC file, you can rerun the same command and add the\n"
1594 				"-F parameter to try and recover as much as possible from the file.\n"
1595 			);
1596 			decoder_session->error_callback_suppress_messages = true;
1597 		}
1598 		else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1599 			decoder_session->aborting_due_to_unparseable = true;
1600 		decoder_session->abort_flag = true;
1601 	}
1602 }
1603 
print_error_with_init_status(const DecoderSession * d,const char * message,FLAC__StreamDecoderInitStatus init_status)1604 void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
1605 {
1606 	const int ilen = strlen(d->inbasefilename) + 1;
1607 
1608 	flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1609 
1610 	flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
1611 
1612 	/* print out some more info for some errors: */
1613 	if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
1614 		flac__utils_printf(stderr, 1,
1615 			"\n"
1616 #ifdef _WIN32
1617 			"An error occurred opening the input file; it is likely that it does not exist,\n"
1618 			"is not readable or has a filename that exceeds the path length limit.\n"
1619 #else
1620 			"An error occurred opening the input file; it is likely that it does not exist\n"
1621 			"or is not readable.\n"
1622 #endif
1623 		);
1624 	}
1625 }
1626 
print_error_with_state(const DecoderSession * d,const char * message)1627 void print_error_with_state(const DecoderSession *d, const char *message)
1628 {
1629 	const int ilen = strlen(d->inbasefilename) + 1;
1630 
1631 	flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1632 	flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", FLAC__stream_decoder_get_resolved_state_string(d->decoder));
1633 
1634 	/* print out some more info for some errors: */
1635 	if (d->aborting_due_to_unparseable) {
1636 		flac__utils_printf(stderr, 1,
1637 			"\n"
1638 			"The FLAC stream may have been created by a more advanced encoder.  Try\n"
1639 			"  metaflac --show-vendor-tag %s\n"
1640 			"If the version number is greater than %s, this decoder is probably\n"
1641 			"not able to decode the file.  If the version number is not, the file\n"
1642 			"may be corrupted, or you may have found a bug.  In this case please\n"
1643 			"submit a bug report to\n"
1644 			"    https://github.com/xiph/flac/issues\n"
1645 			"Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1646 			d->inbasefilename, FLAC__VERSION_STRING
1647 		);
1648 	}
1649 }
1650 
print_stats(const DecoderSession * decoder_session)1651 void print_stats(const DecoderSession *decoder_session)
1652 {
1653 	if(flac__utils_verbosity_ >= 2) {
1654 		const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1655 
1656 		if(decoder_session->total_samples > 0) {
1657 			if ((uint32_t)floor(progress + 0.5) == 100)
1658 				return;
1659 
1660 			stats_print_name(2, decoder_session->inbasefilename);
1661 			stats_print_info(2, "%s%u%% complete",
1662 				decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1663 				(uint32_t)floor(progress + 0.5)
1664 			);
1665 		}
1666 		else {
1667 			stats_print_name(2, decoder_session->inbasefilename);
1668 			stats_print_info(2, "%s %" PRIu64 " samples",
1669 				decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1670 				decoder_session->samples_processed
1671 			);
1672 		}
1673 	}
1674 }
1675