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