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