• 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 <ctype.h>
25 #include <errno.h>
26 #include <locale.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <time.h>
32 
33 #if !defined _MSC_VER && !defined __MINGW32__
34 /* unlink is in stdio.h in VC++ */
35 #include <unistd.h> /* for unlink() */
36 #endif
37 #include "FLAC/all.h"
38 #include "share/alloc.h"
39 #include "share/grabbag.h"
40 #include "share/compat.h"
41 #include "share/endswap.h"
42 #include "share/safe_str.h"
43 #include "analyze.h"
44 #include "decode.h"
45 #include "encode.h"
46 #include "local_string_utils.h" /* for flac__strlcat() and flac__strlcpy() */
47 #include "utils.h"
48 #include "vorbiscomment.h"
49 
50 #if 0
51 /*[JEC] was:#if HAVE_GETOPT_LONG*/
52 /*[JEC] see flac/include/share/getopt.h as to why the change */
53 #  include <getopt.h>
54 #else
55 #  include "share/getopt.h"
56 #endif
57 
58 static int do_it(void);
59 
60 static FLAC__bool init_options(void);
61 static int parse_options(int argc, char *argv[]);
62 static int parse_option(int short_option, const char *long_option, const char *option_argument);
63 static void free_options(void);
64 static void add_compression_setting_bool(compression_setting_type_t type, FLAC__bool value);
65 static void add_compression_setting_string(compression_setting_type_t type, const char *value);
66 static void add_compression_setting_uint32_t(compression_setting_type_t type, uint32_t value);
67 
68 static int usage_error(const char *message, ...);
69 static void short_usage(void);
70 static void show_version(void);
71 static void show_help(void);
72 static void show_explain(void);
73 static void format_mistake(const char *infilename, FileFormat wrong, FileFormat right);
74 
75 static int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_last_file);
76 static int decode_file(const char *infilename);
77 
78 static const char *get_encoded_outfilename(const char *infilename);
79 static const char *get_decoded_outfilename(const char *infilename, const FileFormat format);
80 static const char *get_outfilename(const char *infilename, const char *suffix);
81 
82 static void die(const char *message);
83 static int conditional_fclose(FILE *f);
84 static char *local_strdup(const char *source);
85 
86 /*
87  * share__getopt format struct; note that for long options with no
88  * short option equivalent we just set the 'val' field to 0.
89  */
90 static struct share__option long_options_[] = {
91 	/*
92 	 * general options
93 	 */
94 	{ "help"                             , share__no_argument, 0, 'h' },
95 	{ "explain"                          , share__no_argument, 0, 'H' },
96 	{ "version"                          , share__no_argument, 0, 'v' },
97 	{ "decode"                           , share__no_argument, 0, 'd' },
98 	{ "analyze"                          , share__no_argument, 0, 'a' },
99 	{ "test"                             , share__no_argument, 0, 't' },
100 	{ "stdout"                           , share__no_argument, 0, 'c' },
101 	{ "silent"                           , share__no_argument, 0, 's' },
102 	{ "totally-silent"                   , share__no_argument, 0, 0 },
103 	{ "warnings-as-errors"               , share__no_argument, 0, 'w' },
104 	{ "force"                            , share__no_argument, 0, 'f' },
105 	{ "delete-input-file"                , share__no_argument, 0, 0 },
106 	{ "preserve-modtime"                 , share__no_argument, 0, 0 },
107 	{ "keep-foreign-metadata"            , share__no_argument, 0, 0 },
108 	{ "keep-foreign-metadata-if-present" , share__no_argument, 0, 0 },
109 	{ "output-prefix"                    , share__required_argument, 0, 0 },
110 	{ "output-name"                      , share__required_argument, 0, 'o' },
111 	{ "skip"                             , share__required_argument, 0, 0 },
112 	{ "until"                            , share__required_argument, 0, 0 },
113 	{ "channel-map"                      , share__required_argument, 0, 0 }, /* undocumented */
114 
115 	/*
116 	 * decoding options
117 	 */
118 	{ "decode-through-errors", share__no_argument, 0, 'F' },
119 	{ "cue"                  , share__required_argument, 0, 0 },
120 	{ "apply-replaygain-which-is-not-lossless", share__optional_argument, 0, 0 }, /* undocumented */
121 
122 	/*
123 	 * encoding options
124 	 */
125 	{ "cuesheet"                  , share__required_argument, 0, 0 },
126 	{ "no-cued-seekpoints"        , share__no_argument, 0, 0 },
127 	{ "picture"                   , share__required_argument, 0, 0 },
128 	{ "tag"                       , share__required_argument, 0, 'T' },
129 	{ "tag-from-file"             , share__required_argument, 0, 0 },
130 	{ "compression-level-0"       , share__no_argument, 0, '0' },
131 	{ "compression-level-1"       , share__no_argument, 0, '1' },
132 	{ "compression-level-2"       , share__no_argument, 0, '2' },
133 	{ "compression-level-3"       , share__no_argument, 0, '3' },
134 	{ "compression-level-4"       , share__no_argument, 0, '4' },
135 	{ "compression-level-5"       , share__no_argument, 0, '5' },
136 	{ "compression-level-6"       , share__no_argument, 0, '6' },
137 	{ "compression-level-7"       , share__no_argument, 0, '7' },
138 	{ "compression-level-8"       , share__no_argument, 0, '8' },
139 	{ "compression-level-9"       , share__no_argument, 0, '9' },
140 	{ "best"                      , share__no_argument, 0, '8' },
141 	{ "fast"                      , share__no_argument, 0, '0' },
142 	{ "verify"                    , share__no_argument, 0, 'V' },
143 	{ "force-raw-format"          , share__no_argument, 0, 0 },
144 	{ "force-aiff-format"         , share__no_argument, 0, 0 },
145 	{ "force-rf64-format"         , share__no_argument, 0, 0 },
146 	{ "force-wave64-format"       , share__no_argument, 0, 0 },
147 	{ "force-legacy-wave-format"  , share__no_argument, 0, 0 },
148 	{ "force-extensible-wave-format",share__no_argument,0, 0 },
149 	{ "force-aiff-c-none-format"  , share__no_argument, 0, 0 },
150 	{ "force-aiff-c-sowt-format"  , share__no_argument, 0, 0 },
151 	{ "lax"                       , share__no_argument, 0, 0 },
152 	{ "replay-gain"               , share__no_argument, 0, 0 },
153 	{ "ignore-chunk-sizes"        , share__no_argument, 0, 0 },
154 	{ "sector-align"              , share__no_argument, 0, 0 }, /* DEPRECATED */
155 	{ "seekpoint"                 , share__required_argument, 0, 'S' },
156 	{ "padding"                   , share__required_argument, 0, 'P' },
157 #if FLAC__HAS_OGG
158 	{ "ogg"                       , share__no_argument, 0, 0 },
159 	{ "serial-number"             , share__required_argument, 0, 0 },
160 #endif
161 	{ "blocksize"                 , share__required_argument, 0, 'b' },
162 	{ "exhaustive-model-search"   , share__no_argument, 0, 'e' },
163 	{ "max-lpc-order"             , share__required_argument, 0, 'l' },
164 	{ "apodization"               , share__required_argument, 0, 'A' },
165 	{ "mid-side"                  , share__no_argument, 0, 'm' },
166 	{ "adaptive-mid-side"         , share__no_argument, 0, 'M' },
167 	{ "qlp-coeff-precision-search", share__no_argument, 0, 'p' },
168 	{ "qlp-coeff-precision"       , share__required_argument, 0, 'q' },
169 	{ "rice-partition-order"      , share__required_argument, 0, 'r' },
170 	{ "endian"                    , share__required_argument, 0, 0 },
171 	{ "channels"                  , share__required_argument, 0, 0 },
172 	{ "bps"                       , share__required_argument, 0, 0 },
173 	{ "sample-rate"               , share__required_argument, 0, 0 },
174 	{ "sign"                      , share__required_argument, 0, 0 },
175 	{ "input-size"                , share__required_argument, 0, 0 },
176 	{ "error-on-compression-fail" , share__no_argument, 0, 0 },
177 	{ "limit-min-bitrate"         , share__no_argument, 0, 0 },
178 
179 	/*
180 	 * analysis options
181 	 */
182 	{ "residual-gnuplot", share__no_argument, 0, 0 },
183 	{ "residual-text", share__no_argument, 0, 0 },
184 
185 	/*
186 	 * negatives
187 	 */
188 	{ "no-preserve-modtime"       , share__no_argument, 0, 0 },
189 	{ "no-decode-through-errors"  , share__no_argument, 0, 0 },
190 	{ "no-silent"                 , share__no_argument, 0, 0 },
191 	{ "no-force"                  , share__no_argument, 0, 0 },
192 	{ "no-seektable"              , share__no_argument, 0, 0 },
193 	{ "no-delete-input-file"      , share__no_argument, 0, 0 },
194 	{ "no-keep-foreign-metadata"  , share__no_argument, 0, 0 },
195 	{ "no-replay-gain"            , share__no_argument, 0, 0 },
196 	{ "no-ignore-chunk-sizes"     , share__no_argument, 0, 0 },
197 	{ "no-sector-align"           , share__no_argument, 0, 0 }, /* DEPRECATED */
198 	{ "no-utf8-convert"           , share__no_argument, 0, 0 },
199 	{ "no-lax"                    , share__no_argument, 0, 0 },
200 #if FLAC__HAS_OGG
201 	{ "no-ogg"                    , share__no_argument, 0, 0 },
202 #endif
203 	{ "no-exhaustive-model-search", share__no_argument, 0, 0 },
204 	{ "no-mid-side"               , share__no_argument, 0, 0 },
205 	{ "no-adaptive-mid-side"      , share__no_argument, 0, 0 },
206 	{ "no-qlp-coeff-prec-search"  , share__no_argument, 0, 0 },
207 	{ "no-padding"                , share__no_argument, 0, 0 },
208 	{ "no-verify"                 , share__no_argument, 0, 0 },
209 	{ "no-warnings-as-errors"     , share__no_argument, 0, 0 },
210 	{ "no-residual-gnuplot"       , share__no_argument, 0, 0 },
211 	{ "no-residual-text"          , share__no_argument, 0, 0 },
212 	{ "no-error-on-compression-fail", share__no_argument, 0, 0 },
213 	/*
214 	 * undocumented debugging options for the test suite
215 	 */
216 	{ "disable-constant-subframes", share__no_argument, 0, 0 },
217 	{ "disable-fixed-subframes"   , share__no_argument, 0, 0 },
218 	{ "disable-verbatim-subframes", share__no_argument, 0, 0 },
219 	{ "no-md5-sum"                , share__no_argument, 0, 0 },
220 
221 	{0, 0, 0, 0}
222 };
223 
224 
225 /*
226  * global to hold command-line option values
227  */
228 
229 static struct {
230 	FLAC__bool show_help;
231 	FLAC__bool show_explain;
232 	FLAC__bool show_version;
233 	FLAC__bool mode_decode;
234 	FLAC__bool verify;
235 	FLAC__bool treat_warnings_as_errors;
236 	FLAC__bool force_file_overwrite;
237 	FLAC__bool continue_through_decode_errors;
238 	replaygain_synthesis_spec_t replaygain_synthesis_spec;
239 	FLAC__bool lax;
240 	FLAC__bool test_only;
241 	FLAC__bool analyze;
242 	FLAC__bool use_ogg;
243 	FLAC__bool has_serial_number; /* true iff --serial-number was used */
244 	long serial_number; /* this is the Ogg serial number and is unused for native FLAC */
245 	FLAC__bool force_to_stdout;
246 	FLAC__bool force_raw_format;
247 	FLAC__bool force_aiff_format;
248 	FLAC__bool force_rf64_format;
249 	FLAC__bool force_wave64_format;
250 	FLAC__bool force_legacy_wave_format;
251 	FLAC__bool force_extensible_wave_format;
252 	FLAC__bool force_aiff_c_none_format;
253 	FLAC__bool force_aiff_c_sowt_format;
254 	FLAC__bool delete_input;
255 	FLAC__bool preserve_modtime;
256 	FLAC__bool keep_foreign_metadata;
257 	FLAC__bool keep_foreign_metadata_if_present;
258 	FLAC__bool replay_gain;
259 	FLAC__bool ignore_chunk_sizes;
260 	FLAC__bool sector_align;
261 	FLAC__bool utf8_convert; /* true by default, to convert tag strings from locale to utf-8, false if --no-utf8-convert used */
262 	const char *cmdline_forced_outfilename;
263 	const char *output_prefix;
264 	analysis_options aopts;
265 	int padding; /* -1 => no -P options were given, 0 => -P- was given, else -P value */
266 	size_t num_compression_settings;
267 	compression_setting_t compression_settings[64]; /* bad MAGIC NUMBER but buffer overflow is checked */
268 	const char *skip_specification;
269 	const char *until_specification;
270 	const char *cue_specification;
271 	int format_is_big_endian;
272 	int format_is_unsigned_samples;
273 	int format_channels;
274 	int format_bps;
275 	int format_sample_rate;
276 	FLAC__off_t format_input_size;
277 	char requested_seek_points[5000]; /* bad MAGIC NUMBER but buffer overflow is checked */
278 	int num_requested_seek_points; /* -1 => no -S options were given, 0 => -S- was given */
279 	const char *cuesheet_filename;
280 	FLAC__bool cued_seekpoints;
281 	FLAC__bool channel_map_none; /* --channel-map=none specified, eventually will expand to take actual channel map */
282 	FLAC__bool error_on_compression_fail;
283 	FLAC__bool limit_min_bitrate;
284 
285 	uint32_t num_files;
286 	char **filenames;
287 
288 	FLAC__StreamMetadata *vorbis_comment;
289 	FLAC__StreamMetadata *pictures[64];
290 	uint32_t num_pictures;
291 
292 	struct {
293 		FLAC__bool disable_constant_subframes;
294 		FLAC__bool disable_fixed_subframes;
295 		FLAC__bool disable_verbatim_subframes;
296 		FLAC__bool do_md5;
297 	} debug;
298 } option_values;
299 
300 
301 /*
302  * miscellaneous globals
303  */
304 
305 static FLAC__int32 align_reservoir_0[588], align_reservoir_1[588]; /* for carrying over samples from --sector-align */ /* DEPRECATED */
306 static FLAC__int32 *align_reservoir[2] = { align_reservoir_0, align_reservoir_1 };
307 static uint32_t align_reservoir_samples = 0; /* 0 .. 587 */
308 
309 
310 #ifndef FUZZ_TOOL_FLAC
main(int argc,char * argv[])311 int main(int argc, char *argv[])
312 #else
313 static int main_to_fuzz(int argc, char *argv[])
314 #endif
315 {
316 	int retval = 0;
317 
318 #ifdef __EMX__
319 	_response(&argc, &argv);
320 	_wildcard(&argc, &argv);
321 #endif
322 #ifdef _WIN32
323 	if (get_utf8_argv(&argc, &argv) != 0) {
324 		fprintf(stderr, "ERROR: failed to convert command line parameters to UTF-8\n");
325 		return 1;
326 	}
327 #endif
328 
329 	srand((uint32_t)time(0));
330 #ifdef _WIN32
331 	{
332 		const char *var;
333 		var = getenv("LC_ALL");
334 		if (!var)
335 			var = getenv("LC_NUMERIC");
336 		if (!var)
337 			var = getenv("LANG");
338 		if (!var || strcmp(var, "C") != 0)
339 			setlocale(LC_ALL, "");
340 	}
341 #else
342 	setlocale(LC_ALL, "");
343 #endif
344 	if(!init_options()) {
345 		flac__utils_printf(stderr, 1, "ERROR: allocating memory\n");
346 		retval = 1;
347 	}
348 	else {
349 		if((retval = parse_options(argc, argv)) == 0)
350 			retval = do_it();
351 	}
352 
353 	free_options();
354 
355 	return retval;
356 }
357 
do_it(void)358 int do_it(void)
359 {
360 	int retval = 0;
361 
362 	if(option_values.show_version) {
363 		show_version();
364 		return 0;
365 	}
366 	else if(option_values.show_explain) {
367 		show_explain();
368 		return 0;
369 	}
370 	else if(option_values.show_help) {
371 		show_help();
372 		return 0;
373 	}
374 	else {
375 		if(option_values.num_files == 0) {
376 			if(flac__utils_verbosity_ >= 1)
377 				short_usage();
378 			return 0;
379 		}
380 
381 		/*
382 		 * tweak options; validate the values
383 		 */
384 		if(!option_values.mode_decode) {
385 			if(0 != option_values.cue_specification)
386 				return usage_error("ERROR: --cue is not allowed in test mode\n");
387 		}
388 		else {
389 			if(option_values.test_only) {
390 				if(0 != option_values.skip_specification)
391 					return usage_error("ERROR: --skip is not allowed in test mode\n");
392 				if(0 != option_values.until_specification)
393 					return usage_error("ERROR: --until is not allowed in test mode\n");
394 				if(0 != option_values.cue_specification)
395 					return usage_error("ERROR: --cue is not allowed in test mode\n");
396 				if(0 != option_values.analyze)
397 					return usage_error("ERROR: analysis mode (-a/--analyze) and test mode (-t/--test) cannot be used together\n");
398 			}
399 		}
400 
401 		if(0 != option_values.cue_specification && (0 != option_values.skip_specification || 0 != option_values.until_specification))
402 			return usage_error("ERROR: --cue may not be combined with --skip or --until\n");
403 
404 		if(option_values.format_channels >= 0) {
405 			if(option_values.format_channels == 0 || (uint32_t)option_values.format_channels > FLAC__MAX_CHANNELS)
406 				return usage_error("ERROR: invalid number of channels '%u', must be > 0 and <= %u\n", option_values.format_channels, FLAC__MAX_CHANNELS);
407 		}
408 		if(option_values.format_bps >= 0) {
409 			if(option_values.format_bps != 8 && option_values.format_bps != 16 && option_values.format_bps != 24 && option_values.format_bps != 32)
410 				return usage_error("ERROR: invalid bits per sample '%u' (must be 8/16/24/32)\n", option_values.format_bps);
411 		}
412 		if(option_values.format_sample_rate >= 0) {
413 			if(!FLAC__format_sample_rate_is_valid(option_values.format_sample_rate))
414 				return usage_error("ERROR: invalid sample rate '%u', must be > 0 and <= %u\n", option_values.format_sample_rate, FLAC__MAX_SAMPLE_RATE);
415 		}
416 		if((option_values.force_raw_format?1:0) +
417 		   (option_values.force_aiff_format?1:0) +
418 		   (option_values.force_rf64_format?1:0) +
419 		   (option_values.force_wave64_format?1:0) +
420 		   (option_values.force_legacy_wave_format?1:0) +
421 		   (option_values.force_extensible_wave_format?1:0) +
422 		   (option_values.force_aiff_c_none_format?1:0) +
423 		   (option_values.force_aiff_c_sowt_format?1:0)
424 		    > 1)
425 			return usage_error("ERROR: only one of force format options allowed\n");
426 		if(option_values.mode_decode) {
427 			if(!option_values.force_raw_format) {
428 				if(option_values.format_is_big_endian >= 0)
429 					return usage_error("ERROR: --endian only allowed with --force-raw-format\n");
430 				if(option_values.format_is_unsigned_samples >= 0)
431 					return usage_error("ERROR: --sign only allowed with --force-raw-format\n");
432 			}
433 			if(option_values.format_channels >= 0)
434 				return usage_error("ERROR: --channels not allowed with --decode\n");
435 			if(option_values.format_bps >= 0)
436 				return usage_error("ERROR: --bps not allowed with --decode\n");
437 			if(option_values.format_sample_rate >= 0)
438 				return usage_error("ERROR: --sample-rate not allowed with --decode\n");
439 		}
440 
441 		if(option_values.ignore_chunk_sizes) {
442 			if(option_values.mode_decode)
443 				return usage_error("ERROR: --ignore-chunk-sizes only allowed for encoding\n");
444 			if(0 != option_values.sector_align)
445 				return usage_error("ERROR: --ignore-chunk-sizes not allowed with --sector-align\n");
446 			if(0 != option_values.until_specification)
447 				return usage_error("ERROR: --ignore-chunk-sizes not allowed with --until\n");
448 			if(0 != option_values.cue_specification)
449 				return usage_error("ERROR: --ignore-chunk-sizes not allowed with --cue\n");
450 			if(0 != option_values.cuesheet_filename)
451 				return usage_error("ERROR: --ignore-chunk-sizes not allowed with --cuesheet\n");
452 		}
453 		if(option_values.sector_align) {
454 			if(option_values.mode_decode)
455 				return usage_error("ERROR: --sector-align only allowed for encoding\n");
456 			if(0 != option_values.skip_specification)
457 				return usage_error("ERROR: --sector-align not allowed with --skip\n");
458 			if(0 != option_values.until_specification)
459 				return usage_error("ERROR: --sector-align not allowed with --until\n");
460 			if(0 != option_values.cue_specification)
461 				return usage_error("ERROR: --sector-align not allowed with --cue\n");
462 			if(option_values.format_channels >= 0 && option_values.format_channels != 2)
463 				return usage_error("ERROR: --sector-align can only be done with stereo input\n");
464 			if(option_values.format_bps >= 0 && option_values.format_bps != 16)
465 				return usage_error("ERROR: --sector-align can only be done with 16-bit samples\n");
466 			if(option_values.format_sample_rate >= 0 && option_values.format_sample_rate != 44100)
467 				return usage_error("ERROR: --sector-align can only be done with a sample rate of 44100\n");
468 		}
469 		if(option_values.replay_gain) {
470 			if(option_values.force_to_stdout)
471 				return usage_error("ERROR: --replay-gain not allowed with -c/--stdout\n");
472 			if(option_values.mode_decode)
473 				return usage_error("ERROR: --replay-gain only allowed for encoding\n");
474 			if(option_values.format_channels > 2)
475 				return usage_error("ERROR: --replay-gain can only be done with mono/stereo input\n");
476 			if(option_values.format_sample_rate >= 0 && !grabbag__replaygain_is_valid_sample_frequency(option_values.format_sample_rate))
477 				return usage_error("ERROR: invalid sample rate used with --replay-gain\n");
478 			if(
479 				(option_values.padding >= 0 && option_values.padding < (int)GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED) ||
480 				(option_values.padding < 0 && FLAC_ENCODE__DEFAULT_PADDING < (int)GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED)
481 			) {
482 				flac__utils_printf(stderr, 1, "NOTE: --replay-gain may leave a small PADDING block even with --no-padding\n");
483 			}
484 		}
485 		if(option_values.num_files > 1 && option_values.cmdline_forced_outfilename) {
486 			return usage_error("ERROR: -o/--output-name cannot be used with multiple files\n");
487 		}
488 		if(option_values.cmdline_forced_outfilename && option_values.output_prefix) {
489 			return usage_error("ERROR: --output-prefix conflicts with -o/--output-name\n");
490 		}
491 		if(!option_values.mode_decode && 0 != option_values.cuesheet_filename && option_values.num_files > 1) {
492 			return usage_error("ERROR: --cuesheet cannot be used when encoding multiple files\n");
493 		}
494 		if(option_values.keep_foreign_metadata || option_values.keep_foreign_metadata_if_present) {
495 			/* we're not going to try and support the re-creation of broken WAVE files */
496 			if(option_values.ignore_chunk_sizes)
497 				return usage_error("ERROR: using --keep-foreign-metadata cannot be used with --ignore-chunk-sizes\n");
498 			if(option_values.test_only)
499 				return usage_error("ERROR: --keep-foreign-metadata is not allowed in test mode\n");
500 			if(option_values.analyze)
501 				return usage_error("ERROR: --keep-foreign-metadata is not allowed in analyis mode\n");
502 			flac__utils_printf(stderr, 1, "NOTE: --keep-foreign-metadata is a new feature; make sure to test the output file before deleting the original.\n");
503 		}
504 	}
505 
506 	flac__utils_printf(stderr, 2, "\n");
507 	flac__utils_printf(stderr, 2, "flac %s\n", FLAC__VERSION_STRING);
508 	flac__utils_printf(stderr, 2, "Copyright (C) 2000-2009  Josh Coalson, 2011-2022  Xiph.Org Foundation\n");
509 	flac__utils_printf(stderr, 2, "flac comes with ABSOLUTELY NO WARRANTY.  This is free software, and you are\n");
510 	flac__utils_printf(stderr, 2, "welcome to redistribute it under certain conditions.  Type `flac' for details.\n\n");
511 
512 	if(option_values.mode_decode) {
513 		FLAC__bool first = true;
514 
515 		if(option_values.num_files == 0) {
516 			retval = decode_file("-");
517 		}
518 		else {
519 			uint32_t i;
520 			if(option_values.num_files > 1)
521 				option_values.cmdline_forced_outfilename = 0;
522 			for(i = 0, retval = 0; i < option_values.num_files; i++) {
523 				if(0 == strcmp(option_values.filenames[i], "-") && !first)
524 					continue;
525 				retval |= decode_file(option_values.filenames[i]);
526 				first = false;
527 			}
528 		}
529 	}
530 	else { /* encode */
531 		FLAC__bool first = true;
532 
533 		if(option_values.ignore_chunk_sizes)
534 			flac__utils_printf(stderr, 1, "INFO: Make sure you know what you're doing when using --ignore-chunk-sizes.\n      Improper use can cause flac to encode non-audio data as audio.\n");
535 
536 		if(option_values.num_files == 0) {
537 			retval = encode_file("-", first, true);
538 		}
539 		else {
540 			uint32_t i;
541 			if(option_values.num_files > 1)
542 				option_values.cmdline_forced_outfilename = 0;
543 			for(i = 0, retval = 0; i < option_values.num_files; i++) {
544 				if(0 == strcmp(option_values.filenames[i], "-") && !first)
545 					continue;
546 				retval |= encode_file(option_values.filenames[i], first, i == (option_values.num_files-1));
547 				first = false;
548 			}
549 			if(option_values.replay_gain && retval == 0) {
550 				float album_gain, album_peak;
551 				grabbag__replaygain_get_album(&album_gain, &album_peak);
552 				for(i = 0; i < option_values.num_files; i++) {
553 					const char *error, *outfilename = get_encoded_outfilename(option_values.filenames[i]);
554 					if(0 == outfilename) {
555 						flac__utils_printf(stderr, 1, "ERROR: filename too long: %s", option_values.filenames[i]);
556 						return 1;
557 					}
558 					if(0 != (error = grabbag__replaygain_store_to_file_album(outfilename, album_gain, album_peak, option_values.preserve_modtime))) {
559 						flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain album tags (%s)\n", outfilename, error);
560 						retval = 1;
561 					}
562 				}
563 			}
564 		}
565 	}
566 
567 	return retval;
568 }
569 
init_options(void)570 FLAC__bool init_options(void)
571 {
572 	option_values.show_help = false;
573 	option_values.show_explain = false;
574 	option_values.mode_decode = false;
575 	option_values.verify = false;
576 	option_values.treat_warnings_as_errors = false;
577 	option_values.force_file_overwrite = false;
578 	option_values.continue_through_decode_errors = false;
579 	option_values.replaygain_synthesis_spec.apply = false;
580 	option_values.replaygain_synthesis_spec.use_album_gain = true;
581 	option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__HARD;
582 	option_values.replaygain_synthesis_spec.noise_shaping = NOISE_SHAPING_LOW;
583 	option_values.replaygain_synthesis_spec.preamp = 0.0;
584 	option_values.lax = false;
585 	option_values.test_only = false;
586 	option_values.analyze = false;
587 	option_values.use_ogg = false;
588 	option_values.has_serial_number = false;
589 	option_values.serial_number = 0;
590 	option_values.force_to_stdout = false;
591 	option_values.force_raw_format = false;
592 	option_values.force_aiff_format = false;
593 	option_values.force_rf64_format = false;
594 	option_values.force_wave64_format = false;
595 	option_values.force_legacy_wave_format = false;
596 	option_values.force_extensible_wave_format = false;
597 	option_values.force_aiff_c_none_format = false;
598 	option_values.force_aiff_c_sowt_format = false;
599 	option_values.delete_input = false;
600 	option_values.preserve_modtime = true;
601 	option_values.keep_foreign_metadata = false;
602 	option_values.keep_foreign_metadata_if_present = false;
603 	option_values.replay_gain = false;
604 	option_values.ignore_chunk_sizes = false;
605 	option_values.sector_align = false;
606 	option_values.utf8_convert = true;
607 	option_values.cmdline_forced_outfilename = 0;
608 	option_values.output_prefix = 0;
609 	option_values.aopts.do_residual_text = false;
610 	option_values.aopts.do_residual_gnuplot = false;
611 	option_values.padding = -1;
612 	option_values.num_compression_settings = 1;
613 	option_values.compression_settings[0].type = CST_COMPRESSION_LEVEL;
614 	option_values.compression_settings[0].value.t_unsigned = 5;
615 	option_values.skip_specification = 0;
616 	option_values.until_specification = 0;
617 	option_values.cue_specification = 0;
618 	option_values.format_is_big_endian = -1;
619 	option_values.format_is_unsigned_samples = -1;
620 	option_values.format_channels = -1;
621 	option_values.format_bps = -1;
622 	option_values.format_sample_rate = -1;
623 	option_values.format_input_size = (FLAC__off_t)(-1);
624 	option_values.requested_seek_points[0] = '\0';
625 	option_values.num_requested_seek_points = -1;
626 	option_values.cuesheet_filename = 0;
627 	option_values.cued_seekpoints = true;
628 	option_values.channel_map_none = false;
629 	option_values.error_on_compression_fail = false;
630 	option_values.limit_min_bitrate = false;
631 
632 	option_values.num_files = 0;
633 	option_values.filenames = 0;
634 
635 	if(0 == (option_values.vorbis_comment = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT)))
636 		return false;
637 	option_values.num_pictures = 0;
638 
639 	option_values.debug.disable_constant_subframes = false;
640 	option_values.debug.disable_fixed_subframes = false;
641 	option_values.debug.disable_verbatim_subframes = false;
642 	option_values.debug.do_md5 = true;
643 
644 	return true;
645 }
646 
parse_options(int argc,char * argv[])647 int parse_options(int argc, char *argv[])
648 {
649 	int short_option;
650 	int option_index = 1;
651 	FLAC__bool had_error = false;
652 	const char *short_opts = "0123456789aA:b:cdefFhHl:mMo:pP:q:r:sS:tT:vVw";
653 
654 	while ((short_option = share__getopt_long(argc, argv, short_opts, long_options_, &option_index)) != -1) {
655 		switch (short_option) {
656 			case 0: /* long option with no equivalent short option */
657 				had_error |= (parse_option(short_option, long_options_[option_index].name, share__optarg) != 0);
658 				break;
659 			case '?':
660 			case ':':
661 				had_error = true;
662 				break;
663 			default: /* short option */
664 				had_error |= (parse_option(short_option, 0, share__optarg) != 0);
665 				break;
666 		}
667 	}
668 
669 	if(had_error) {
670 		return 1;
671 	}
672 
673 	FLAC__ASSERT(share__optind <= argc);
674 
675 	option_values.num_files = argc - share__optind;
676 
677 	if(option_values.num_files > 0) {
678 		uint32_t i = 0;
679 		if(0 == (option_values.filenames = malloc(sizeof(char*) * option_values.num_files)))
680 			die("out of memory allocating space for file names list");
681 		while(share__optind < argc)
682 			option_values.filenames[i++] = local_strdup(argv[share__optind++]);
683 	}
684 
685 	return 0;
686 }
687 
parse_option(int short_option,const char * long_option,const char * option_argument)688 int parse_option(int short_option, const char *long_option, const char *option_argument)
689 {
690 	const char *violation;
691 
692 	if(short_option == 0) {
693 		FLAC__ASSERT(0 != long_option);
694 		if(0 == strcmp(long_option, "totally-silent")) {
695 			flac__utils_verbosity_ = 0;
696 		}
697 		else if(0 == strcmp(long_option, "delete-input-file")) {
698 			option_values.delete_input = true;
699 		}
700 		else if(0 == strcmp(long_option, "preserve-modtime")) {
701 			option_values.preserve_modtime = true;
702 		}
703 		else if(0 == strcmp(long_option, "keep-foreign-metadata")) {
704 			option_values.keep_foreign_metadata = true;
705 		}
706 		else if(0 == strcmp(long_option, "keep-foreign-metadata-if-present")) {
707 			option_values.keep_foreign_metadata_if_present = true;
708 		}
709 		else if(0 == strcmp(long_option, "output-prefix")) {
710 			FLAC__ASSERT(0 != option_argument);
711 			option_values.output_prefix = option_argument;
712 		}
713 		else if(0 == strcmp(long_option, "skip")) {
714 			FLAC__ASSERT(0 != option_argument);
715 			option_values.skip_specification = option_argument;
716 		}
717 		else if(0 == strcmp(long_option, "until")) {
718 			FLAC__ASSERT(0 != option_argument);
719 			option_values.until_specification = option_argument;
720 		}
721 		else if(0 == strcmp(long_option, "input-size")) {
722 			FLAC__ASSERT(0 != option_argument);
723 			{
724 				char *end;
725 				FLAC__int64 ix;
726 				ix = strtoll(option_argument, &end, 10);
727 				if(0 == strlen(option_argument) || *end)
728 					return usage_error("ERROR: --%s must be a number\n", long_option);
729 				option_values.format_input_size = (FLAC__off_t)ix;
730 				if(option_values.format_input_size != ix) /* check if FLAC__off_t is smaller than long long */
731 					return usage_error("ERROR: --%s too large; this build of flac does not support filesizes over 2GB\n", long_option);
732 				if(option_values.format_input_size <= 0)
733 					return usage_error("ERROR: --%s must be > 0\n", long_option);
734 			}
735 		}
736 		else if(0 == strcmp(long_option, "cue")) {
737 			FLAC__ASSERT(0 != option_argument);
738 			option_values.cue_specification = option_argument;
739 		}
740 		else if(0 == strcmp(long_option, "apply-replaygain-which-is-not-lossless")) {
741 			option_values.replaygain_synthesis_spec.apply = true;
742 			if (0 != option_argument) {
743 				char *p;
744 				option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__NONE;
745 				option_values.replaygain_synthesis_spec.noise_shaping = NOISE_SHAPING_NONE;
746 				option_values.replaygain_synthesis_spec.preamp = strtod(option_argument, &p);
747 				for ( ; *p; p++) {
748 					if (*p == 'a')
749 						option_values.replaygain_synthesis_spec.use_album_gain = true;
750 					else if (*p == 't')
751 						option_values.replaygain_synthesis_spec.use_album_gain = false;
752 					else if (*p == 'l')
753 						option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__PEAK;
754 					else if (*p == 'L')
755 						option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__HARD;
756 					else if (*p == 'n' && p[1] >= '0' && p[1] <= '3') {
757 						option_values.replaygain_synthesis_spec.noise_shaping = p[1] - '0';
758 						p++;
759 					}
760 					else
761 						return usage_error("ERROR: bad specification string \"%s\" for --%s\n", option_argument, long_option);
762 				}
763 			}
764 		}
765 		else if(0 == strcmp(long_option, "channel-map")) {
766 			if (0 == option_argument || strcmp(option_argument, "none"))
767 				return usage_error("ERROR: only --channel-map=none currently supported\n");
768 			option_values.channel_map_none = true;
769 		}
770 		else if(0 == strcmp(long_option, "cuesheet")) {
771 			FLAC__ASSERT(0 != option_argument);
772 			option_values.cuesheet_filename = option_argument;
773 		}
774 		else if(0 == strcmp(long_option, "picture")) {
775 			const uint32_t max_pictures = sizeof(option_values.pictures)/sizeof(option_values.pictures[0]);
776 			FLAC__ASSERT(0 != option_argument);
777 			if(option_values.num_pictures >= max_pictures)
778 				return usage_error("ERROR: too many --picture arguments, only %u allowed\n", max_pictures);
779 			if(0 == (option_values.pictures[option_values.num_pictures] = grabbag__picture_parse_specification(option_argument, &violation)))
780 				return usage_error("ERROR: (--picture) %s\n", violation);
781 			option_values.num_pictures++;
782 		}
783 		else if(0 == strcmp(long_option, "tag-from-file")) {
784 			FLAC__ASSERT(0 != option_argument);
785 			if(!flac__vorbiscomment_add(option_values.vorbis_comment, option_argument, /*value_from_file=*/true, /*raw=*/!option_values.utf8_convert, &violation))
786 				return usage_error("ERROR: (--tag-from-file) %s\n", violation);
787 		}
788 		else if(0 == strcmp(long_option, "no-cued-seekpoints")) {
789 			option_values.cued_seekpoints = false;
790 		}
791 		else if(0 == strcmp(long_option, "force-raw-format")) {
792 			option_values.force_raw_format = true;
793 		}
794 		else if(0 == strcmp(long_option, "force-aiff-format")) {
795 			option_values.force_aiff_format = true;
796 		}
797 		else if(0 == strcmp(long_option, "force-rf64-format")) {
798 			option_values.force_rf64_format = true;
799 		}
800 		else if(0 == strcmp(long_option, "force-wave64-format")) {
801 			option_values.force_wave64_format = true;
802 		}
803 		else if(0 == strcmp(long_option, "force-legacy-wave-format")) {
804 			option_values.force_legacy_wave_format = true;
805 		}
806 		else if(0 == strcmp(long_option, "force-extensible-wave-format")) {
807 			option_values.force_extensible_wave_format = true;
808 		}
809 		else if(0 == strcmp(long_option, "force-aiff-c-none-format")) {
810 			option_values.force_aiff_c_none_format = true;
811 		}
812 		else if(0 == strcmp(long_option, "force-aiff-c-sowt-format")) {
813 			option_values.force_aiff_c_sowt_format = true;
814 		}
815 		else if(0 == strcmp(long_option, "lax")) {
816 			option_values.lax = true;
817 		}
818 		else if(0 == strcmp(long_option, "replay-gain")) {
819 			option_values.replay_gain = true;
820 		}
821 		else if(0 == strcmp(long_option, "ignore-chunk-sizes")) {
822 			option_values.ignore_chunk_sizes = true;
823 		}
824 		else if(0 == strcmp(long_option, "sector-align")) {
825 			flac__utils_printf(stderr, 1, "WARNING: --sector-align is DEPRECATED and may not exist in future versions of flac.\n");
826 			flac__utils_printf(stderr, 1, "         shntool provides similar functionality\n");
827 			option_values.sector_align = true;
828 		}
829 #if FLAC__HAS_OGG
830 		else if(0 == strcmp(long_option, "ogg")) {
831 			option_values.use_ogg = true;
832 		}
833 		else if(0 == strcmp(long_option, "serial-number")) {
834 			option_values.has_serial_number = true;
835 			option_values.serial_number = atol(option_argument);
836 		}
837 #endif
838 		else if(0 == strcmp(long_option, "endian")) {
839 			FLAC__ASSERT(0 != option_argument);
840 			if(0 == strncmp(option_argument, "big", strlen(option_argument)))
841 				option_values.format_is_big_endian = true;
842 			else if(0 == strncmp(option_argument, "little", strlen(option_argument)))
843 				option_values.format_is_big_endian = false;
844 			else
845 				return usage_error("ERROR: argument to --endian must be \"big\" or \"little\"\n");
846 		}
847 		else if(0 == strcmp(long_option, "channels")) {
848 			FLAC__ASSERT(0 != option_argument);
849 			option_values.format_channels = atoi(option_argument);
850 		}
851 		else if(0 == strcmp(long_option, "bps")) {
852 			FLAC__ASSERT(0 != option_argument);
853 			option_values.format_bps = atoi(option_argument);
854 		}
855 		else if(0 == strcmp(long_option, "sample-rate")) {
856 			FLAC__ASSERT(0 != option_argument);
857 			option_values.format_sample_rate = atoi(option_argument);
858 		}
859 		else if(0 == strcmp(long_option, "sign")) {
860 			FLAC__ASSERT(0 != option_argument);
861 			if(0 == strncmp(option_argument, "signed", strlen(option_argument)))
862 				option_values.format_is_unsigned_samples = false;
863 			else if(0 == strncmp(option_argument, "unsigned", strlen(option_argument)))
864 				option_values.format_is_unsigned_samples = true;
865 			else
866 				return usage_error("ERROR: argument to --sign must be \"signed\" or \"unsigned\"\n");
867 		}
868 		else if(0 == strcmp(long_option, "residual-gnuplot")) {
869 			option_values.aopts.do_residual_gnuplot = true;
870 		}
871 		else if(0 == strcmp(long_option, "residual-text")) {
872 			option_values.aopts.do_residual_text = true;
873 		}
874 		else if(0 == strcmp(long_option, "limit-min-bitrate")) {
875 			option_values.limit_min_bitrate = true;
876 		}
877 		/*
878 		 * negatives
879 		 */
880 		else if(0 == strcmp(long_option, "no-preserve-modtime")) {
881 			option_values.preserve_modtime = false;
882 		}
883 		else if(0 == strcmp(long_option, "no-decode-through-errors")) {
884 			option_values.continue_through_decode_errors = false;
885 		}
886 		else if(0 == strcmp(long_option, "no-silent")) {
887 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
888 			flac__utils_verbosity_ = 2;
889 #endif
890 		}
891 		else if(0 == strcmp(long_option, "no-force")) {
892 			option_values.force_file_overwrite = false;
893 		}
894 		else if(0 == strcmp(long_option, "no-seektable")) {
895 			option_values.num_requested_seek_points = 0;
896 			option_values.requested_seek_points[0] = '\0';
897 		}
898 		else if(0 == strcmp(long_option, "no-delete-input-file")) {
899 			option_values.delete_input = false;
900 		}
901 		else if(0 == strcmp(long_option, "no-keep-foreign-metadata")) {
902 			option_values.keep_foreign_metadata = false;
903 			option_values.keep_foreign_metadata_if_present = false;
904 		}
905 		else if(0 == strcmp(long_option, "no-replay-gain")) {
906 			option_values.replay_gain = false;
907 		}
908 		else if(0 == strcmp(long_option, "no-ignore-chunk-sizes")) {
909 			option_values.ignore_chunk_sizes = false;
910 		}
911 		else if(0 == strcmp(long_option, "no-sector-align")) {
912 			option_values.sector_align = false;
913 		}
914 		else if(0 == strcmp(long_option, "no-utf8-convert")) {
915 			option_values.utf8_convert = false;
916 		}
917 		else if(0 == strcmp(long_option, "no-lax")) {
918 			option_values.lax = false;
919 		}
920 #if FLAC__HAS_OGG
921 		else if(0 == strcmp(long_option, "no-ogg")) {
922 			option_values.use_ogg = false;
923 		}
924 #endif
925 		else if(0 == strcmp(long_option, "no-exhaustive-model-search")) {
926 			add_compression_setting_bool(CST_DO_EXHAUSTIVE_MODEL_SEARCH, false);
927 		}
928 		else if(0 == strcmp(long_option, "no-mid-side")) {
929 			add_compression_setting_bool(CST_DO_MID_SIDE, false);
930 			add_compression_setting_bool(CST_LOOSE_MID_SIDE, false);
931 		}
932 		else if(0 == strcmp(long_option, "no-adaptive-mid-side")) {
933 			add_compression_setting_bool(CST_DO_MID_SIDE, false);
934 			add_compression_setting_bool(CST_LOOSE_MID_SIDE, false);
935 		}
936 		else if(0 == strcmp(long_option, "no-qlp-coeff-prec-search")) {
937 			add_compression_setting_bool(CST_DO_QLP_COEFF_PREC_SEARCH, false);
938 		}
939 		else if(0 == strcmp(long_option, "no-padding")) {
940 			option_values.padding = 0;
941 		}
942 		else if(0 == strcmp(long_option, "no-verify")) {
943 			option_values.verify = false;
944 		}
945 		else if(0 == strcmp(long_option, "no-warnings-as-errors")) {
946 			option_values.treat_warnings_as_errors = false;
947 		}
948 		else if(0 == strcmp(long_option, "no-residual-gnuplot")) {
949 			option_values.aopts.do_residual_gnuplot = false;
950 		}
951 		else if(0 == strcmp(long_option, "no-residual-text")) {
952 			option_values.aopts.do_residual_text = false;
953 		}
954 		else if(0 == strcmp(long_option, "disable-constant-subframes")) {
955 			option_values.debug.disable_constant_subframes = true;
956 		}
957 		else if(0 == strcmp(long_option, "disable-fixed-subframes")) {
958 			option_values.debug.disable_fixed_subframes = true;
959 		}
960 		else if(0 == strcmp(long_option, "disable-verbatim-subframes")) {
961 			option_values.debug.disable_verbatim_subframes = true;
962 		}
963 		else if(0 == strcmp(long_option, "no-md5-sum")) {
964 			option_values.debug.do_md5 = false;
965 		}
966 		else if(0 == strcmp(long_option, "no-error-on-compression-fail")) {
967 			option_values.error_on_compression_fail = false;
968 		}
969 		else if(0 == strcmp(long_option, "error-on-compression-fail")) {
970 			option_values.error_on_compression_fail = true;
971 		}
972 	}
973 	else {
974 		switch(short_option) {
975 			case 'h':
976 				option_values.show_help = true;
977 				break;
978 			case 'H':
979 				option_values.show_explain = true;
980 				break;
981 			case 'v':
982 				option_values.show_version = true;
983 				break;
984 			case 'd':
985 				option_values.mode_decode = true;
986 				break;
987 			case 'a':
988 				option_values.mode_decode = true;
989 				option_values.analyze = true;
990 				break;
991 			case 't':
992 				option_values.mode_decode = true;
993 				option_values.test_only = true;
994 				break;
995 			case 'c':
996 				option_values.force_to_stdout = true;
997 				break;
998 			case 's':
999 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1000 				flac__utils_verbosity_ = 1;
1001 #endif
1002 				break;
1003 			case 'f':
1004 				option_values.force_file_overwrite = true;
1005 				break;
1006 			case 'o':
1007 				FLAC__ASSERT(0 != option_argument);
1008 				option_values.cmdline_forced_outfilename = option_argument;
1009 				break;
1010 			case 'F':
1011 				option_values.continue_through_decode_errors = true;
1012 				break;
1013 			case 'T':
1014 				FLAC__ASSERT(0 != option_argument);
1015 				if(!flac__vorbiscomment_add(option_values.vorbis_comment, option_argument, /*value_from_file=*/false, /*raw=*/!option_values.utf8_convert, &violation))
1016 					return usage_error("ERROR: (-T/--tag) %s\n", violation);
1017 				break;
1018 			case '0':
1019 			case '1':
1020 			case '2':
1021 			case '3':
1022 			case '4':
1023 			case '5':
1024 			case '6':
1025 			case '7':
1026 			case '8':
1027 				add_compression_setting_uint32_t(CST_COMPRESSION_LEVEL, short_option-'0');
1028 				break;
1029 			case '9':
1030 				return usage_error("ERROR: compression level '9' is reserved\n");
1031 			case 'V':
1032 				option_values.verify = true;
1033 				break;
1034 			case 'w':
1035 				option_values.treat_warnings_as_errors = true;
1036 				break;
1037 			case 'S':
1038 				FLAC__ASSERT(0 != option_argument);
1039 				if(0 == strcmp(option_argument, "-")) {
1040 					option_values.num_requested_seek_points = 0;
1041 					option_values.requested_seek_points[0] = '\0';
1042 				}
1043 				else {
1044 					if(option_values.num_requested_seek_points < 0)
1045 						option_values.num_requested_seek_points = 0;
1046 					option_values.num_requested_seek_points++;
1047 					if(strlen(option_values.requested_seek_points)+strlen(option_argument)+2 >= sizeof(option_values.requested_seek_points)) {
1048 						return usage_error("ERROR: too many seekpoints requested\n");
1049 					}
1050 					else {
1051 						size_t len = strlen(option_values.requested_seek_points);
1052 						flac_snprintf(option_values.requested_seek_points+len, sizeof(option_values.requested_seek_points) - len, "%s;", option_argument);
1053 					}
1054 				}
1055 				break;
1056 			case 'P':
1057 				FLAC__ASSERT(0 != option_argument);
1058 				option_values.padding = atoi(option_argument);
1059 				if(option_values.padding < 0)
1060 					return usage_error("ERROR: argument to -%c must be >= 0; for no padding use -%c-\n", short_option, short_option);
1061 				break;
1062 			case 'b':
1063 				{
1064 					uint32_t i ;
1065 					FLAC__ASSERT(0 != option_argument);
1066 					i = atoi(option_argument);
1067 					if((i < (int)FLAC__MIN_BLOCK_SIZE || i > (int)FLAC__MAX_BLOCK_SIZE))
1068 						return usage_error("ERROR: invalid blocksize (-%c) '%d', must be >= %u and <= %u\n", short_option, i, FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE);
1069 					add_compression_setting_uint32_t(CST_BLOCKSIZE, (uint32_t)i);
1070 				}
1071 				break;
1072 			case 'e':
1073 				add_compression_setting_bool(CST_DO_EXHAUSTIVE_MODEL_SEARCH, true);
1074 				break;
1075 			case 'E':
1076 				add_compression_setting_bool(CST_DO_ESCAPE_CODING, true);
1077 				break;
1078 			case 'l':
1079 				{
1080 					uint32_t i ;
1081 					FLAC__ASSERT(0 != option_argument);
1082 					i = atoi(option_argument);
1083 					if(i > FLAC__MAX_LPC_ORDER)
1084 						return usage_error("ERROR: invalid LPC order (-%c) '%d', must be >= %u and <= %u\n", short_option, i, 0, FLAC__MAX_LPC_ORDER);
1085 					add_compression_setting_uint32_t(CST_MAX_LPC_ORDER, i);
1086 				}
1087 				break;
1088 			case 'A':
1089 				FLAC__ASSERT(0 != option_argument);
1090 				add_compression_setting_string(CST_APODIZATION, option_argument);
1091 				break;
1092 			case 'm':
1093 				add_compression_setting_bool(CST_DO_MID_SIDE, true);
1094 				add_compression_setting_bool(CST_LOOSE_MID_SIDE, false);
1095 				break;
1096 			case 'M':
1097 				add_compression_setting_bool(CST_DO_MID_SIDE, true);
1098 				add_compression_setting_bool(CST_LOOSE_MID_SIDE, true);
1099 				break;
1100 			case 'p':
1101 				add_compression_setting_bool(CST_DO_QLP_COEFF_PREC_SEARCH, true);
1102 				break;
1103 			case 'q':
1104 				{
1105 					uint32_t i ;
1106 					FLAC__ASSERT(0 != option_argument);
1107 					i = atoi(option_argument);
1108 					if((i > 0 && (i < FLAC__MIN_QLP_COEFF_PRECISION || i > FLAC__MAX_QLP_COEFF_PRECISION)))
1109 						return usage_error("ERROR: invalid value '%d' for qlp coeff precision (-%c), must be 0 or between %u and %u, inclusive\n", i, short_option, FLAC__MIN_QLP_COEFF_PRECISION, FLAC__MAX_QLP_COEFF_PRECISION);
1110 					add_compression_setting_uint32_t(CST_QLP_COEFF_PRECISION, i);
1111 				}
1112 				break;
1113 			case 'r':
1114 				{
1115 					uint32_t i;
1116 					char * p;
1117 					FLAC__ASSERT(0 != option_argument);
1118 					p = strchr(option_argument, ',');
1119 					if(0 == p) {
1120 						add_compression_setting_uint32_t(CST_MIN_RESIDUAL_PARTITION_ORDER, 0);
1121 						i = atoi(option_argument);
1122 						if(i > FLAC__MAX_RICE_PARTITION_ORDER)
1123 							return usage_error("ERROR: invalid value '%d' for residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER);
1124 						add_compression_setting_uint32_t(CST_MAX_RESIDUAL_PARTITION_ORDER, i);
1125 					}
1126 					else {
1127 						i = atoi(option_argument);
1128 						if(i > FLAC__MAX_RICE_PARTITION_ORDER)
1129 							return usage_error("ERROR: invalid value '%d' for min residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER);
1130 						add_compression_setting_uint32_t(CST_MIN_RESIDUAL_PARTITION_ORDER, i);
1131 						i = atoi(++p);
1132 						if(i > FLAC__MAX_RICE_PARTITION_ORDER)
1133 							return usage_error("ERROR: invalid value '%d' for max residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER);
1134 						add_compression_setting_uint32_t(CST_MAX_RESIDUAL_PARTITION_ORDER, i);
1135 					}
1136 				}
1137 				break;
1138 			case 'R':
1139 				{
1140 					uint32_t i;
1141 					i = atoi(option_argument);
1142 					add_compression_setting_uint32_t(CST_RICE_PARAMETER_SEARCH_DIST, i);
1143 				}
1144 				break;
1145 			default:
1146 				FLAC__ASSERT(0);
1147 		}
1148 	}
1149 
1150 	return 0;
1151 }
1152 
free_options(void)1153 void free_options(void)
1154 {
1155 	uint32_t i;
1156 	if(0 != option_values.filenames) {
1157 		for(i = 0; i < option_values.num_files; i++) {
1158 			if(0 != option_values.filenames[i])
1159 				free(option_values.filenames[i]);
1160 		}
1161 		free(option_values.filenames);
1162 	}
1163 	if(0 != option_values.vorbis_comment)
1164 		FLAC__metadata_object_delete(option_values.vorbis_comment);
1165 	for(i = 0; i < option_values.num_pictures; i++)
1166 		FLAC__metadata_object_delete(option_values.pictures[i]);
1167 }
1168 
add_compression_setting_bool(compression_setting_type_t type,FLAC__bool value)1169 void add_compression_setting_bool(compression_setting_type_t type, FLAC__bool value)
1170 {
1171 	if(option_values.num_compression_settings >= sizeof(option_values.compression_settings)/sizeof(option_values.compression_settings[0]))
1172 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1173 		die("too many compression settings");
1174 #else
1175 		return;
1176 #endif
1177 	option_values.compression_settings[option_values.num_compression_settings].type = type;
1178 	option_values.compression_settings[option_values.num_compression_settings].value.t_bool = value;
1179 	option_values.num_compression_settings++;
1180 }
1181 
add_compression_setting_string(compression_setting_type_t type,const char * value)1182 void add_compression_setting_string(compression_setting_type_t type, const char *value)
1183 {
1184 	if(option_values.num_compression_settings >= sizeof(option_values.compression_settings)/sizeof(option_values.compression_settings[0]))
1185 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1186 		die("too many compression settings");
1187 #else
1188 		return;
1189 #endif
1190 	option_values.compression_settings[option_values.num_compression_settings].type = type;
1191 	option_values.compression_settings[option_values.num_compression_settings].value.t_string = value;
1192 	option_values.num_compression_settings++;
1193 }
1194 
add_compression_setting_uint32_t(compression_setting_type_t type,uint32_t value)1195 void add_compression_setting_uint32_t(compression_setting_type_t type, uint32_t value)
1196 {
1197 	if(option_values.num_compression_settings >= sizeof(option_values.compression_settings)/sizeof(option_values.compression_settings[0]))
1198 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1199 		die("too many compression settings");
1200 #else
1201 		return;
1202 #endif
1203 	if(type == CST_COMPRESSION_LEVEL) {
1204 		/* Compression level always goes first */
1205 		option_values.compression_settings[0].type = type;
1206 		option_values.compression_settings[0].value.t_unsigned = value;
1207 	}
1208 	else {
1209 		option_values.compression_settings[option_values.num_compression_settings].type = type;
1210 		option_values.compression_settings[option_values.num_compression_settings].value.t_unsigned = value;
1211 		option_values.num_compression_settings++;
1212 	}
1213 }
1214 
usage_error(const char * message,...)1215 int usage_error(const char *message, ...)
1216 {
1217 	if(flac__utils_verbosity_ >= 1) {
1218 		va_list args;
1219 
1220 		FLAC__ASSERT(0 != message);
1221 
1222 		va_start(args, message);
1223 
1224 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1225 		(void) vfprintf(stderr, message, args);
1226 #endif
1227 
1228 		va_end(args);
1229 
1230 		printf("Type \"flac\" for a usage summary or \"flac --help\" for all options\n");
1231 	}
1232 
1233 	return 1;
1234 }
1235 
show_version(void)1236 void show_version(void)
1237 {
1238 	printf("flac %s\n", FLAC__VERSION_STRING);
1239 }
1240 
usage_header(void)1241 static void usage_header(void)
1242 {
1243 	printf("===============================================================================\n");
1244 	printf("flac - Command-line FLAC encoder/decoder version %s\n", FLAC__VERSION_STRING);
1245 	printf("Copyright (C) 2000-2009  Josh Coalson\n");
1246 	printf("Copyright (C) 2011-2022  Xiph.Org Foundation\n");
1247 	printf("\n");
1248 	printf("This program is free software; you can redistribute it and/or\n");
1249 	printf("modify it under the terms of the GNU General Public License\n");
1250 	printf("as published by the Free Software Foundation; either version 2\n");
1251 	printf("of the License, or (at your option) any later version.\n");
1252 	printf("\n");
1253 	printf("This program is distributed in the hope that it will be useful,\n");
1254 	printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
1255 	printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n");
1256 	printf("GNU General Public License for more details.\n");
1257 	printf("\n");
1258 	printf("You should have received a copy of the GNU General Public License along\n");
1259 	printf("with this program; if not, write to the Free Software Foundation, Inc.,\n");
1260 	printf("51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n");
1261 	printf("===============================================================================\n");
1262 }
1263 
usage_summary(void)1264 static void usage_summary(void)
1265 {
1266 	printf("Usage:\n");
1267 	printf("\n");
1268 	printf(" Encoding: flac [<general/encoding/format options>] [INPUTFILE [...]]\n");
1269 	printf(" Decoding: flac -d [<general/decoding/format options>] [FLACFILE [...]]\n");
1270 	printf("  Testing: flac -t [<general options>] [FLACFILE [...]]\n");
1271 	printf("Analyzing: flac -a [<general/analysis options>] [FLACFILE [...]]\n");
1272 	printf("\n");
1273 	printf("Be sure to read the list of known bugs at:\n");
1274 	printf("http://xiph.org/flac/documentation_bugs.html\n");
1275 	printf("\n");
1276 }
1277 
short_usage(void)1278 void short_usage(void)
1279 {
1280 	usage_header();
1281 	printf("\n");
1282 	printf("This is the short help; for all options use 'flac --help'; for even more\n");
1283 	printf("instructions use 'flac --explain'\n");
1284 	printf("\n");
1285 	printf("Be sure to read the list of known bugs at:\n");
1286 	printf("http://xiph.org/flac/documentation_bugs.html\n");
1287 	printf("\n");
1288 	printf("To encode:\n");
1289 	printf("  flac [-#] [INPUTFILE [...]]\n");
1290 	printf("\n");
1291 	printf("  -# is -0 (fastest compression) to -8 (highest compression); -5 is the default\n");
1292 	printf("\n");
1293 	printf("To decode:\n");
1294 	printf("  flac -d [INPUTFILE [...]]\n");
1295 	printf("\n");
1296 	printf("To test:\n");
1297 	printf("  flac -t [INPUTFILE [...]]\n");
1298 }
1299 
show_help(void)1300 void show_help(void)
1301 {
1302 	usage_header();
1303 	usage_summary();
1304 	printf("general options:\n");
1305 	printf("  -v, --version                Show the flac version number\n");
1306 	printf("  -h, --help                   Show this screen\n");
1307 	printf("  -H, --explain                Show detailed explanation of usage and options\n");
1308 	printf("  -d, --decode                 Decode (the default behavior is to encode)\n");
1309 	printf("  -t, --test                   Same as -d except no decoded file is written\n");
1310 	printf("  -a, --analyze                Same as -d except an analysis file is written\n");
1311 	printf("  -c, --stdout                 Write output to stdout\n");
1312 	printf("  -s, --silent                 Do not write runtime encode/decode statistics\n");
1313 	printf("      --totally-silent         Do not print anything, including errors\n");
1314 	printf("      --no-utf8-convert        Do not convert tags from local charset to UTF-8\n");
1315 	printf("  -w, --warnings-as-errors     Treat all warnings as errors\n");
1316 	printf("  -f, --force                  Force overwriting of output files\n");
1317 	printf("  -o, --output-name=FILENAME   Force the output file name\n");
1318 	printf("      --output-prefix=STRING   Prepend STRING to output names\n");
1319 	printf("      --delete-input-file      Deletes after a successful encode/decode\n");
1320 	printf("      --preserve-modtime       Output files keep timestamp of input (default)\n");
1321 	printf("      --keep-foreign-metadata  Save/restore WAVE or AIFF non-audio chunks\n");
1322 	printf("      --keep-foreign-metadata-if-present  Save/restore WAVE or AIFF non-audio\n");
1323 	printf("                        but not return an error when no such chunks are found\n");
1324 	printf("      --skip={#|mm:ss.ss}      Skip the given initial samples for each input\n");
1325 	printf("      --until={#|[+|-]mm:ss.ss}  Stop at the given sample for each input file\n");
1326 #if FLAC__HAS_OGG
1327 	printf("      --ogg                    Use Ogg as transport layer\n");
1328 	printf("      --serial-number          Serial number to use for the FLAC stream\n");
1329 #endif
1330 	printf("analysis options:\n");
1331 	printf("      --residual-text          Include residual signal in text output\n");
1332 	printf("      --residual-gnuplot       Generate gnuplot files of residual distribution\n");
1333 	printf("decoding options:\n");
1334 	printf("  -F, --decode-through-errors  Continue decoding through stream errors\n");
1335 	printf("      --cue=[#.#][-[#.#]]      Set the beginning and ending cuepoints to decode\n");
1336 	printf("encoding options:\n");
1337 	printf("  -V, --verify                 Verify a correct encoding\n");
1338 	printf("      --lax                    Allow encoder to generate non-Subset files\n");
1339 	printf("      --ignore-chunk-sizes     Ignore data chunk sizes in WAVE/AIFF files\n");
1340 	printf("      --sector-align (DEPRECATED) Align multiple files on sector boundaries\n");
1341 	printf("      --replay-gain            Calculate ReplayGain & store in FLAC tags\n");
1342 	printf("      --cuesheet=FILENAME      Import cuesheet and store in CUESHEET block\n");
1343 	printf("      --picture=SPECIFICATION  Import picture and store in PICTURE block\n");
1344 	printf("  -T, --tag=FIELD=VALUE        Add a FLAC tag; may appear multiple times\n");
1345 	printf("      --tag-from-file=FIELD=FILENAME   Like --tag but gets value from file\n");
1346 	printf("  -S, --seekpoint={#|X|#x|#s}  Add seek point(s)\n");
1347 	printf("  -P, --padding=#              Write a PADDING block of length #\n");
1348 	printf("  -0, --compression-level-0, --fast  Synonymous with -l 0 -b 1152 -r 3\n");
1349 	printf("  -1, --compression-level-1          Synonymous with -l 0 -b 1152 -M -r 3\n");
1350 	printf("  -2, --compression-level-2          Synonymous with -l 0 -b 1152 -m -r 3\n");
1351 	printf("  -3, --compression-level-3          Synonymous with -l 6 -b 4096 -r 4\n");
1352 	printf("  -4, --compression-level-4          Synonymous with -l 8 -b 4096 -M -r 4\n");
1353 	printf("  -5, --compression-level-5          Synonymous with -l 8 -b 4096 -m -r 5\n");
1354 	printf("  -6, --compression-level-6          Synonymous with -l 8 -b 4096 -m -r 6\n");
1355 	printf("                                         -A subdivide_tukey(2)\n");
1356 	printf("  -7, --compression-level-7          Synonymous with -l 12 -b 4096 -m -r 6\n");
1357 	printf("                                         -A subdivide_tukey(2)\n");
1358 	printf("  -8, --compression-level-8, --best  Synonymous with -l 12 -b 4096 -m -r 6\n");
1359 	printf("                                         -A subdivide_tukey(3)\n");
1360 	printf("  -b, --blocksize=#                  Specify blocksize in samples\n");
1361 	printf("  -m, --mid-side                     Try mid-side coding for each frame\n");
1362 	printf("  -M, --adaptive-mid-side            Adaptive mid-side coding for all frames\n");
1363 	printf("  -e, --exhaustive-model-search      Do exhaustive model search (expensive!)\n");
1364 	printf("  -A, --apodization=\"function\"       Window audio data with given the function\n");
1365 	printf("  -l, --max-lpc-order=#              Max LPC order; 0 => only fixed predictors\n");
1366 	printf("  -p, --qlp-coeff-precision-search   Exhaustively search LP coeff quantization\n");
1367 	printf("  -q, --qlp-coeff-precision=#        Specify precision in bits\n");
1368 	printf("  -r, --rice-partition-order=[#,]#   Set [min,]max residual partition order\n");
1369 	printf("      --limit-min-bitrate            Limit minimum bitrate (for streaming)\n");
1370 	printf("format options:\n");
1371 	printf("      --force-raw-format             Treat input or output as raw samples\n");
1372 	printf("      --force-aiff-format            Decode to AIFF format\n");
1373 	printf("      --force-rf64-format            Decode to RF64 format\n");
1374 	printf("      --force-wave64-format          Decode to Wave64 format\n");
1375 	printf("      --force-legacy-wave-format     Decode to legacy wave format\n");
1376 	printf("      --force-extensible-wave-format Decode to extensible wave format\n");
1377 	printf("      --force-aiff-c-none-format     Decode to AIFF-C NONE format\n");
1378 	printf("      --force-aiff-c-sowt-format     Decode to AIFF-C sowt format\n");
1379 	printf("raw format options:\n");
1380 	printf("      --endian={big|little}    Set byte order for samples\n");
1381 	printf("      --channels=#             Number of channels\n");
1382 	printf("      --bps=#                  Number of bits per sample\n");
1383 	printf("      --sample-rate=#          Sample rate in Hz\n");
1384 	printf("      --sign={signed|unsigned} Sign of samples\n");
1385 	printf("      --input-size=#           Size of the raw input in bytes\n");
1386 	printf("negative options:\n");
1387 	printf("      --no-adaptive-mid-side\n");
1388 	printf("      --no-cued-seekpoints\n");
1389 	printf("      --no-decode-through-errors\n");
1390 	printf("      --no-delete-input-file\n");
1391 	printf("      --no-error-on-compression-fail\n");
1392 	printf("      --no-preserve-modtime\n");
1393 	printf("      --no-keep-foreign-metadata\n");
1394 	printf("      --no-exhaustive-model-search\n");
1395 	printf("      --no-lax\n");
1396 	printf("      --no-mid-side\n");
1397 #if FLAC__HAS_OGG
1398 	printf("      --no-ogg\n");
1399 #endif
1400 	printf("      --no-padding\n");
1401 	printf("      --no-qlp-coeff-prec-search\n");
1402 	printf("      --no-replay-gain\n");
1403 	printf("      --no-residual-gnuplot\n");
1404 	printf("      --no-residual-text\n");
1405 	printf("      --no-ignore-chunk-sizes\n");
1406 	printf("      --no-sector-align\n");
1407 	printf("      --no-seektable\n");
1408 	printf("      --no-silent\n");
1409 	printf("      --no-force\n");
1410 	printf("      --no-verify\n");
1411 	printf("      --no-warnings-as-errors\n");
1412 }
1413 
show_explain(void)1414 void show_explain(void)
1415 {
1416 	usage_header();
1417 	usage_summary();
1418 	printf("For encoding:\n");
1419 	printf("  The input file(s) may be a PCM WAVE, Wave64, RF64 file, AIFF (or uncompressed\n");
1420 	printf("  AIFF-C) file, or raw samples. The output file(s)  will be in native FLAC\n");
1421 	printf("  or Ogg FLAC format\n");
1422 	printf("For decoding, the reverse is true.\n");
1423 	printf("\n");
1424 	printf("A single INPUTFILE may be - for stdin.  No INPUTFILE implies stdin.  Use of\n");
1425 	printf("stdin implies -c (write to stdout).  Normally you should use:\n");
1426 	printf("   flac [options] -o outfilename  or  flac -d [options] -o outfilename\n");
1427 	printf("instead of:\n");
1428 	printf("   flac [options] > outfilename   or  flac -d [options] > outfilename\n");
1429 	printf("since the former allows flac to seek backwards to write the STREAMINFO or\n");
1430 	printf("WAVE/AIFF header contents when necessary.\n");
1431 	printf("\n");
1432 	printf("general options:\n");
1433 	printf("  -v, --version                Show the flac version number\n");
1434 	printf("  -h, --help                   Show basic usage a list of all options\n");
1435 	printf("  -H, --explain                Show this screen\n");
1436 	printf("  -d, --decode                 Decode (the default behavior is to encode)\n");
1437 	printf("  -t, --test                   Same as -d except no decoded file is written\n");
1438 	printf("  -a, --analyze                Same as -d except an analysis file is written\n");
1439 	printf("  -c, --stdout                 Write output to stdout\n");
1440 	printf("  -s, --silent                 Do not write runtime encode/decode statistics\n");
1441 	printf("      --totally-silent         Do not print anything of any kind, including\n");
1442 	printf("                               warnings or errors.  The exit code will be the\n");
1443 	printf("                               only way to determine successful completion.\n");
1444 	printf("      --no-utf8-convert        Do not convert tags from local charset to UTF-8.\n");
1445 	printf("                               This is useful for scripts, and setting tags in\n");
1446 	printf("                               situations where the locale is wrong.  This\n");
1447 	printf("                               option must appear before any tag options!\n");
1448 	printf("  -w, --warnings-as-errors     Treat all warnings as errors\n");
1449 	printf("  -f, --force                  Force overwriting of output files\n");
1450 	printf("  -o, --output-name=FILENAME   Force the output file name; usually flac just\n");
1451 	printf("                               changes the extension.  May only be used when\n");
1452 	printf("                               encoding a single file.  May not be used in\n");
1453 	printf("                               conjunction with --output-prefix.\n");
1454 	printf("      --output-prefix=STRING   Prefix each output file name with the given\n");
1455 	printf("                               STRING.  This can be useful for encoding or\n");
1456 	printf("                               decoding files to a different directory.  Make\n");
1457 	printf("                               sure if your STRING is a path name that it ends\n");
1458 	printf("                               with a '/' slash.\n");
1459 	printf("      --delete-input-file      Automatically delete the input file after a\n");
1460 	printf("                               successful encode or decode.  If there was an\n");
1461 	printf("                               error (including a verify error) the input file\n");
1462 	printf("                               is left intact.\n");
1463 	printf("      --preserve-modtime       Output files have their timestamps/permissions\n");
1464 	printf("                               set to match those of their inputs (this is\n");
1465 	printf("                               default).  Use --no-preserve-modtime to make\n");
1466 	printf("                               output files have the current time and default\n");
1467 	printf("                               permissions.\n");
1468 	printf("      --keep-foreign-metadata  If encoding, save WAVE or AIFF non-audio chunks\n");
1469 	printf("                               in FLAC metadata.  If decoding, restore any saved\n");
1470 	printf("                               non-audio chunks from FLAC metadata when writing\n");
1471 	printf("                               the decoded file.  Foreign metadata cannot be\n");
1472 	printf("                               transcoded, e.g. WAVE chunks saved in a FLAC file\n");
1473 	printf("                               cannot be restored when decoding to AIFF.  Input\n");
1474 	printf("                               and output must be regular files, not stdin/out.\n");
1475 	printf("                               With this option, FLAC will pick the right\n");
1476 	printf("                               output format on decoding.\n");
1477 	printf("      --keep-foreign-metadata-if-present  As previous option, but do not throw\n");
1478 	printf("                               an error in case no foreign metadata is found,\n");
1479 	printf("                               the wrong kind of foreign metadata is found (on\n");
1480 	printf("                               decoding) or if the foreign could not be parsed,\n");
1481 	printf("                               i.e. all foreign metadata related errors are\n");
1482 	printf("                               treated as warnings.\n");
1483 	printf("      --skip={#|mm:ss.ss}      Skip the first # samples of each input file; can\n");
1484 	printf("                               be used both for encoding and decoding.  The\n");
1485 	printf("                               alternative form mm:ss.ss can be used to specify\n");
1486 	printf("                               minutes, seconds, and fractions of a second.\n");
1487 	printf("      --until={#|[+|-]mm:ss.ss}  Stop at the given sample number for each input\n");
1488 	printf("                               file.  The given sample number is not included\n");
1489 	printf("                               in the decoded output.  The alternative form\n");
1490 	printf("                               mm:ss.ss can be used to specify minutes,\n");
1491 	printf("                               seconds, and fractions of a second.  If a `+'\n");
1492 	printf("                               sign is at the beginning, the --until point is\n");
1493 	printf("                               relative to the --skip point.  If a `-' sign is\n");
1494 	printf("                               at the beginning, the --until point is relative\n");
1495 	printf("                               to end of the audio.\n");
1496 #if FLAC__HAS_OGG
1497 	printf("      --ogg                    When encoding, generate Ogg FLAC output instead\n");
1498 	printf("                               of native FLAC.  Ogg FLAC streams are FLAC\n");
1499 	printf("                               streams wrapped in an Ogg transport layer.  The\n");
1500 	printf("                               resulting file should have an '.oga' extension\n");
1501 	printf("                               and will still be decodable by flac.  When\n");
1502 	printf("                               decoding, force the input to be treated as\n");
1503 	printf("                               Ogg FLAC.  This is useful when piping input\n");
1504 	printf("                               from stdin or when the filename does not end in\n");
1505 	printf("                               '.oga' or '.ogg'.\n");
1506 	printf("      --serial-number          Serial number to use for the FLAC stream.  When\n");
1507 	printf("                               encoding and no serial number is given, flac\n");
1508 	printf("                               uses a random one.  If encoding to multiple files\n");
1509 	printf("                               the serial number is incremented for each file.\n");
1510 	printf("                               When decoding and no number is given, flac uses\n");
1511 	printf("                               the serial number of the first page.\n");
1512 #endif
1513 	printf("analysis options:\n");
1514 	printf("      --residual-text          Include residual signal in text output.  This\n");
1515 	printf("                               will make the file very big, much larger than\n");
1516 	printf("                               even the decoded file.\n");
1517 	printf("      --residual-gnuplot       Generate gnuplot files of residual distribution\n");
1518 	printf("                               of each subframe\n");
1519 	printf("decoding options:\n");
1520 	printf("  -F, --decode-through-errors  By default flac stops decoding with an error\n");
1521 	printf("                               and removes the partially decoded file if it\n");
1522 	printf("                               encounters a bitstream error.  With -F, errors\n");
1523 	printf("                               are still printed but flac will continue\n");
1524 	printf("                               decoding to completion.  Note that errors may\n");
1525 	printf("                               cause the decoded audio to be missing some\n");
1526 	printf("                               samples or have silent sections.\n");
1527 	printf("      --cue=[#.#][-[#.#]]      Set the beginning and ending cuepoints to\n");
1528 	printf("                               decode.  The optional first #.# is the track and\n");
1529 	printf("                               index point at which decoding will start; the\n");
1530 	printf("                               default is the beginning of the stream.  The\n");
1531 	printf("                               optional second #.# is the track and index point\n");
1532 	printf("                               at which decoding will end; the default is the\n");
1533 	printf("                               end of the stream.  If the cuepoint does not\n");
1534 	printf("                               exist, the closest one before it (for the start\n");
1535 	printf("                               point) or after it (for the end point) will be\n");
1536 	printf("                               used.  The cuepoints are merely translated into\n");
1537 	printf("                               sample numbers then used as --skip and --until.\n");
1538 	printf("                               A CD track can always be cued by, for example,\n");
1539 	printf("                               --cue=9.1-10.1 for track 9, even if the CD has\n");
1540 	printf("                               no 10th track.\n");
1541 	printf("encoding options:\n");
1542 	printf("  -V, --verify                 Verify a correct encoding by decoding the\n");
1543 	printf("                               output in parallel and comparing to the\n");
1544 	printf("                               original\n");
1545 	printf("      --lax                    Allow encoder to generate non-Subset files\n");
1546 	printf("      --ignore-chunk-sizes     Ignore data chunk sizes in WAVE/AIFF files;\n");
1547 	printf("                               useful when piping data from programs which\n");
1548 	printf("                               generate bogus data chunk sizes.\n");
1549 	printf("      --sector-align           Align encoding of multiple CD format WAVE files\n");
1550 	printf("                               on sector boundaries.  This option is DEPRECATED\n");
1551 	printf("                               and may not exist in future versions of flac.\n");
1552 	printf("                               shntool offers similar functionality.\n");
1553 	printf("      --replay-gain            Calculate ReplayGain values and store them as\n");
1554 	printf("                               FLAC tags.  Title gains/peaks will be computed\n");
1555 	printf("                               for each file, and an album gain/peak will be\n");
1556 	printf("                               computed for all files.  All input files must\n");
1557 	printf("                               have the same resolution, sample rate, and\n");
1558 	printf("                               number of channels.  Only mono and stereo files\n");
1559 	printf("                               are allowed, and the sample rate must be 8,\n");
1560 	printf("                               11.025, 12, 16, 18.9, 22.05, 24, 28, 32, 36,\n");
1561 	printf("                               37.8, 44.1, 48, 56, 64, 72, 75.6, 88.2, 96, 112,\n");
1562 	printf("                               128, 144, 151.2, 176.4, 192, 224, 256, 288,\n");
1563 	printf("                               302.4, 352.8, 384, 448, 512, 576, or 604.8 kHz.\n");
1564 	printf("                               NOTE: this option may also leave a few extra\n");
1565 	printf("                               bytes in the PADDING block.\n");
1566 	printf("      --cuesheet=FILENAME      Import the given cuesheet file and store it in\n");
1567 	printf("                               a CUESHEET metadata block.  This option may only\n");
1568 	printf("                               be used when encoding a single file.  A\n");
1569 	printf("                               seekpoint will be added for each index point in\n");
1570 	printf("                               the cuesheet to the SEEKTABLE unless\n");
1571 	printf("                               --no-cued-seekpoints is specified.\n");
1572 	printf("      --picture=SPECIFICATION  Import a picture and store it in a PICTURE block.\n");
1573 	printf("                               More than one --picture command can be specified.\n");
1574 	printf("                               The SPECIFICATION can either be a simple filename\n");
1575 	printf("                               for the picture file, or a complete specification\n");
1576 	printf("                               whose parts are separated by | characters.  Some\n");
1577 	printf("                               parts may be left empty to invoke default values.\n");
1578 	printf("                               Using a filename is shorthand for \"||||FILE\".\n");
1579 	printf("                               The SPECIFICATION format is:\n");
1580 	printf("         [TYPE]|[MIME-TYPE]|[DESCRIPTION]|[WIDTHxHEIGHTxDEPTH[/COLORS]]|FILE\n");
1581 	printf("           TYPE is optional; it is a number from one of:\n");
1582 	printf("              0: Other\n");
1583 	printf("              1: 32x32 pixels 'file icon' (PNG only)\n");
1584 	printf("              2: Other file icon\n");
1585 	printf("              3: Cover (front)\n");
1586 	printf("              4: Cover (back)\n");
1587 	printf("              5: Leaflet page\n");
1588 	printf("              6: Media (e.g. label side of CD)\n");
1589 	printf("              7: Lead artist/lead performer/soloist\n");
1590 	printf("              8: Artist/performer\n");
1591 	printf("              9: Conductor\n");
1592 	printf("             10: Band/Orchestra\n");
1593 	printf("             11: Composer\n");
1594 	printf("             12: Lyricist/text writer\n");
1595 	printf("             13: Recording Location\n");
1596 	printf("             14: During recording\n");
1597 	printf("             15: During performance\n");
1598 	printf("             16: Movie/video screen capture\n");
1599 	printf("             17: A bright coloured fish\n");
1600 	printf("             18: Illustration\n");
1601 	printf("             19: Band/artist logotype\n");
1602 	printf("             20: Publisher/Studio logotype\n");
1603 	printf("             The default is 3 (front cover).  There may only be one picture each\n");
1604 	printf("             of type 1 and 2 in a file.\n");
1605 	printf("           MIME-TYPE is optional; if left blank, it will be detected from the\n");
1606 	printf("             file.  For best compatibility with players, use pictures with MIME\n");
1607 	printf("             type image/jpeg or image/png.  The MIME type can also be --> to\n");
1608 	printf("             mean that FILE is actually a URL to an image, though this use is\n");
1609 	printf("             discouraged.\n");
1610 	printf("           DESCRIPTION is optional; the default is an empty string\n");
1611 	printf("           The next part specifies the resolution and color information.  If\n");
1612 	printf("             the MIME-TYPE is image/jpeg, image/png, or image/gif, you can\n");
1613 	printf("             usually leave this empty and they can be detected from the file.\n");
1614 	printf("             Otherwise, you must specify the width in pixels, height in pixels,\n");
1615 	printf("             and color depth in bits-per-pixel.  If the image has indexed colors\n");
1616 	printf("             you should also specify the number of colors used.\n");
1617 	printf("           FILE is the path to the picture file to be imported, or the URL if\n");
1618 	printf("             MIME type is -->\n");
1619 	printf("  -T, --tag=FIELD=VALUE        Add a FLAC tag.  Make sure to quote the\n");
1620 	printf("                               comment if necessary.  This option may appear\n");
1621 	printf("                               more than once to add several comments.  NOTE:\n");
1622 	printf("                               all tags will be added to all encoded files.\n");
1623 	printf("      --tag-from-file=FIELD=FILENAME   Like --tag, except FILENAME is a file\n");
1624 	printf("                               whose contents will be read verbatim to set the\n");
1625 	printf("                               tag value.  The contents will be converted to\n");
1626 	printf("                               UTF-8 from the local charset.  This can be used\n");
1627 	printf("                               to store a cuesheet in a tag (e.g.\n");
1628 	printf("                               --tag-from-file=\"CUESHEET=image.cue\").  Do not\n");
1629 	printf("                               try to store binary data in tag fields!  Use\n");
1630 	printf("                               APPLICATION blocks for that.\n");
1631 	printf("  -S, --seekpoint={#|X|#x|#s}  Include a point or points in a SEEKTABLE\n");
1632 	printf("       #  : a specific sample number for a seek point\n");
1633 	printf("       X  : a placeholder point (always goes at the end of the SEEKTABLE)\n");
1634 	printf("       #x : # evenly spaced seekpoints, the first being at sample 0\n");
1635 	printf("       #s : a seekpoint every # seconds; # does not have to be a whole number\n");
1636 	printf("     You may use many -S options; the resulting SEEKTABLE will be the unique-\n");
1637 	printf("           ified union of all such values.\n");
1638 	printf("     With no -S options, flac defaults to '-S 10s'.  Use -S- for no SEEKTABLE.\n");
1639 	printf("     Note: -S #x and -S #s will not work if the encoder can't determine the\n");
1640 	printf("           input size before starting.\n");
1641 	printf("     Note: if you use -S # and # is >= samples in the input, there will be\n");
1642 	printf("           either no seek point entered (if the input size is determinable\n");
1643 	printf("           before encoding starts) or a placeholder point (if input size is not\n");
1644 	printf("           determinable)\n");
1645 	printf("  -P, --padding=#              Tell the encoder to write a PADDING metadata\n");
1646 	printf("                               block of the given length (in bytes) after the\n");
1647 	printf("                               STREAMINFO block.  This is useful if you plan\n");
1648 	printf("                               to tag the file later with an APPLICATION\n");
1649 	printf("                               block; instead of having to rewrite the entire\n");
1650 	printf("                               file later just to insert your block, you can\n");
1651 	printf("                               write directly over the PADDING block.  Note\n");
1652 	printf("                               that the total length of the PADDING block will\n");
1653 	printf("                               be 4 bytes longer than the length given because\n");
1654 	printf("                               of the 4 metadata block header bytes.  You can\n");
1655 	printf("                               force no PADDING block at all to be written with\n");
1656 	printf("                               --no-padding.  The encoder writes a PADDING\n");
1657 	printf("                               block of 8192 bytes by default, or 65536 bytes\n");
1658 	printf("                               if the input audio is more than 20 minutes long.\n");
1659 	printf("  -b, --blocksize=#            Specify the blocksize in samples; the default is\n");
1660 	printf("                               1152 for -l 0, else 4096; for subset streams this\n");
1661 	printf("                               must be <= 4608 if the samplerate <= 48kHz,\n");
1662 	printf("                               for subset streams with a higher samplerates it\n");
1663 	printf("                               must be <= 16384.\n");
1664 	printf("  -0, --compression-level-0, --fast  Synonymous with -l 0 -b 1152 -r 3\n");
1665 	printf("                                                            --no-mid-side\n");
1666 	printf("  -1, --compression-level-1          Synonymous with -l 0 -b 1152 -M -r 3\n");
1667 	printf("  -2, --compression-level-2          Synonymous with -l 0 -b 1152 -m -r 3\n");
1668 	printf("  -3, --compression-level-3          Synonymous with -l 6 -b 4096 -r 4\n");
1669 	printf("                                                            --no-mid-side\n");
1670 	printf("  -4, --compression-level-4          Synonymous with -l 8 -b 4096 -M -r 4\n");
1671 	printf("  -5, --compression-level-5          Synonymous with -l 8 -b 4096 -m -r 5\n");
1672 	printf("                                     -5 is the default setting\n");
1673 	printf("  -6, --compression-level-6          Synonymous with -l 8 -b 4096 -m -r 6\n");
1674 	printf("                                         -A subdivide_tukey(2)\n");
1675 	printf("  -7, --compression-level-7          Synonymous with -l 12 -b 4096 -m -r 6\n");
1676 	printf("                                         -A subdivide_tukey(2)\n");
1677 	printf("  -8, --compression-level-8, --best  Synonymous with -l 12 -b 4096 -m -r 6\n");
1678 	printf("                                         -A subdivide_tukey(3)\n");
1679 	printf("  -m, --mid-side                     Try mid-side coding for each frame\n");
1680 	printf("                                     (stereo only)\n");
1681 	printf("  -M, --adaptive-mid-side            Adaptive mid-side coding for all frames\n");
1682 	printf("                                     (stereo only)\n");
1683 	printf("  -e, --exhaustive-model-search      Do exhaustive model search (expensive!)\n");
1684 	printf("  -A, --apodization=\"function\"       Window audio data with given the function.\n");
1685 	printf("                                     The functions are: bartlett, bartlett_hann,\n");
1686 	printf("                                     blackman, blackman_harris_4term_92db,\n");
1687 	printf("                                     connes, flattop, gauss(STDDEV), hamming,\n");
1688 	printf("                                     hann, kaiser_bessel, nuttall, rectangle,\n");
1689 	printf("                                     triangle, tukey(P), welch, partial_tukey(n)\n");
1690 	printf("                                     punchout_tukey(n) and subdivide_tukey(n).\n");
1691 	printf("                                     More than one may be specified but encoding\n");
1692 	printf("                                     time is a multiple of the number of\n");
1693 	printf("                                     functions since they are each tried in \n");
1694 	printf("                                     turn.  The encoder chooses suitable\n");
1695 	printf("                                     defaults in the absence of any -A options.\n");
1696 	printf("  -l, --max-lpc-order=#              Max LPC order; 0 => only fixed predictors.\n");
1697 	printf("                                     Must be <= 12 for Subset streams if sample\n");
1698 	printf("                                     rate is <=48kHz.\n");
1699 	printf("  -p, --qlp-coeff-precision-search   Do exhaustive search of LP coefficient\n");
1700 	printf("                                     quantization (expensive!); overrides -q;\n");
1701 	printf("                                     does nothing if using -l 0\n");
1702 	printf("  -q, --qlp-coeff-precision=#        Specify precision in bits of quantized\n");
1703 	printf("                                     linear-predictor coefficients; 0 => let\n");
1704 	printf("                                     encoder decide (the minimum is %u, the\n", FLAC__MIN_QLP_COEFF_PRECISION);
1705 	printf("                                     default is -q 0)\n");
1706 	printf("  -r, --rice-partition-order=[#,]#   Set [min,]max residual partition order\n");
1707 	printf("                                     (# is 0 to 15 inclusive; min defaults to 0;\n");
1708 	printf("                                     the default is -r 0; above 4 does not\n");
1709 	printf("                                     usually help much)\n");
1710 	printf("      --limit-min-bitrate            Limit minimum bitrate by not allowing\n");
1711 	printf("                                     frames consisting of only constant\n");
1712 	printf("                                     subframes. This ensures a bitrate of at\n");
1713 	printf("                                     least 1 bit/sample, for example 48kbit/s\n");
1714 	printf("                                     for 48kHz input. This is mostly beneficial\n");
1715 	printf("                                     for internet streaming.\n");
1716 	printf("format options:\n");
1717 	printf("      --force-raw-format       Force input (when encoding) or output (when\n");
1718 	printf("                               decoding) to be treated as raw samples\n");
1719 	printf("      --force-aiff-format\n");
1720 	printf("      --force-rf64-format\n");
1721 	printf("      --force-wave64-format\n");
1722 	printf("            Force the decoder to output AIFF/RF64/WAVE64 format respectively.\n");
1723 	printf("            This option is not needed if the output filename (as set by -o)\n");
1724 	printf("            ends with *.aif* or *.aiff*, *.rf64* and *.w64* respectively. Also,\n");
1725 	printf("            this option has no effect when encoding since input is\n");
1726 	printf("            auto-detected. When none of these options nor\n");
1727 	printf("            --keep-foreign-metadata are given and no output filename is set,\n");
1728 	printf("            the output format is WAV by default.\n");
1729 	printf("      --force-legacy-wave-format\n");
1730 	printf("      --force-extensible-wave-format\n");
1731 	printf("            Instruct the decoder to output a WAVE file with WAVE_FORMAT_PCM and\n");
1732 	printf("            WAVE_FORMAT_EXTENSIBLE respectively. If none of these options nor\n");
1733 	printf("            --keep-foreign-metadata are given, FLAC outputs WAVE_FORMAT_PCM\n");
1734 	printf("            for mono or stereo with a bit depth of 8 or 16 bits, and\n");
1735 	printf("            WAVE_FORMAT_EXTENSIBLE for all other audio formats.\n");
1736 	printf("      --force-aiff-c-none-format\n");
1737 	printf("      --force-aiff-c-sowt-format\n");
1738 	printf("            Instruct the decoder to output an AIFF-C file with format NONE and\n");
1739 	printf("            sowt respectively.\n");
1740 	printf("raw format options:\n");
1741 	printf("      --endian={big|little}    Set byte order for samples\n");
1742 	printf("      --channels=#             Number of channels\n");
1743 	printf("      --bps=#                  Number of bits per sample\n");
1744 	printf("      --sample-rate=#          Sample rate in Hz\n");
1745 	printf("      --sign={signed|unsigned} Sign of samples\n");
1746 	printf("      --input-size=#           Size of the raw input in bytes.  If you are\n");
1747 	printf("                               encoding raw samples from stdin, you must set\n");
1748 	printf("                               this option in order to be able to use --skip,\n");
1749 	printf("                               --until, --cuesheet, or other options that need\n");
1750 	printf("                               to know the size of the input beforehand.  If\n");
1751 	printf("                               the size given is greater than what is found in\n");
1752 	printf("                               the input stream, the encoder will complain\n");
1753 	printf("                               about an unexpected end-of-file.  If the size\n");
1754 	printf("                               given is less, samples will be truncated.\n");
1755 	printf("negative options:\n");
1756 	printf("      --no-adaptive-mid-side\n");
1757 	printf("      --no-cued-seekpoints\n");
1758 	printf("      --no-decode-through-errors\n");
1759 	printf("      --no-delete-input-file\n");
1760 	printf("      --no-preserve-modtime\n");
1761 	printf("      --no-keep-foreign-metadata\n");
1762 	printf("      --no-exhaustive-model-search\n");
1763 	printf("      --no-lax\n");
1764 	printf("      --no-mid-side\n");
1765 #if FLAC__HAS_OGG
1766 	printf("      --no-ogg\n");
1767 #endif
1768 	printf("      --no-padding\n");
1769 	printf("      --no-qlp-coeff-prec-search\n");
1770 	printf("      --no-residual-gnuplot\n");
1771 	printf("      --no-residual-text\n");
1772 	printf("      --no-ignore-chunk-sizes\n");
1773 	printf("      --no-sector-align\n");
1774 	printf("      --no-seektable\n");
1775 	printf("      --no-silent\n");
1776 	printf("      --no-force\n");
1777 	printf("      --no-verify\n");
1778 	printf("      --no-warnings-as-errors\n");
1779 }
1780 
format_mistake(const char * infilename,FileFormat wrong,FileFormat right)1781 void format_mistake(const char *infilename, FileFormat wrong, FileFormat right)
1782 {
1783 	/* WATCHOUT: indexed by FileFormat */
1784 	flac__utils_printf(stderr, 1, "WARNING: %s is not a%s file; treating as a%s file\n", infilename, FileFormatString[wrong], FileFormatString[right]);
1785 }
1786 
encode_file(const char * infilename,FLAC__bool is_first_file,FLAC__bool is_last_file)1787 int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_last_file)
1788 {
1789 	FILE *encode_infile;
1790 	FLAC__byte lookahead[12];
1791 	uint32_t lookahead_length = 0, master_chunk_size = 0;
1792 	FileFormat input_format = FORMAT_RAW;
1793 	int retval;
1794 	FLAC__off_t infilesize;
1795 	encode_options_t encode_options;
1796 	const char *outfilename = get_encoded_outfilename(infilename); /* the final name of the encoded file */
1797 	/* internal_outfilename is the file we will actually write to; it will be a temporary name if infilename==outfilename */
1798 	char *internal_outfilename = 0; /* NULL implies 'use outfilename' */
1799 	size_t infilename_length;
1800 
1801 	if(0 == outfilename) {
1802 		flac__utils_printf(stderr, 1, "ERROR: filename too long: %s", infilename);
1803 		return 1;
1804 	}
1805 
1806 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1807 	if(0 == strcmp(infilename, "-")) {
1808 		infilesize = (FLAC__off_t)(-1);
1809 		encode_infile = grabbag__file_get_binary_stdin();
1810 	}
1811 	else
1812 #endif
1813 	{
1814 		infilesize = grabbag__file_get_filesize(infilename);
1815 		if(0 == (encode_infile = flac_fopen(infilename, "rb"))) {
1816 			flac__utils_printf(stderr, 1, "ERROR: can't open input file %s: %s\n", infilename, strerror(errno));
1817 			return 1;
1818 		}
1819 	}
1820 
1821 	if(!option_values.force_raw_format) {
1822 		/* first set format based on name */
1823 		infilename_length = strlen(infilename);
1824 		if(infilename_length >= 4 && 0 == FLAC__STRCASECMP(infilename+(infilename_length-4), ".wav"))
1825 			input_format = FORMAT_WAVE;
1826 		else if(infilename_length >= 5 && 0 == FLAC__STRCASECMP(infilename+(infilename_length-5), ".rf64"))
1827 			input_format = FORMAT_RF64;
1828 		else if(infilename_length >= 4 && 0 == FLAC__STRCASECMP(infilename+(infilename_length-4), ".w64"))
1829 			input_format = FORMAT_WAVE64;
1830 		else if(infilename_length >= 4 && 0 == FLAC__STRCASECMP(infilename+(infilename_length-4), ".aif"))
1831 			input_format = FORMAT_AIFF;
1832 		else if(infilename_length >= 5 && 0 == FLAC__STRCASECMP(infilename+(infilename_length-5), ".aiff"))
1833 			input_format = FORMAT_AIFF;
1834 		else if(infilename_length >= 5 && 0 == FLAC__STRCASECMP(infilename+(infilename_length-5), ".flac"))
1835 			input_format = FORMAT_FLAC;
1836 		else if(infilename_length >= 4 && 0 == FLAC__STRCASECMP(infilename+(infilename_length-4), ".oga"))
1837 			input_format = FORMAT_OGGFLAC;
1838 		else if(infilename_length >= 4 && 0 == FLAC__STRCASECMP(infilename+(infilename_length-4), ".ogg"))
1839 			input_format = FORMAT_OGGFLAC;
1840 
1841 		/* attempt to guess the file type based on the first 12 bytes */
1842 		if((lookahead_length = fread(lookahead, 1, 12, encode_infile)) < 12) {
1843 			/* all supported non-raw formats have at least 12 bytes of header to read */
1844 			if(input_format != FORMAT_RAW) {
1845 				format_mistake(infilename, input_format, FORMAT_RAW);
1846 				if(option_values.treat_warnings_as_errors) {
1847 					conditional_fclose(encode_infile);
1848 					return 1;
1849 				}
1850 			}
1851 			/* force to raw */
1852 			input_format = FORMAT_RAW;
1853 		}
1854 		else {
1855 			if(!memcmp(lookahead, "ID3", 3)) {
1856 				flac__utils_printf(stderr, 1, "ERROR: input file %s has an ID3v2 tag\n", infilename);
1857 				conditional_fclose(encode_infile);
1858 				return 1;
1859 			}
1860 			else if(!memcmp(lookahead, "RIFF", 4) && !memcmp(lookahead+8, "WAVE", 4))
1861 				input_format = FORMAT_WAVE;
1862 			else if(!memcmp(lookahead, "RF64", 4) && !memcmp(lookahead+8, "WAVE", 4))
1863 				input_format = FORMAT_RF64;
1864 			else if(!memcmp(lookahead, "riff\x2E\x91\xCF\x11\xA5\xD6\x28\xDB", 12)) /* just check 1st 12 bytes of GUID */
1865 				input_format = FORMAT_WAVE64;
1866 			else if(!memcmp(lookahead, "FORM", 4) && !memcmp(lookahead+8, "AIFF", 4))
1867 				input_format = FORMAT_AIFF;
1868 			else if(!memcmp(lookahead, "FORM", 4) && !memcmp(lookahead+8, "AIFC", 4))
1869 				input_format = FORMAT_AIFF_C;
1870 			else if(!memcmp(lookahead, FLAC__STREAM_SYNC_STRING, sizeof(FLAC__STREAM_SYNC_STRING)))
1871 				input_format = FORMAT_FLAC;
1872 			/*@@@ this could be made more accurate by looking at the first packet to make sure it's Ogg FLAC and not, say, Ogg Vorbis.  we do catch such problems later though. */
1873 			else if(!memcmp(lookahead, "OggS", 4))
1874 				input_format = FORMAT_OGGFLAC;
1875 			else {
1876 				/* didn't find header of any supported format */
1877 				if(input_format != FORMAT_RAW) {
1878 					format_mistake(infilename, input_format, FORMAT_RAW);
1879 					if(option_values.treat_warnings_as_errors) {
1880 						conditional_fclose(encode_infile);
1881 						return 1;
1882 					}
1883 				}
1884 				/* force to raw */
1885 				input_format = FORMAT_RAW;
1886 			}
1887 		}
1888 	}
1889 
1890 	if(!option_values.ignore_chunk_sizes
1891 	   && (input_format == FORMAT_WAVE || input_format == FORMAT_AIFF || input_format == FORMAT_AIFF_C)
1892 	   && infilesize >= UINT32_MAX) {
1893 		conditional_fclose(encode_infile);
1894 		return usage_error("ERROR: file %s is too large to be valid.\n"
1895 		                   "Please consult the manual on the --ignore-chunk-sizes option\n\n", infilename);
1896 	}
1897 
1898 	if(input_format == FORMAT_WAVE || input_format == FORMAT_AIFF || input_format == FORMAT_AIFF_C) {
1899 		memcpy(&master_chunk_size,lookahead+4,sizeof(master_chunk_size));
1900 		if((input_format != FORMAT_WAVE) != CPU_IS_BIG_ENDIAN /* logical xor */)
1901 			/* true for WAVE on big endian CPUs or AIFF/AIFF-C on little endian CPUs */
1902 			master_chunk_size = ENDSWAP_32(master_chunk_size);
1903 
1904 		if(infilesize != (FLAC__off_t)(-1) && infilesize > 8 && (infilesize - 8) != master_chunk_size) {
1905 			flac__utils_printf(stderr, 1, "WARNING: %s chunk size of file %s does not agree with filesize\n", (input_format == FORMAT_WAVE)?"RIFF":"FORM", infilename);
1906 			if(option_values.treat_warnings_as_errors)
1907 				return 1;
1908 		}
1909 	}
1910 
1911 	if(option_values.keep_foreign_metadata || option_values.keep_foreign_metadata_if_present) {
1912 		if(encode_infile == stdin || option_values.force_to_stdout) {
1913 			conditional_fclose(encode_infile);
1914 			return usage_error("ERROR: --keep-foreign-metadata cannot be used when encoding from stdin or to stdout\n");
1915 		}
1916 		if(input_format != FORMAT_WAVE && input_format != FORMAT_WAVE64 && input_format != FORMAT_RF64 && input_format != FORMAT_AIFF && input_format != FORMAT_AIFF_C) {
1917 			conditional_fclose(encode_infile);
1918 			return usage_error("ERROR: --keep-foreign-metadata can only be used with WAVE, Wave64, RF64, or AIFF input\n");
1919 		}
1920 	}
1921 
1922 	/*
1923 	 * Error if output file already exists (and -f not used).
1924 	 * Use grabbag__file_get_filesize() as a cheap way to check.
1925 	 */
1926 	if(!option_values.test_only && !option_values.force_file_overwrite && strcmp(outfilename, "-") && grabbag__file_get_filesize(outfilename) != (FLAC__off_t)(-1)) {
1927 		if(input_format == FORMAT_FLAC) {
1928 			/* need more detailed error message when re-flac'ing to avoid confusing the user */
1929 			flac__utils_printf(stderr, 1,
1930 				"ERROR: output file %s already exists.\n\n"
1931 				"By default flac encodes files to FLAC format; if you meant to decode this file\n"
1932 				"from FLAC to something else, use -d.  If you meant to re-encode this file from\n"
1933 				"FLAC to FLAC again, use -f to force writing to the same file, or -o to specify\n"
1934 				"a different output filename.\n",
1935 				outfilename
1936 			);
1937 		}
1938 		else if(input_format == FORMAT_OGGFLAC) {
1939 			/* need more detailed error message when re-flac'ing to avoid confusing the user */
1940 			flac__utils_printf(stderr, 1,
1941 				"ERROR: output file %s already exists.\n\n"
1942 				"By default 'flac -ogg' encodes files to Ogg FLAC format; if you meant to decode\n"
1943 				"this file from Ogg FLAC to something else, use -d.  If you meant to re-encode\n"
1944 				"this file from Ogg FLAC to Ogg FLAC again, use -f to force writing to the same\n"
1945 				"file, or -o to specify a different output filename.\n",
1946 				outfilename
1947 			);
1948 		}
1949 		else
1950 			flac__utils_printf(stderr, 1, "ERROR: output file %s already exists, use -f to override\n", outfilename);
1951 		conditional_fclose(encode_infile);
1952 		return 1;
1953 	}
1954 
1955 	if(option_values.format_input_size >= 0) {
1956 	   	if (input_format != FORMAT_RAW || infilesize >= 0) {
1957 			flac__utils_printf(stderr, 1, "ERROR: can only use --input-size when encoding raw samples from stdin\n");
1958 			conditional_fclose(encode_infile);
1959 			return 1;
1960 		}
1961 		else {
1962 			infilesize = option_values.format_input_size;
1963 		}
1964 	}
1965 
1966 	if(option_values.sector_align && (input_format == FORMAT_FLAC || input_format == FORMAT_OGGFLAC)) {
1967 		flac__utils_printf(stderr, 1, "ERROR: can't use --sector-align when the input file is FLAC or Ogg FLAC\n");
1968 		conditional_fclose(encode_infile);
1969 		return 1;
1970 	}
1971 	if(option_values.sector_align && input_format == FORMAT_RAW && infilesize < 0) {
1972 		flac__utils_printf(stderr, 1, "ERROR: can't use --sector-align when the input size is unknown\n");
1973 		conditional_fclose(encode_infile);
1974 		return 1;
1975 	}
1976 
1977 	if(input_format == FORMAT_RAW) {
1978 		if(option_values.format_is_big_endian < 0 || option_values.format_is_unsigned_samples < 0 || option_values.format_channels < 0 || option_values.format_bps < 0 || option_values.format_sample_rate < 0) {
1979 			conditional_fclose(encode_infile);
1980 			return usage_error("ERROR: for encoding a raw file you must specify a value for --endian, --sign, --channels, --bps, and --sample-rate\n");
1981 		}
1982 	}
1983 	else {
1984 		if(option_values.format_is_big_endian >= 0 || option_values.format_is_unsigned_samples >= 0 || option_values.format_channels >= 0 || option_values.format_bps >= 0 || option_values.format_sample_rate >= 0) {
1985 			conditional_fclose(encode_infile);
1986 			return usage_error("ERROR: raw format options (--endian, --sign, --channels, --bps, and --sample-rate) are not allowed for non-raw input\n");
1987 		}
1988 	}
1989 
1990 	if(option_values.force_to_stdout) {
1991 		if(option_values.replay_gain) {
1992 			conditional_fclose(encode_infile);
1993 			return usage_error("ERROR: --replay-gain cannot be used when encoding to stdout\n");
1994 		}
1995 	}
1996 	if(option_values.replay_gain && option_values.use_ogg) {
1997 		conditional_fclose(encode_infile);
1998 		return usage_error("ERROR: --replay-gain cannot be used when encoding to Ogg FLAC yet\n");
1999 	}
2000 
2001 	if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &encode_options.skip_specification) || encode_options.skip_specification.is_relative) {
2002 		conditional_fclose(encode_infile);
2003 		return usage_error("ERROR: invalid value for --skip\n");
2004 	}
2005 
2006 	if(!flac__utils_parse_skip_until_specification(option_values.until_specification, &encode_options.until_specification)) { /*@@@@ more checks: no + without --skip, no - unless known total_samples_to_{en,de}code */
2007 		conditional_fclose(encode_infile);
2008 		return usage_error("ERROR: invalid value for --until\n");
2009 	}
2010 	/* if there is no "--until" we want to default to "--until=-0" */
2011 	if(0 == option_values.until_specification)
2012 		encode_options.until_specification.is_relative = true;
2013 
2014 	encode_options.verify = option_values.verify;
2015 	encode_options.treat_warnings_as_errors = option_values.treat_warnings_as_errors;
2016 #if FLAC__HAS_OGG
2017 	encode_options.use_ogg = option_values.use_ogg;
2018 	/* set a random serial number if one has not yet been specified */
2019 	if(!option_values.has_serial_number) {
2020 		option_values.serial_number = rand();
2021 		option_values.has_serial_number = true;
2022 	}
2023 	encode_options.serial_number = option_values.serial_number++;
2024 #endif
2025 	encode_options.lax = option_values.lax;
2026 	encode_options.padding = option_values.padding;
2027 	encode_options.num_compression_settings = option_values.num_compression_settings;
2028 	FLAC__ASSERT(sizeof(encode_options.compression_settings) >= sizeof(option_values.compression_settings));
2029 	memcpy(encode_options.compression_settings, option_values.compression_settings, sizeof(option_values.compression_settings));
2030 	encode_options.requested_seek_points = option_values.requested_seek_points;
2031 	encode_options.num_requested_seek_points = option_values.num_requested_seek_points;
2032 	encode_options.cuesheet_filename = option_values.cuesheet_filename;
2033 	encode_options.continue_through_decode_errors = option_values.continue_through_decode_errors;
2034 	encode_options.cued_seekpoints = option_values.cued_seekpoints;
2035 	encode_options.channel_map_none = option_values.channel_map_none;
2036 	encode_options.is_first_file = is_first_file;
2037 	encode_options.is_last_file = is_last_file;
2038 	encode_options.align_reservoir = align_reservoir;
2039 	encode_options.align_reservoir_samples = &align_reservoir_samples;
2040 	encode_options.replay_gain = option_values.replay_gain;
2041 	encode_options.ignore_chunk_sizes = option_values.ignore_chunk_sizes;
2042 	encode_options.sector_align = option_values.sector_align;
2043 	encode_options.vorbis_comment = option_values.vorbis_comment;
2044 	FLAC__ASSERT(sizeof(encode_options.pictures) >= sizeof(option_values.pictures));
2045 	memcpy(encode_options.pictures, option_values.pictures, sizeof(option_values.pictures));
2046 	encode_options.num_pictures = option_values.num_pictures;
2047 	encode_options.format = input_format;
2048 	encode_options.debug.disable_constant_subframes = option_values.debug.disable_constant_subframes;
2049 	encode_options.debug.disable_fixed_subframes = option_values.debug.disable_fixed_subframes;
2050 	encode_options.debug.disable_verbatim_subframes = option_values.debug.disable_verbatim_subframes;
2051 	encode_options.debug.do_md5 = option_values.debug.do_md5;
2052 	encode_options.error_on_compression_fail = option_values.error_on_compression_fail;
2053 	encode_options.limit_min_bitrate = option_values.limit_min_bitrate;
2054 	encode_options.relaxed_foreign_metadata_handling = option_values.keep_foreign_metadata_if_present;
2055 
2056 	/* if infilename and outfilename point to the same file, we need to write to a temporary file */
2057 	if(encode_infile != stdin && grabbag__file_are_same(infilename, outfilename)) {
2058 		static const char *tmp_suffix = ".tmp,fl-ac+en'c";
2059 		size_t dest_len = strlen(outfilename) + strlen(tmp_suffix) + 1;
2060 		/*@@@@ still a remote possibility that a file with this filename exists */
2061 		if((internal_outfilename = safe_malloc_(dest_len)) == NULL) {
2062 			flac__utils_printf(stderr, 1, "ERROR allocating memory for tempfile name\n");
2063 			conditional_fclose(encode_infile);
2064 			return 1;
2065 		}
2066 		flac_snprintf(internal_outfilename, dest_len, "%s%s", outfilename, tmp_suffix);
2067 	}
2068 
2069 	if(input_format == FORMAT_RAW) {
2070 		encode_options.format_options.raw.is_big_endian = option_values.format_is_big_endian;
2071 		encode_options.format_options.raw.is_unsigned_samples = option_values.format_is_unsigned_samples;
2072 		encode_options.format_options.raw.channels = option_values.format_channels;
2073 		encode_options.format_options.raw.bps = option_values.format_bps;
2074 		encode_options.format_options.raw.sample_rate = option_values.format_sample_rate;
2075 
2076 		retval = flac__encode_file(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, encode_options);
2077 	}
2078 	else if(input_format == FORMAT_FLAC || input_format == FORMAT_OGGFLAC) {
2079 		retval = flac__encode_file(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, encode_options);
2080 	}
2081 	else if(input_format == FORMAT_WAVE || input_format == FORMAT_WAVE64 || input_format == FORMAT_RF64 || input_format == FORMAT_AIFF || input_format == FORMAT_AIFF_C) {
2082 		encode_options.format_options.iff.foreign_metadata = 0;
2083 
2084 		/* initialize foreign metadata if requested */
2085 		if(option_values.keep_foreign_metadata || option_values.keep_foreign_metadata_if_present) {
2086 			encode_options.format_options.iff.foreign_metadata =
2087 				flac__foreign_metadata_new(
2088 					input_format==FORMAT_WAVE || input_format==FORMAT_RF64?
2089 						FOREIGN_BLOCK_TYPE__RIFF :
2090 					input_format==FORMAT_WAVE64?
2091 						FOREIGN_BLOCK_TYPE__WAVE64 :
2092 						FOREIGN_BLOCK_TYPE__AIFF
2093 				);
2094 			if(0 == encode_options.format_options.iff.foreign_metadata) {
2095 				flac__utils_printf(stderr, 1, "ERROR: creating foreign metadata object\n");
2096 				conditional_fclose(encode_infile);
2097 				if(internal_outfilename != 0)
2098 					free(internal_outfilename);
2099 				return 1;
2100 			}
2101 		}
2102 
2103 		retval = flac__encode_file(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, encode_options);
2104 
2105 		if(encode_options.format_options.iff.foreign_metadata)
2106 			flac__foreign_metadata_delete(encode_options.format_options.iff.foreign_metadata);
2107 	}
2108 	else {
2109 		FLAC__ASSERT(0);
2110 		retval = 1; /* double protection */
2111 	}
2112 
2113 	if(retval == 0) {
2114 		if(strcmp(outfilename, "-")) {
2115 			if(option_values.replay_gain) {
2116 				float title_gain, title_peak;
2117 				const char *error;
2118 				grabbag__replaygain_get_title(&title_gain, &title_peak);
2119 				if(
2120 					0 != (error = grabbag__replaygain_store_to_file_reference(internal_outfilename? internal_outfilename : outfilename, option_values.preserve_modtime)) ||
2121 					0 != (error = grabbag__replaygain_store_to_file_title(internal_outfilename? internal_outfilename : outfilename, title_gain, title_peak, option_values.preserve_modtime))
2122 				) {
2123 					flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain reference/title tags (%s)\n", outfilename, error);
2124 					retval = 1;
2125 				}
2126 			}
2127 			if(option_values.preserve_modtime && strcmp(infilename, "-"))
2128 				grabbag__file_copy_metadata(infilename, internal_outfilename? internal_outfilename : outfilename);
2129 		}
2130 	}
2131 
2132 	/* rename temporary file if necessary */
2133 	if(retval == 0 && internal_outfilename != 0) {
2134 		if(flac_rename(internal_outfilename, outfilename) < 0) {
2135 #if defined _MSC_VER || defined __MINGW32__ || defined __EMX__
2136 			/* on some flavors of windows, flac_rename() will fail if the destination already exists, so we unlink and try again */
2137 			if(flac_unlink(outfilename) < 0) {
2138 				flac__utils_printf(stderr, 1, "ERROR: moving new FLAC file %s back on top of original FLAC file %s, keeping both\n", internal_outfilename, outfilename);
2139 				retval = 1;
2140 			}
2141 			else if(flac_rename(internal_outfilename, outfilename) < 0) {
2142 				flac__utils_printf(stderr, 1, "ERROR: moving new FLAC file %s back on top of original FLAC file %s, you must do it\n", internal_outfilename, outfilename);
2143 				retval = 1;
2144 			}
2145 #else
2146 			flac__utils_printf(stderr, 1, "ERROR: moving new FLAC file %s back on top of original FLAC file %s, keeping both\n", internal_outfilename, outfilename);
2147 			retval = 1;
2148 #endif
2149 		}
2150 	}
2151 
2152 	/* handle --delete-input-file, but don't want to delete if piping from stdin, or if input filename and output filename are the same */
2153 	if(retval == 0 && option_values.delete_input && strcmp(infilename, "-") && internal_outfilename == 0)
2154 		flac_unlink(infilename);
2155 
2156 	if(internal_outfilename != 0)
2157 		free(internal_outfilename);
2158 
2159 	return retval;
2160 }
2161 
decode_file(const char * infilename)2162 int decode_file(const char *infilename)
2163 {
2164 	int retval;
2165 	FLAC__bool treat_as_ogg = false;
2166 	FileFormat output_format = FORMAT_WAVE;
2167 	FileSubFormat output_subformat = SUBFORMAT_UNSPECIFIED;
2168 	decode_options_t decode_options;
2169 	foreign_metadata_t *foreign_metadata = 0;
2170 	const char *outfilename = get_outfilename(infilename, ".    "); /* Placeholder until we know what the actual suffix is */
2171 	size_t infilename_length;
2172 
2173 	if(0 == outfilename) {
2174 		flac__utils_printf(stderr, 1, "ERROR: filename too long: %s", infilename);
2175 		return 1;
2176 	}
2177 
2178 	if(!option_values.analyze && !option_values.test_only &&(option_values.keep_foreign_metadata || option_values.keep_foreign_metadata_if_present)) {
2179 		const char *error;
2180 		if(0 == strcmp(infilename, "-") || 0 == strcmp(outfilename, "-"))
2181 			return usage_error("ERROR: --keep-foreign-metadata cannot be used when decoding from stdin or to stdout\n");
2182 		if(output_format == FORMAT_RAW)
2183 			return usage_error("ERROR: --keep-foreign-metadata cannot be used with raw output\n");
2184 		decode_options.format_options.iff.foreign_metadata = 0;
2185 		/* initialize foreign metadata structure */
2186 		foreign_metadata = flac__foreign_metadata_new(FOREIGN_BLOCK_TYPE__RIFF); /* RIFF is just a placeholder */
2187 		if(0 == foreign_metadata) {
2188 			flac__utils_printf(stderr, 1, "ERROR: creating foreign metadata object\n");
2189 			return 1;
2190 		}
2191 		if(!flac__foreign_metadata_read_from_flac(foreign_metadata, infilename, &error)) {
2192 			if(option_values.keep_foreign_metadata_if_present) {
2193 				flac__utils_printf(stderr, 1, "%s: WARNING reading foreign metadata: %s\n", infilename, error);
2194 				if(option_values.treat_warnings_as_errors) {
2195 					flac__foreign_metadata_delete(foreign_metadata);
2196 					return 1;
2197 				}
2198 				else {
2199 					/* Couldn't find foreign metadata, stop processing */
2200 					flac__foreign_metadata_delete(foreign_metadata);
2201 					foreign_metadata = 0;
2202 				}
2203 			}
2204 			else {
2205 				flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", infilename, error);
2206 				flac__foreign_metadata_delete(foreign_metadata);
2207 				return 1;
2208 			}
2209 		}
2210 	}
2211 
2212 	if(option_values.force_raw_format)
2213 		output_format = FORMAT_RAW;
2214 	else if(
2215 		option_values.force_aiff_format ||
2216 		(strlen(outfilename) >= 4 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-4), ".aif")) ||
2217 		(strlen(outfilename) >= 5 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-5), ".aiff"))
2218 	)
2219 		output_format = FORMAT_AIFF;
2220 	else if(
2221 		option_values.force_rf64_format ||
2222 		(strlen(outfilename) >= 5 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-5), ".rf64"))
2223 	)
2224 		output_format = FORMAT_RF64;
2225 	else if(
2226 		option_values.force_wave64_format ||
2227 		(strlen(outfilename) >= 4 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-4), ".w64"))
2228 	)
2229 		output_format = FORMAT_WAVE64;
2230 	else if(foreign_metadata != NULL) {
2231 		/* Pick a format based on what the foreign metadata contains */
2232 		if(foreign_metadata->type == FOREIGN_BLOCK_TYPE__WAVE64)
2233 			output_format = FORMAT_WAVE64;
2234 		else if(foreign_metadata->is_rf64)
2235 			output_format = FORMAT_RF64;
2236 		else if(foreign_metadata->type == FOREIGN_BLOCK_TYPE__AIFF) {
2237 			output_format = FORMAT_AIFF;
2238 			if(foreign_metadata->is_aifc) {
2239 				output_format = FORMAT_AIFF_C;
2240 			}
2241 		}
2242 		else
2243 			output_format = FORMAT_WAVE;
2244 	}
2245 	else
2246 		output_format = FORMAT_WAVE;
2247 
2248 	/* Now do subformats */
2249 	if(option_values.force_legacy_wave_format)
2250 		output_subformat = SUBFORMAT_WAVE_PCM;
2251 	else if(option_values.force_extensible_wave_format)
2252 		output_subformat = SUBFORMAT_WAVE_EXTENSIBLE;
2253 	else if(option_values.force_aiff_c_none_format) {
2254 		output_format = FORMAT_AIFF_C;
2255 		output_subformat = SUBFORMAT_AIFF_C_NONE;
2256 	}
2257 	else if(option_values.force_aiff_c_sowt_format) {
2258 		output_format = FORMAT_AIFF_C;
2259 		output_subformat = SUBFORMAT_AIFF_C_SOWT;
2260 	}
2261 	else if(foreign_metadata != NULL) {
2262 		if(foreign_metadata->is_wavefmtex)
2263 			output_subformat = SUBFORMAT_WAVE_EXTENSIBLE;
2264 		else if(output_format == FORMAT_WAVE)
2265 			output_subformat = SUBFORMAT_WAVE_PCM;
2266 		else if(foreign_metadata->is_aifc) {
2267 			if(foreign_metadata->is_sowt)
2268 				output_subformat = SUBFORMAT_AIFF_C_SOWT;
2269 			else
2270 				output_subformat = SUBFORMAT_AIFF_C_NONE;
2271 		}
2272 	}
2273 
2274 
2275 	/* Check whether output format agrees with foreign metadata */
2276 	if(foreign_metadata != NULL) {
2277 		if((output_format != FORMAT_WAVE && output_format != FORMAT_RF64) && foreign_metadata->type == FOREIGN_BLOCK_TYPE__RIFF) {
2278 			flac__foreign_metadata_delete(foreign_metadata);
2279 			return usage_error("ERROR: foreign metadata type RIFF cannot be restored to a%s file, only to WAVE and RF64\n",FileFormatString[output_format]);
2280 		}
2281 		if((output_format != FORMAT_AIFF && output_format != FORMAT_AIFF_C) && foreign_metadata->type == FOREIGN_BLOCK_TYPE__AIFF) {
2282 			flac__foreign_metadata_delete(foreign_metadata);
2283 			return usage_error("ERROR: foreign metadata type AIFF cannot be restored to a%s file, only to AIFF and AIFF-C\n",FileFormatString[output_format]);
2284 		}
2285 		if(output_format != FORMAT_WAVE64 && foreign_metadata->type == FOREIGN_BLOCK_TYPE__WAVE64) {
2286 			flac__foreign_metadata_delete(foreign_metadata);
2287 			return usage_error("ERROR: foreign metadata type Wave64 cannot be restored to a%s file, only to Wave64\n",FileFormatString[output_format]);
2288 		}
2289 	}
2290 
2291 	/* Now reassemble outfilename */
2292 	get_decoded_outfilename(infilename, output_format);
2293 
2294 	/*
2295 	 * Error if output file already exists (and -f not used).
2296 	 * Use grabbag__file_get_filesize() as a cheap way to check.
2297 	 */
2298 	if(!option_values.test_only && !option_values.force_file_overwrite && strcmp(outfilename, "-") && grabbag__file_get_filesize(outfilename) != (FLAC__off_t)(-1)) {
2299 		flac__utils_printf(stderr, 1, "ERROR: output file %s already exists, use -f to override\n", outfilename);
2300 		flac__foreign_metadata_delete(foreign_metadata);
2301 		return 1;
2302 	}
2303 
2304 	if(!option_values.test_only && !option_values.analyze) {
2305 		if(output_format == FORMAT_RAW && (option_values.format_is_big_endian < 0 || option_values.format_is_unsigned_samples < 0)) {
2306 			flac__foreign_metadata_delete(foreign_metadata);
2307 			return usage_error("ERROR: for decoding to a raw file you must specify a value for --endian and --sign\n");
2308 		}
2309 	}
2310 
2311 	infilename_length = strlen(infilename);
2312 	if(option_values.use_ogg)
2313 		treat_as_ogg = true;
2314 	else if(infilename_length >= 4 && 0 == FLAC__STRCASECMP(infilename+(infilename_length-4), ".oga"))
2315 		treat_as_ogg = true;
2316 	else if(infilename_length >= 4 && 0 == FLAC__STRCASECMP(infilename+(infilename_length-4), ".ogg"))
2317 		treat_as_ogg = true;
2318 	else
2319 		treat_as_ogg = false;
2320 
2321 #if !FLAC__HAS_OGG
2322 	if(treat_as_ogg) {
2323 		flac__utils_printf(stderr, 1, "%s: Ogg support has not been built into this copy of flac\n", infilename);
2324 		flac__foreign_metadata_delete(foreign_metadata);
2325 		return 1;
2326 	}
2327 #endif
2328 
2329 	if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &decode_options.skip_specification) || decode_options.skip_specification.is_relative) {
2330 		flac__foreign_metadata_delete(foreign_metadata);
2331 		return usage_error("ERROR: invalid value for --skip\n");
2332 	}
2333 
2334 	if(!flac__utils_parse_skip_until_specification(option_values.until_specification, &decode_options.until_specification)) { /*@@@ more checks: no + without --skip, no - unless known total_samples_to_{en,de}code */
2335 		flac__foreign_metadata_delete(foreign_metadata);
2336 		return usage_error("ERROR: invalid value for --until\n");
2337 	}
2338 	/* if there is no "--until" we want to default to "--until=-0" */
2339 	if(0 == option_values.until_specification)
2340 		decode_options.until_specification.is_relative = true;
2341 
2342 	if(option_values.cue_specification) {
2343 		if(!flac__utils_parse_cue_specification(option_values.cue_specification, &decode_options.cue_specification)) {
2344 			flac__foreign_metadata_delete(foreign_metadata);
2345 			return usage_error("ERROR: invalid value for --cue\n");
2346 		}
2347 		decode_options.has_cue_specification = true;
2348 	}
2349 	else
2350 		decode_options.has_cue_specification = false;
2351 
2352 	decode_options.treat_warnings_as_errors = option_values.treat_warnings_as_errors;
2353 	decode_options.continue_through_decode_errors = option_values.continue_through_decode_errors;
2354 	decode_options.relaxed_foreign_metadata_handling = option_values.keep_foreign_metadata_if_present;
2355 	decode_options.replaygain_synthesis_spec = option_values.replaygain_synthesis_spec;
2356 	decode_options.force_subformat = output_subformat;
2357 #if FLAC__HAS_OGG
2358 	decode_options.is_ogg = treat_as_ogg;
2359 	decode_options.use_first_serial_number = !option_values.has_serial_number;
2360 	decode_options.serial_number = option_values.serial_number;
2361 #endif
2362 	decode_options.channel_map_none = option_values.channel_map_none;
2363 	decode_options.format = output_format;
2364 
2365 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2366 	/* Can't fuzz from stdin */
2367 	if(0 == strcmp(infilename, "-") || 0 == strcmp(outfilename, "-"))
2368 		return 1;
2369 #endif
2370 
2371 	if(output_format == FORMAT_RAW) {
2372 		decode_options.format_options.raw.is_big_endian = option_values.format_is_big_endian;
2373 		decode_options.format_options.raw.is_unsigned_samples = option_values.format_is_unsigned_samples;
2374 
2375 		retval = flac__decode_file(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, decode_options);
2376 	}
2377 	else {
2378 		decode_options.format_options.iff.foreign_metadata = foreign_metadata;
2379 
2380 		retval = flac__decode_file(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, decode_options);
2381 
2382 	}
2383 
2384 	if(foreign_metadata)
2385 		flac__foreign_metadata_delete(foreign_metadata);
2386 
2387 	if(retval == 0 && strcmp(infilename, "-")) {
2388 		if(option_values.preserve_modtime && strcmp(outfilename, "-"))
2389 			grabbag__file_copy_metadata(infilename, outfilename);
2390 		if(option_values.delete_input && !option_values.test_only && !option_values.analyze)
2391 			flac_unlink(infilename);
2392 	}
2393 
2394 	return retval;
2395 }
2396 
get_encoded_outfilename(const char * infilename)2397 const char *get_encoded_outfilename(const char *infilename)
2398 {
2399 	const char *suffix = (option_values.use_ogg? ".oga" : ".flac");
2400 	const char *p;
2401 
2402 	if(option_values.output_prefix) {
2403 		p = grabbag__file_get_basename(infilename);
2404 	}
2405 	else {
2406 		p = infilename;
2407 	}
2408 
2409 	return get_outfilename(p, suffix);
2410 }
2411 
get_decoded_outfilename(const char * infilename,const FileFormat format)2412 const char *get_decoded_outfilename(const char *infilename, const FileFormat format)
2413 {
2414 	const char *suffix;
2415 	const char *p;
2416 
2417 	if(option_values.output_prefix) {
2418 		p = grabbag__file_get_basename(infilename);
2419 	}
2420 	else {
2421 		p = infilename;
2422 	}
2423 
2424 	if(option_values.analyze) {
2425 		suffix = ".ana";
2426 	}
2427 	else if(format == FORMAT_RAW) {
2428 		suffix = ".raw";
2429 	}
2430 	else if(format == FORMAT_AIFF) {
2431 		suffix = ".aiff";
2432 	}
2433 	else if(format == FORMAT_AIFF_C) {
2434 		suffix = ".aifc";
2435 	}
2436 	else if(format == FORMAT_RF64) {
2437 		suffix = ".rf64";
2438 	}
2439 	else if(format == FORMAT_WAVE64) {
2440 		suffix = ".w64";
2441 	}
2442 	else {
2443 		suffix = ".wav";
2444 	}
2445 	return get_outfilename(p, suffix);
2446 }
2447 
get_outfilename(const char * infilename,const char * suffix)2448 const char *get_outfilename(const char *infilename, const char *suffix)
2449 {
2450 	if(0 == option_values.cmdline_forced_outfilename) {
2451 		static char buffer[4096];
2452 
2453 		if(0 == strcmp(infilename, "-") || option_values.force_to_stdout) {
2454 			buffer [0] = '-';
2455 			buffer [1] = 0;
2456 		}
2457 		else {
2458 			char *p;
2459 			if (flac__strlcpy(buffer, option_values.output_prefix? option_values.output_prefix : "", sizeof buffer) >= sizeof buffer)
2460 				return 0;
2461 			if (flac__strlcat(buffer, infilename, sizeof buffer) >= sizeof buffer)
2462 				return 0;
2463 			/* the . must come after any / to avoid problems with, e.g. "some.directory/extensionless-filename" */
2464 			if(0 == (p = strrchr(buffer, '.')) || strchr(p, '/')) {
2465 				if (flac__strlcat(buffer, suffix, sizeof buffer) >= sizeof buffer)
2466 					return 0;
2467 			}
2468 			else {
2469 				*p = '\0';
2470 				if (flac__strlcat(buffer, suffix, sizeof buffer) >= sizeof buffer)
2471 					return 0;
2472 			}
2473 		}
2474 		return buffer;
2475 	}
2476 	else
2477 		return option_values.cmdline_forced_outfilename;
2478 }
2479 
die(const char * message)2480 void die(const char *message)
2481 {
2482 	FLAC__ASSERT(0 != message);
2483 	flac__utils_printf(stderr, 1, "ERROR: %s\n", message);
2484 	exit(1);
2485 }
2486 
conditional_fclose(FILE * f)2487 int conditional_fclose(FILE *f)
2488 {
2489 	if(f == 0 || f == stdin || f == stdout)
2490 		return 0;
2491 	else
2492 		return fclose(f);
2493 }
2494 
local_strdup(const char * source)2495 char *local_strdup(const char *source)
2496 {
2497 	char *ret;
2498 	FLAC__ASSERT(0 != source);
2499 	if(0 == (ret = strdup(source)))
2500 		die("out of memory during strdup()");
2501 	return ret;
2502 }
2503