fix bug: -a and -t were not prevented from being used together (sf #1229481: https...
[platform/upstream/flac.git] / src / flac / main.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001,2002,2003,2004,2005  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 #include <ctype.h>
20 #include <locale.h>
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <time.h>
26
27 #ifdef HAVE_CONFIG_H
28 #include <config.h>
29 #endif
30
31 #if !defined _MSC_VER && !defined __MINGW32__
32 /* unlink is in stdio.h in VC++ */
33 #include <unistd.h> /* for unlink() */
34 #else
35 #define strcasecmp stricmp
36 #endif
37 #include "FLAC/all.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 0
47 /*[JEC] was:#if HAVE_GETOPT_LONG*/
48 /*[JEC] see flac/include/share/getopt.h as to why the change */
49 #  include <getopt.h>
50 #else
51 #  include "share/getopt.h"
52 #endif
53
54 typedef enum { RAW, WAV, AIF } FileFormat;
55
56 static int do_it();
57
58 static FLAC__bool init_options();
59 static int parse_options(int argc, char *argv[]);
60 static int parse_option(int short_option, const char *long_option, const char *option_argument);
61 static void free_options();
62
63 static int usage_error(const char *message, ...);
64 static void short_usage();
65 static void show_version();
66 static void show_help();
67 static void show_explain();
68 static void format_mistake(const char *infilename, const char *wrong, const char *right);
69
70 static int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_last_file);
71 static int decode_file(const char *infilename);
72
73 static const char *get_encoded_outfilename(const char *infilename);
74 static const char *get_decoded_outfilename(const char *infilename);
75 static const char *get_outfilename(const char *infilename, const char *suffix);
76
77 static void die(const char *message);
78 static char *local_strdup(const char *source);
79
80
81 /*
82  * share__getopt format struct; note that for long options with no
83  * short option equivalent we just set the 'val' field to 0.
84  */
85 static struct share__option long_options_[] = {
86         /*
87          * general options
88          */
89         { "help"             , share__no_argument, 0, 'h' },
90         { "explain"          , share__no_argument, 0, 'H' },
91         { "version"          , share__no_argument, 0, 'v' },
92         { "decode"           , share__no_argument, 0, 'd' },
93         { "analyze"          , share__no_argument, 0, 'a' },
94         { "test"             , share__no_argument, 0, 't' },
95         { "stdout"           , share__no_argument, 0, 'c' },
96         { "silent"           , share__no_argument, 0, 's' },
97         { "totally-silent"   , share__no_argument, 0, 0 },
98         { "force"            , share__no_argument, 0, 'f' },
99         { "delete-input-file", share__no_argument, 0, 0 },
100         { "output-prefix"    , share__required_argument, 0, 0 },
101         { "output-name"      , share__required_argument, 0, 'o' },
102         { "skip"             , share__required_argument, 0, 0 },
103         { "until"            , share__required_argument, 0, 0 },
104
105         /*
106          * decoding options
107          */
108         { "decode-through-errors", share__no_argument, 0, 'F' },
109         { "cue"                  , share__required_argument, 0, 0 },
110         { "apply-replaygain-which-is-not-lossless", share__optional_argument, 0, 0 }, /* undocumented */
111
112         /*
113          * encoding options
114          */
115         { "cuesheet"                  , share__required_argument, 0, 0 },
116         { "no-cued-seekpoints"        , share__no_argument, 0, 0 },
117         { "tag"                       , share__required_argument, 0, 'T' },
118         { "compression-level-0"       , share__no_argument, 0, '0' },
119         { "compression-level-1"       , share__no_argument, 0, '1' },
120         { "compression-level-2"       , share__no_argument, 0, '2' },
121         { "compression-level-3"       , share__no_argument, 0, '3' },
122         { "compression-level-4"       , share__no_argument, 0, '4' },
123         { "compression-level-5"       , share__no_argument, 0, '5' },
124         { "compression-level-6"       , share__no_argument, 0, '6' },
125         { "compression-level-7"       , share__no_argument, 0, '7' },
126         { "compression-level-8"       , share__no_argument, 0, '8' },
127         { "compression-level-9"       , share__no_argument, 0, '9' },
128         { "best"                      , share__no_argument, 0, '8' },
129         { "fast"                      , share__no_argument, 0, '0' },
130         { "super-secret-totally-impractical-compression-level", share__no_argument, 0, 0 },
131         { "verify"                    , share__no_argument, 0, 'V' },
132         { "force-aiff-format"         , share__no_argument, 0, 0 },
133         { "force-raw-format"          , share__no_argument, 0, 0 },
134         { "lax"                       , share__no_argument, 0, 0 },
135         { "replay-gain"               , share__no_argument, 0, 0 },
136         { "sector-align"              , share__no_argument, 0, 0 },
137         { "seekpoint"                 , share__required_argument, 0, 'S' },
138         { "padding"                   , share__required_argument, 0, 'P' },
139 #ifdef FLAC__HAS_OGG
140         { "ogg"                       , share__no_argument, 0, 0 },
141         { "serial-number"             , share__required_argument, 0, 0 },
142 #endif
143         { "blocksize"                 , share__required_argument, 0, 'b' },
144         { "exhaustive-model-search"   , share__no_argument, 0, 'e' },
145         { "max-lpc-order"             , share__required_argument, 0, 'l' },
146         { "mid-side"                  , share__no_argument, 0, 'm' },
147         { "adaptive-mid-side"         , share__no_argument, 0, 'M' },
148         { "qlp-coeff-precision-search", share__no_argument, 0, 'p' },
149         { "qlp-coeff-precision"       , share__required_argument, 0, 'q' },
150         { "rice-partition-order"      , share__required_argument, 0, 'r' },
151         { "endian"                    , share__required_argument, 0, 0 },
152         { "channels"                  , share__required_argument, 0, 0 },
153         { "bps"                       , share__required_argument, 0, 0 },
154         { "sample-rate"               , share__required_argument, 0, 0 },
155         { "sign"                      , share__required_argument, 0, 0 },
156         { "input-size"                , share__required_argument, 0, 0 },
157
158         /*
159          * analysis options
160          */
161         { "residual-gnuplot", share__no_argument, 0, 0 },
162         { "residual-text", share__no_argument, 0, 0 },
163
164         /*
165          * negatives
166          */
167         { "no-decode-through-errors"  , share__no_argument, 0, 0 },
168         { "no-silent"                 , share__no_argument, 0, 0 },
169         { "no-force"                  , share__no_argument, 0, 0 },
170         { "no-seektable"              , share__no_argument, 0, 0 },
171         { "no-delete-input-file"      , share__no_argument, 0, 0 },
172         { "no-replay-gain"            , share__no_argument, 0, 0 },
173         { "no-sector-align"           , share__no_argument, 0, 0 },
174         { "no-lax"                    , share__no_argument, 0, 0 },
175 #ifdef FLAC__HAS_OGG
176         { "no-ogg"                    , share__no_argument, 0, 0 },
177 #endif
178         { "no-exhaustive-model-search", share__no_argument, 0, 0 },
179         { "no-mid-side"               , share__no_argument, 0, 0 },
180         { "no-adaptive-mid-side"      , share__no_argument, 0, 0 },
181         { "no-qlp-coeff-prec-search"  , share__no_argument, 0, 0 },
182         { "no-padding"                , share__no_argument, 0, 0 },
183         { "no-verify"                 , share__no_argument, 0, 0 },
184         { "no-residual-gnuplot"       , share__no_argument, 0, 0 },
185         { "no-residual-text"          , share__no_argument, 0, 0 },
186         /*
187          * undocumented debugging options for the test suite
188          */
189         { "disable-constant-subframes", share__no_argument, 0, 0 },
190         { "disable-fixed-subframes"   , share__no_argument, 0, 0 },
191         { "disable-verbatim-subframes", share__no_argument, 0, 0 },
192
193         {0, 0, 0, 0}
194 };
195
196
197 /*
198  * global to hold command-line option values
199  */
200
201 static struct {
202         FLAC__bool show_help;
203         FLAC__bool show_explain;
204         FLAC__bool show_version;
205         FLAC__bool mode_decode;
206         FLAC__bool verify;
207         FLAC__bool force_file_overwrite;
208         FLAC__bool continue_through_decode_errors;
209         replaygain_synthesis_spec_t replaygain_synthesis_spec;
210         FLAC__bool lax;
211         FLAC__bool test_only;
212         FLAC__bool analyze;
213         FLAC__bool use_ogg;
214         FLAC__bool has_serial_number; /* true iff --serial-number was used */
215         long serial_number; /* this is the Ogg serial number and is unused for native FLAC */
216         FLAC__bool do_mid_side;
217         FLAC__bool loose_mid_side;
218         FLAC__bool do_exhaustive_model_search;
219         FLAC__bool do_escape_coding;
220         FLAC__bool do_qlp_coeff_prec_search;
221         FLAC__bool force_to_stdout;
222         FLAC__bool force_aiff_format;
223         FLAC__bool force_raw_format;
224         FLAC__bool delete_input;
225         FLAC__bool replay_gain;
226         FLAC__bool sector_align;
227         const char *cmdline_forced_outfilename;
228         const char *output_prefix;
229         analysis_options aopts;
230         int padding;
231         unsigned max_lpc_order;
232         unsigned qlp_coeff_precision;
233         const char *skip_specification;
234         const char *until_specification;
235         const char *cue_specification;
236         int format_is_big_endian;
237         int format_is_unsigned_samples;
238         int format_channels;
239         int format_bps;
240         int format_sample_rate;
241         long format_input_size;
242         int blocksize;
243         int min_residual_partition_order;
244         int max_residual_partition_order;
245         int rice_parameter_search_dist;
246         char requested_seek_points[50000]; /* bad MAGIC NUMBER but buffer overflow is checked */
247         int num_requested_seek_points; /* -1 => no -S options were given, 0 => -S- was given */
248         const char *cuesheet_filename;
249         FLAC__bool cued_seekpoints;
250
251         unsigned num_files;
252         char **filenames;
253
254         FLAC__StreamMetadata *vorbis_comment;
255
256         struct {
257                 FLAC__bool disable_constant_subframes;
258                 FLAC__bool disable_fixed_subframes;
259                 FLAC__bool disable_verbatim_subframes;
260         } debug;
261 } option_values;
262
263
264 /*
265  * miscellaneous globals
266  */
267
268 static FLAC__int32 align_reservoir_0[588], align_reservoir_1[588]; /* for carrying over samples from --sector-align */
269 static FLAC__int32 *align_reservoir[2] = { align_reservoir_0, align_reservoir_1 };
270 static unsigned align_reservoir_samples = 0; /* 0 .. 587 */
271
272
273 int main(int argc, char *argv[])
274 {
275         int retval = 0;
276
277         setlocale(LC_ALL, "");
278         if(!init_options()) {
279                 flac__utils_printf(stderr, 1, "ERROR: allocating memory\n");
280                 retval = 1;
281         }
282         else {
283                 if((retval = parse_options(argc, argv)) == 0)
284                         retval = do_it();
285         }
286
287         free_options();
288
289         return retval;
290 }
291
292 int do_it()
293 {
294         int retval = 0;
295
296         if(option_values.show_version) {
297                 show_version();
298                 return 0;
299         }
300         else if(option_values.show_explain) {
301                 show_explain();
302                 return 0;
303         }
304         else if(option_values.show_help) {
305                 show_help();
306                 return 0;
307         }
308         else {
309                 if(option_values.num_files == 0) {
310                         if(flac__utils_verbosity_ >= 1)
311                                 short_usage();
312                         return 0;
313                 }
314
315                 /*
316                  * tweak options; validate the values
317                  */
318                 if(!option_values.mode_decode) {
319                         if(option_values.blocksize < 0) {
320                                 if(option_values.max_lpc_order == 0)
321                                         option_values.blocksize = 1152;
322                                 else
323                                         option_values.blocksize = 4608;
324                         }
325                         if(option_values.max_residual_partition_order < 0) {
326                                 if(option_values.blocksize <= 1152)
327                                         option_values.max_residual_partition_order = 2;
328                                 else if(option_values.blocksize <= 2304)
329                                         option_values.max_residual_partition_order = 3;
330                                 else if(option_values.blocksize <= 4608)
331                                         option_values.max_residual_partition_order = 3;
332                                 else
333                                         option_values.max_residual_partition_order = 4;
334                                 option_values.min_residual_partition_order = option_values.max_residual_partition_order;
335                         }
336                         if(option_values.rice_parameter_search_dist < 0) {
337                                 option_values.rice_parameter_search_dist = 0;
338                         }
339                         if(0 != option_values.cue_specification)
340                                 return usage_error("ERROR: --cue is not allowed in test mode\n");
341                 }
342                 else {
343                         if(option_values.test_only) {
344                                 if(0 != option_values.skip_specification)
345                                         return usage_error("ERROR: --skip is not allowed in test mode\n");
346                                 if(0 != option_values.until_specification)
347                                         return usage_error("ERROR: --until is not allowed in test mode\n");
348                                 if(0 != option_values.cue_specification)
349                                         return usage_error("ERROR: --cue is not allowed in test mode\n");
350                                 if(0 != option_values.analyze)
351                                         return usage_error("ERROR: analysis mode (-a/--analyze) and test mode (-t/--test) cannot be used together\n");
352                         }
353                 }
354
355                 if(0 != option_values.cue_specification && (0 != option_values.skip_specification || 0 != option_values.until_specification))
356                         return usage_error("ERROR: --cue may not be combined with --skip or --until\n");
357
358                 FLAC__ASSERT(option_values.blocksize >= 0 || option_values.mode_decode);
359
360                 if(option_values.format_channels >= 0) {
361                         if(option_values.format_channels == 0 || (unsigned)option_values.format_channels > FLAC__MAX_CHANNELS)
362                                 return usage_error("ERROR: invalid number of channels '%u', must be > 0 and <= %u\n", option_values.format_channels, FLAC__MAX_CHANNELS);
363                 }
364                 if(option_values.format_bps >= 0) {
365                         if(option_values.format_bps != 8 && option_values.format_bps != 16 && option_values.format_bps != 24)
366                                 return usage_error("ERROR: invalid bits per sample '%u' (must be 8/16/24)\n", option_values.format_bps);
367                 }
368                 if(option_values.format_sample_rate >= 0) {
369                         if(!FLAC__format_sample_rate_is_valid(option_values.format_sample_rate))
370                                 return usage_error("ERROR: invalid sample rate '%u', must be > 0 and <= %u\n", option_values.format_sample_rate, FLAC__MAX_SAMPLE_RATE);
371                 }
372                 if(option_values.force_raw_format && option_values.force_aiff_format)
373                         return usage_error("ERROR: only one of --force-raw-format and --force-aiff-format allowed\n");
374                 if(option_values.mode_decode) {
375                         if(!option_values.force_raw_format) {
376                                 if(option_values.format_is_big_endian >= 0)
377                                         return usage_error("ERROR: --endian only allowed with --force-raw-format\n");
378                                 if(option_values.format_is_unsigned_samples >= 0)
379                                         return usage_error("ERROR: --sign only allowed with --force-raw-format\n");
380                         }
381                         if(option_values.format_channels >= 0)
382                                 return usage_error("ERROR: --channels not allowed with --decode\n");
383                         if(option_values.format_bps >= 0)
384                                 return usage_error("ERROR: --bps not allowed with --decode\n");
385                         if(option_values.format_sample_rate >= 0)
386                                 return usage_error("ERROR: --sample-rate not allowed with --decode\n");
387                 }
388                 if(!option_values.mode_decode && ((unsigned)option_values.blocksize < FLAC__MIN_BLOCK_SIZE || (unsigned)option_values.blocksize > FLAC__MAX_BLOCK_SIZE)) {
389                         return usage_error("ERROR: invalid blocksize '%u', must be >= %u and <= %u\n", (unsigned)option_values.blocksize, FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE);
390                 }
391                 if(option_values.qlp_coeff_precision > 0 && option_values.qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION) {
392                         return usage_error("ERROR: invalid value '%u' for qlp coeff precision, must be 0 or >= %u\n", option_values.qlp_coeff_precision, FLAC__MIN_QLP_COEFF_PRECISION);
393                 }
394
395                 if(option_values.sector_align) {
396                         if(option_values.mode_decode)
397                                 return usage_error("ERROR: --sector-align only allowed for encoding\n");
398                         if(0 != option_values.skip_specification)
399                                 return usage_error("ERROR: --sector-align not allowed with --skip\n");
400                         if(0 != option_values.until_specification)
401                                 return usage_error("ERROR: --sector-align not allowed with --until\n");
402                         if(0 != option_values.cue_specification)
403                                 return usage_error("ERROR: --sector-align not allowed with --cue\n");
404                         if(option_values.format_channels >= 0 && option_values.format_channels != 2)
405                                 return usage_error("ERROR: --sector-align can only be done with stereo input\n");
406                         if(option_values.format_bps >= 0 && option_values.format_bps != 16)
407                                 return usage_error("ERROR: --sector-align can only be done with 16-bit samples\n");
408                         if(option_values.format_sample_rate >= 0 && option_values.format_sample_rate != 44100)
409                                 return usage_error("ERROR: --sector-align can only be done with a sample rate of 44100\n");
410                 }
411                 if(option_values.replay_gain) {
412                         if(option_values.force_to_stdout)
413                                 return usage_error("ERROR: --replay-gain not allowed with -c/--stdout\n");
414                         if(option_values.mode_decode)
415                                 return usage_error("ERROR: --replay-gain only allowed for encoding\n");
416                         if(option_values.format_channels > 2)
417                                 return usage_error("ERROR: --replay-gain can only be done with mono/stereo input\n");
418                         if(option_values.format_sample_rate >= 0 && !grabbag__replaygain_is_valid_sample_frequency(option_values.format_sample_rate))
419                                 return usage_error("ERROR: invalid sample rate used with --replay-gain\n");
420                         /*
421                          * We want to reserve padding space for the ReplayGain
422                          * tags that we will set later, to avoid rewriting the
423                          * whole file.
424                          */
425                         if(option_values.padding < 0) {
426                                 flac__utils_printf(stderr, 1, "NOTE: --replay-gain may leave a small PADDING block even with --no-padding\n");
427                                 option_values.padding = GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED;
428                         }
429                         else {
430                                 option_values.padding += GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED;
431                         }
432                 }
433                 if(option_values.num_files > 1 && option_values.cmdline_forced_outfilename) {
434                         return usage_error("ERROR: -o/--output-name cannot be used with multiple files\n");
435                 }
436                 if(option_values.cmdline_forced_outfilename && option_values.output_prefix) {
437                         return usage_error("ERROR: --output-prefix conflicts with -o/--output-name\n");
438                 }
439                 if(!option_values.mode_decode && 0 != option_values.cuesheet_filename && option_values.num_files > 1) {
440                         return usage_error("ERROR: --cuesheet cannot be used when encoding multiple files\n");
441                 }
442         }
443
444         flac__utils_printf(stderr, 2, "\n");
445         flac__utils_printf(stderr, 2, "flac %s, Copyright (C) 2000,2001,2002,2003,2004,2005  Josh Coalson\n", FLAC__VERSION_STRING);
446         flac__utils_printf(stderr, 2, "flac comes with ABSOLUTELY NO WARRANTY.  This is free software, and you are\n");
447         flac__utils_printf(stderr, 2, "welcome to redistribute it under certain conditions.  Type `flac' for details.\n\n");
448
449         if(!option_values.mode_decode) {
450                 char padopt[16];
451                 if(option_values.padding < 0)
452                         strcpy(padopt, "-");
453                 else
454                         sprintf(padopt, " %d", option_values.padding);
455                 flac__utils_printf(stderr, 2,
456                         "options:%s%s%s%s -P%s -b %u%s -l %u%s%s%s -q %u -r %u,%u%s\n",
457                         option_values.delete_input?" --delete-input-file":"",
458                         option_values.sector_align?" --sector-align":"",
459                         option_values.use_ogg?" --ogg":"",
460                         option_values.lax?" --lax":"",
461                         padopt,
462                         (unsigned)option_values.blocksize,
463                         option_values.loose_mid_side?" -M":option_values.do_mid_side?" -m":"",
464                         option_values.max_lpc_order,
465                         option_values.do_exhaustive_model_search?" -e":"",
466                         option_values.do_escape_coding?" -E":"",
467                         option_values.do_qlp_coeff_prec_search?" -p":"",
468                         option_values.qlp_coeff_precision,
469                         (unsigned)option_values.min_residual_partition_order,
470                         (unsigned)option_values.max_residual_partition_order,
471                         option_values.verify? " -V":""
472                 );
473         }
474
475         if(option_values.mode_decode) {
476                 FLAC__bool first = true;
477
478                 if(option_values.num_files == 0) {
479                         retval = decode_file("-");
480                 }
481                 else {
482                         unsigned i;
483                         if(option_values.num_files > 1)
484                                 option_values.cmdline_forced_outfilename = 0;
485                         for(i = 0, retval = 0; i < option_values.num_files; i++) {
486                                 if(0 == strcmp(option_values.filenames[i], "-") && !first)
487                                         continue;
488                                 retval |= decode_file(option_values.filenames[i]);
489                                 first = false;
490                         }
491                 }
492         }
493         else { /* encode */
494                 FLAC__bool first = true;
495
496                 if(option_values.num_files == 0) {
497                         retval = encode_file("-", first, true);
498                 }
499                 else {
500                         unsigned i;
501                         if(option_values.num_files > 1)
502                                 option_values.cmdline_forced_outfilename = 0;
503                         for(i = 0, retval = 0; i < option_values.num_files; i++) {
504                                 if(0 == strcmp(option_values.filenames[i], "-") && !first)
505                                         continue;
506                                 retval |= encode_file(option_values.filenames[i], first, i == (option_values.num_files-1));
507                                 first = false;
508                         }
509                         if(option_values.replay_gain && retval == 0) {
510                                 float album_gain, album_peak;
511                                 grabbag__replaygain_get_album(&album_gain, &album_peak);
512                                 for(i = 0; i < option_values.num_files; i++) {
513                                         const char *error, *outfilename = get_encoded_outfilename(option_values.filenames[i]);
514                                         if(0 == outfilename) {
515                                                 flac__utils_printf(stderr, 1, "ERROR: filename too long: %s", option_values.filenames[i]);
516                                                 return 1;
517                                         }
518                                         if(0 == strcmp(option_values.filenames[i], "-")) {
519                                                 FLAC__ASSERT(0);
520                                                 /* double protection */
521                                                 flac__utils_printf(stderr, 1, "internal error\n");
522                                                 return 2;
523                                         }
524                                         if(0 != (error = grabbag__replaygain_store_to_file_album(outfilename, album_gain, album_peak, /*preserve_modtime=*/true))) {
525                                                 flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain album tags\n", outfilename);
526                                                 retval = 1;
527                                         }
528                                 }
529                         }
530                 }
531         }
532
533         return retval;
534 }
535
536 FLAC__bool init_options()
537 {
538         option_values.show_help = false;
539         option_values.show_explain = false;
540         option_values.mode_decode = false;
541         option_values.verify = false;
542         option_values.force_file_overwrite = false;
543         option_values.continue_through_decode_errors = false;
544         option_values.replaygain_synthesis_spec.apply = false;
545         option_values.replaygain_synthesis_spec.use_album_gain = true;
546         option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__HARD;
547         option_values.replaygain_synthesis_spec.noise_shaping = NOISE_SHAPING_LOW;
548         option_values.replaygain_synthesis_spec.preamp = 0.0;
549         option_values.lax = false;
550         option_values.test_only = false;
551         option_values.analyze = false;
552         option_values.use_ogg = false;
553         option_values.has_serial_number = false;
554         option_values.serial_number = 0;
555         option_values.do_mid_side = true;
556         option_values.loose_mid_side = false;
557         option_values.do_exhaustive_model_search = false;
558         option_values.do_escape_coding = false;
559         option_values.do_qlp_coeff_prec_search = false;
560         option_values.force_to_stdout = false;
561         option_values.force_aiff_format = false;
562         option_values.force_raw_format = false;
563         option_values.delete_input = false;
564         option_values.replay_gain = false;
565         option_values.sector_align = false;
566         option_values.cmdline_forced_outfilename = 0;
567         option_values.output_prefix = 0;
568         option_values.aopts.do_residual_text = false;
569         option_values.aopts.do_residual_gnuplot = false;
570         option_values.padding = 4096;
571         option_values.max_lpc_order = 8;
572         option_values.qlp_coeff_precision = 0;
573         option_values.skip_specification = 0;
574         option_values.until_specification = 0;
575         option_values.cue_specification = 0;
576         option_values.format_is_big_endian = -1;
577         option_values.format_is_unsigned_samples = -1;
578         option_values.format_channels = -1;
579         option_values.format_bps = -1;
580         option_values.format_sample_rate = -1;
581         option_values.format_input_size = -1;
582         option_values.blocksize = -1;
583         option_values.min_residual_partition_order = -1;
584         option_values.max_residual_partition_order = -1;
585         option_values.rice_parameter_search_dist = -1;
586         option_values.requested_seek_points[0] = '\0';
587         option_values.num_requested_seek_points = -1;
588         option_values.cuesheet_filename = 0;
589         option_values.cued_seekpoints = true;
590
591         option_values.num_files = 0;
592         option_values.filenames = 0;
593
594         if(0 == (option_values.vorbis_comment = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT)))
595                 return false;
596
597         option_values.debug.disable_constant_subframes = false;
598         option_values.debug.disable_fixed_subframes = false;
599         option_values.debug.disable_verbatim_subframes = false;
600
601         return true;
602 }
603
604 int parse_options(int argc, char *argv[])
605 {
606         int short_option;
607         int option_index = 1;
608         FLAC__bool had_error = false;
609         const char *short_opts = "0123456789ab:cdefFhHl:mMo:pP:q:r:sS:tT:vV";
610
611         while ((short_option = share__getopt_long(argc, argv, short_opts, long_options_, &option_index)) != -1) {
612                 switch (short_option) {
613                         case 0: /* long option with no equivalent short option */
614                                 had_error |= (parse_option(short_option, long_options_[option_index].name, share__optarg) != 0);
615                                 break;
616                         case '?':
617                         case ':':
618                                 had_error = true;
619                                 break;
620                         default: /* short option */
621                                 had_error |= (parse_option(short_option, 0, share__optarg) != 0);
622                                 break;
623                 }
624         }
625
626         if(had_error) {
627                 return 1;
628         }
629
630         FLAC__ASSERT(share__optind <= argc);
631
632         option_values.num_files = argc - share__optind;
633
634         if(option_values.num_files > 0) {
635                 unsigned i = 0;
636                 if(0 == (option_values.filenames = (char**)malloc(sizeof(char*) * option_values.num_files)))
637                         die("out of memory allocating space for file names list");
638                 while(share__optind < argc)
639                         option_values.filenames[i++] = local_strdup(argv[share__optind++]);
640         }
641
642         return 0;
643 }
644
645 int parse_option(int short_option, const char *long_option, const char *option_argument)
646 {
647         char *p;
648
649         if(short_option == 0) {
650                 FLAC__ASSERT(0 != long_option);
651                 if(0 == strcmp(long_option, "totally-silent")) {
652                         flac__utils_verbosity_ = 0;
653                 }
654                 else if(0 == strcmp(long_option, "delete-input-file")) {
655                         option_values.delete_input = true;
656                 }
657                 else if(0 == strcmp(long_option, "output-prefix")) {
658                         FLAC__ASSERT(0 != option_argument);
659                         option_values.output_prefix = option_argument;
660                 }
661                 else if(0 == strcmp(long_option, "skip")) {
662                         FLAC__ASSERT(0 != option_argument);
663                         option_values.skip_specification = option_argument;
664                 }
665                 else if(0 == strcmp(long_option, "until")) {
666                         FLAC__ASSERT(0 != option_argument);
667                         option_values.until_specification = option_argument;
668                 }
669                 else if(0 == strcmp(long_option, "input-size")) {
670                         FLAC__ASSERT(0 != option_argument);
671                         option_values.format_input_size = atol(option_argument);
672                 }
673                 else if(0 == strcmp(long_option, "cue")) {
674                         FLAC__ASSERT(0 != option_argument);
675                         option_values.cue_specification = option_argument;
676                 }
677                 else if(0 == strcmp(long_option, "apply-replaygain-which-is-not-lossless")) {
678                         option_values.replaygain_synthesis_spec.apply = true;
679                         if (0 != option_argument) {
680                                 char *p;
681                                 option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__NONE;
682                                 option_values.replaygain_synthesis_spec.noise_shaping = NOISE_SHAPING_NONE;
683                                 option_values.replaygain_synthesis_spec.preamp = strtod(option_argument, &p);
684                                 for ( ; *p; p++) {
685                                         if (*p == 'a')
686                                                 option_values.replaygain_synthesis_spec.use_album_gain = true;
687                                         else if (*p == 't')
688                                                 option_values.replaygain_synthesis_spec.use_album_gain = false;
689                                         else if (*p == 'l')
690                                                 option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__PEAK;
691                                         else if (*p == 'L')
692                                                 option_values.replaygain_synthesis_spec.limiter = RGSS_LIMIT__HARD;
693                                         else if (*p == 'n' && p[1] >= '0' && p[1] <= '3') {
694                                                 option_values.replaygain_synthesis_spec.noise_shaping = p[1] - '0';
695                                                 p++;
696                                         }
697                                         else
698                                                 return usage_error("ERROR: bad specification string \"%s\" for --%s\n", option_argument, long_option);
699                                 }
700                         }
701                 }
702                 else if(0 == strcmp(long_option, "cuesheet")) {
703                         FLAC__ASSERT(0 != option_argument);
704                         option_values.cuesheet_filename = option_argument;
705                 }
706                 else if(0 == strcmp(long_option, "no-cued-seekpoints")) {
707                         option_values.cued_seekpoints = false;
708                 }
709                 else if(0 == strcmp(long_option, "super-secret-totally-impractical-compression-level")) {
710                         option_values.lax = true;
711                         option_values.do_exhaustive_model_search = true;
712                         option_values.do_escape_coding = true;
713                         option_values.do_mid_side = true;
714                         option_values.loose_mid_side = false;
715                         option_values.do_qlp_coeff_prec_search = true;
716                         option_values.min_residual_partition_order = 0;
717                         option_values.max_residual_partition_order = 16;
718                         option_values.rice_parameter_search_dist = 0;
719                         option_values.max_lpc_order = 32;
720                 }
721                 else if(0 == strcmp(long_option, "force-aiff-format")) {
722                         option_values.force_aiff_format = true;
723                 }
724                 else if(0 == strcmp(long_option, "force-raw-format")) {
725                         option_values.force_raw_format = true;
726                 }
727                 else if(0 == strcmp(long_option, "lax")) {
728                         option_values.lax = true;
729                 }
730                 else if(0 == strcmp(long_option, "replay-gain")) {
731                         option_values.replay_gain = true;
732                 }
733                 else if(0 == strcmp(long_option, "sector-align")) {
734                         option_values.sector_align = true;
735                 }
736 #ifdef FLAC__HAS_OGG
737                 else if(0 == strcmp(long_option, "ogg")) {
738                         option_values.use_ogg = true;
739                 }
740                 else if(0 == strcmp(long_option, "serial-number")) {
741                         option_values.has_serial_number = true;
742                         option_values.serial_number = atol(option_argument);
743                 }
744 #endif
745                 else if(0 == strcmp(long_option, "endian")) {
746                         FLAC__ASSERT(0 != option_argument);
747                         if(0 == strncmp(option_argument, "big", strlen(option_argument)))
748                                 option_values.format_is_big_endian = true;
749                         else if(0 == strncmp(option_argument, "little", strlen(option_argument)))
750                                 option_values.format_is_big_endian = false;
751                         else
752                                 return usage_error("ERROR: argument to --endian must be \"big\" or \"little\"\n");
753                 }
754                 else if(0 == strcmp(long_option, "channels")) {
755                         FLAC__ASSERT(0 != option_argument);
756                         option_values.format_channels = atoi(option_argument);
757                 }
758                 else if(0 == strcmp(long_option, "bps")) {
759                         FLAC__ASSERT(0 != option_argument);
760                         option_values.format_bps = atoi(option_argument);
761                 }
762                 else if(0 == strcmp(long_option, "sample-rate")) {
763                         FLAC__ASSERT(0 != option_argument);
764                         option_values.format_sample_rate = atoi(option_argument);
765                 }
766                 else if(0 == strcmp(long_option, "sign")) {
767                         FLAC__ASSERT(0 != option_argument);
768                         if(0 == strncmp(option_argument, "signed", strlen(option_argument)))
769                                 option_values.format_is_unsigned_samples = false;
770                         else if(0 == strncmp(option_argument, "unsigned", strlen(option_argument)))
771                                 option_values.format_is_unsigned_samples = true;
772                         else
773                                 return usage_error("ERROR: argument to --sign must be \"signed\" or \"unsigned\"\n");
774                 }
775                 else if(0 == strcmp(long_option, "residual-gnuplot")) {
776                         option_values.aopts.do_residual_gnuplot = true;
777                 }
778                 else if(0 == strcmp(long_option, "residual-text")) {
779                         option_values.aopts.do_residual_text = true;
780                 }
781                 /*
782                  * negatives
783                  */
784                 else if(0 == strcmp(long_option, "no-decode-through-errors")) {
785                         option_values.continue_through_decode_errors = false;
786                 }
787                 else if(0 == strcmp(long_option, "no-silent")) {
788                         flac__utils_verbosity_ = 2;
789                 }
790                 else if(0 == strcmp(long_option, "no-force")) {
791                         option_values.force_file_overwrite = false;
792                 }
793                 else if(0 == strcmp(long_option, "no-seektable")) {
794                         option_values.num_requested_seek_points = 0;
795                         option_values.requested_seek_points[0] = '\0';
796                 }
797                 else if(0 == strcmp(long_option, "no-delete-input-file")) {
798                         option_values.delete_input = false;
799                 }
800                 else if(0 == strcmp(long_option, "no-replay-gain")) {
801                         option_values.replay_gain = false;
802                 }
803                 else if(0 == strcmp(long_option, "no-sector-align")) {
804                         option_values.sector_align = false;
805                 }
806                 else if(0 == strcmp(long_option, "no-lax")) {
807                         option_values.lax = false;
808                 }
809 #ifdef FLAC__HAS_OGG
810                 else if(0 == strcmp(long_option, "no-ogg")) {
811                         option_values.use_ogg = false;
812                 }
813 #endif
814                 else if(0 == strcmp(long_option, "no-exhaustive-model-search")) {
815                         option_values.do_exhaustive_model_search = false;
816                 }
817                 else if(0 == strcmp(long_option, "no-mid-side")) {
818                         option_values.do_mid_side = option_values.loose_mid_side = false;
819                 }
820                 else if(0 == strcmp(long_option, "no-adaptive-mid-side")) {
821                         option_values.loose_mid_side = option_values.do_mid_side = false;
822                 }
823                 else if(0 == strcmp(long_option, "no-qlp-coeff-prec-search")) {
824                         option_values.do_qlp_coeff_prec_search = false;
825                 }
826                 else if(0 == strcmp(long_option, "no-padding")) {
827                         option_values.padding = -1;
828                 }
829                 else if(0 == strcmp(long_option, "no-verify")) {
830                         option_values.verify = false;
831                 }
832                 else if(0 == strcmp(long_option, "no-residual-gnuplot")) {
833                         option_values.aopts.do_residual_gnuplot = false;
834                 }
835                 else if(0 == strcmp(long_option, "no-residual-text")) {
836                         option_values.aopts.do_residual_text = false;
837                 }
838                 else if(0 == strcmp(long_option, "disable-constant-subframes")) {
839                         option_values.debug.disable_constant_subframes = true;
840                 }
841                 else if(0 == strcmp(long_option, "disable-fixed-subframes")) {
842                         option_values.debug.disable_fixed_subframes = true;
843                 }
844                 else if(0 == strcmp(long_option, "disable-verbatim-subframes")) {
845                         option_values.debug.disable_verbatim_subframes = true;
846                 }
847         }
848         else {
849                 const char *violation;
850                 switch(short_option) {
851                         case 'h':
852                                 option_values.show_help = true;
853                                 break;
854                         case 'H':
855                                 option_values.show_explain = true;
856                                 break;
857                         case 'v':
858                                 option_values.show_version = true;
859                                 break;
860                         case 'd':
861                                 option_values.mode_decode = true;
862                                 break;
863                         case 'a':
864                                 option_values.mode_decode = true;
865                                 option_values.analyze = true;
866                                 break;
867                         case 't':
868                                 option_values.mode_decode = true;
869                                 option_values.test_only = true;
870                                 break;
871                         case 'c':
872                                 option_values.force_to_stdout = true;
873                                 break;
874                         case 's':
875                                 flac__utils_verbosity_ = 1;
876                                 break;
877                         case 'f':
878                                 option_values.force_file_overwrite = true;
879                                 break;
880                         case 'o':
881                                 FLAC__ASSERT(0 != option_argument);
882                                 option_values.cmdline_forced_outfilename = option_argument;
883                                 break;
884                         case 'F':
885                                 option_values.continue_through_decode_errors = true;
886                                 break;
887                         case 'T':
888                                 FLAC__ASSERT(0 != option_argument);
889                                 if(!flac__vorbiscomment_add(option_values.vorbis_comment, option_argument, &violation))
890                                         return usage_error("ERROR: (-T/--tag) %s\n", violation);
891                                 break;
892                         case '0':
893                                 option_values.do_exhaustive_model_search = false;
894                                 option_values.do_escape_coding = false;
895                                 option_values.do_mid_side = false;
896                                 option_values.loose_mid_side = false;
897                                 option_values.qlp_coeff_precision = 0;
898                                 option_values.min_residual_partition_order = option_values.max_residual_partition_order = 2;
899                                 option_values.rice_parameter_search_dist = 0;
900                                 option_values.max_lpc_order = 0;
901                                 break;
902                         case '1':
903                                 option_values.do_exhaustive_model_search = false;
904                                 option_values.do_escape_coding = false;
905                                 option_values.do_mid_side = true;
906                                 option_values.loose_mid_side = true;
907                                 option_values.qlp_coeff_precision = 0;
908                                 option_values.min_residual_partition_order = option_values.max_residual_partition_order = 2;
909                                 option_values.rice_parameter_search_dist = 0;
910                                 option_values.max_lpc_order = 0;
911                                 break;
912                         case '2':
913                                 option_values.do_exhaustive_model_search = false;
914                                 option_values.do_escape_coding = false;
915                                 option_values.do_mid_side = true;
916                                 option_values.loose_mid_side = false;
917                                 option_values.qlp_coeff_precision = 0;
918                                 option_values.min_residual_partition_order = 0;
919                                 option_values.max_residual_partition_order = 3;
920                                 option_values.rice_parameter_search_dist = 0;
921                                 option_values.max_lpc_order = 0;
922                                 break;
923                         case '3':
924                                 option_values.do_exhaustive_model_search = false;
925                                 option_values.do_escape_coding = false;
926                                 option_values.do_mid_side = false;
927                                 option_values.loose_mid_side = false;
928                                 option_values.qlp_coeff_precision = 0;
929                                 option_values.min_residual_partition_order = option_values.max_residual_partition_order = 3;
930                                 option_values.rice_parameter_search_dist = 0;
931                                 option_values.max_lpc_order = 6;
932                                 break;
933                         case '4':
934                                 option_values.do_exhaustive_model_search = false;
935                                 option_values.do_escape_coding = false;
936                                 option_values.do_mid_side = true;
937                                 option_values.loose_mid_side = true;
938                                 option_values.qlp_coeff_precision = 0;
939                                 option_values.min_residual_partition_order = option_values.max_residual_partition_order = 3;
940                                 option_values.rice_parameter_search_dist = 0;
941                                 option_values.max_lpc_order = 8;
942                                 break;
943                         case '5':
944                                 option_values.do_exhaustive_model_search = false;
945                                 option_values.do_escape_coding = false;
946                                 option_values.do_mid_side = true;
947                                 option_values.loose_mid_side = false;
948                                 option_values.qlp_coeff_precision = 0;
949                                 option_values.min_residual_partition_order = option_values.max_residual_partition_order = 3;
950                                 option_values.rice_parameter_search_dist = 0;
951                                 option_values.max_lpc_order = 8;
952                                 break;
953                         case '6':
954                                 option_values.do_exhaustive_model_search = false;
955                                 option_values.do_escape_coding = false;
956                                 option_values.do_mid_side = true;
957                                 option_values.loose_mid_side = false;
958                                 option_values.qlp_coeff_precision = 0;
959                                 option_values.min_residual_partition_order = 0;
960                                 option_values.max_residual_partition_order = 4;
961                                 option_values.rice_parameter_search_dist = 0;
962                                 option_values.max_lpc_order = 8;
963                                 break;
964                         case '7':
965                                 option_values.do_exhaustive_model_search = true;
966                                 option_values.do_escape_coding = false;
967                                 option_values.do_mid_side = true;
968                                 option_values.loose_mid_side = false;
969                                 option_values.qlp_coeff_precision = 0;
970                                 option_values.min_residual_partition_order = 0;
971                                 option_values.max_residual_partition_order = 6;
972                                 option_values.rice_parameter_search_dist = 0;
973                                 option_values.max_lpc_order = 8;
974                                 break;
975                         case '8':
976                                 option_values.do_exhaustive_model_search = true;
977                                 option_values.do_escape_coding = false;
978                                 option_values.do_mid_side = true;
979                                 option_values.loose_mid_side = false;
980                                 option_values.qlp_coeff_precision = 0;
981                                 option_values.min_residual_partition_order = 0;
982                                 option_values.max_residual_partition_order = 6;
983                                 option_values.rice_parameter_search_dist = 0;
984                                 option_values.max_lpc_order = 12;
985                                 break;
986                         case '9':
987                                 return usage_error("ERROR: compression level '9' is reserved\n");
988                         case 'V':
989                                 option_values.verify = true;
990                                 break;
991                         case 'S':
992                                 FLAC__ASSERT(0 != option_argument);
993                                 if(option_values.num_requested_seek_points < 0)
994                                         option_values.num_requested_seek_points = 0;
995                                 option_values.num_requested_seek_points++;
996                                 if(strlen(option_values.requested_seek_points)+strlen(option_argument)+2 >= sizeof(option_values.requested_seek_points)) {
997                                         return usage_error("ERROR: too many seekpoints requested\n");
998                                 }
999                                 else {
1000                                         strcat(option_values.requested_seek_points, option_argument);
1001                                         strcat(option_values.requested_seek_points, ";");
1002                                 }
1003                                 break;
1004                         case 'P':
1005                                 FLAC__ASSERT(0 != option_argument);
1006                                 option_values.padding = atoi(option_argument);
1007                                 if(option_values.padding < 0)
1008                                         return usage_error("ERROR: argument to -P must be >= 0\n");
1009                                 break;
1010                         case 'b':
1011                                 FLAC__ASSERT(0 != option_argument);
1012                                 option_values.blocksize = atoi(option_argument);
1013                                 break;
1014                         case 'e':
1015                                 option_values.do_exhaustive_model_search = true;
1016                                 break;
1017                         case 'E':
1018                                 option_values.do_escape_coding = true;
1019                                 break;
1020                         case 'l':
1021                                 FLAC__ASSERT(0 != option_argument);
1022                                 option_values.max_lpc_order = atoi(option_argument);
1023                                 break;
1024                         case 'm':
1025                                 option_values.do_mid_side = true;
1026                                 option_values.loose_mid_side = false;
1027                                 break;
1028                         case 'M':
1029                                 option_values.loose_mid_side = option_values.do_mid_side = true;
1030                                 break;
1031                         case 'p':
1032                                 option_values.do_qlp_coeff_prec_search = true;
1033                                 break;
1034                         case 'q':
1035                                 FLAC__ASSERT(0 != option_argument);
1036                                 option_values.qlp_coeff_precision = atoi(option_argument);
1037                                 break;
1038                         case 'r':
1039                                 FLAC__ASSERT(0 != option_argument);
1040                                 p = strchr(option_argument, ',');
1041                                 if(0 == p) {
1042                                         option_values.min_residual_partition_order = 0;
1043                                         option_values.max_residual_partition_order = atoi(option_argument);
1044                                 }
1045                                 else {
1046                                         option_values.min_residual_partition_order = atoi(option_argument);
1047                                         option_values.max_residual_partition_order = atoi(++p);
1048                                 }
1049                                 break;
1050                         case 'R':
1051                                 FLAC__ASSERT(0 != option_argument);
1052                                 option_values.rice_parameter_search_dist = atoi(option_argument);
1053                                 break;
1054                         default:
1055                                 FLAC__ASSERT(0);
1056                 }
1057         }
1058
1059         return 0;
1060 }
1061
1062 void free_options()
1063 {
1064         unsigned i;
1065         if(0 != option_values.filenames) {
1066                 for(i = 0; i < option_values.num_files; i++) {
1067                         if(0 != option_values.filenames[i])
1068                                 free(option_values.filenames[i]);
1069                 }
1070                 free(option_values.filenames);
1071         }
1072         if(0 != option_values.vorbis_comment)
1073                 FLAC__metadata_object_delete(option_values.vorbis_comment);
1074 }
1075
1076 int usage_error(const char *message, ...)
1077 {
1078         if(flac__utils_verbosity_ >= 1) {
1079                 va_list args;
1080
1081                 FLAC__ASSERT(0 != message);
1082
1083                 va_start(args, message);
1084
1085                 (void) vfprintf(stderr, message, args);
1086
1087                 va_end(args);
1088
1089                 printf("Type \"flac\" for a usage summary or \"flac --help\" for all options\n");
1090         }
1091
1092         return 1;
1093 }
1094
1095 void show_version()
1096 {
1097         printf("flac %s\n", FLAC__VERSION_STRING);
1098 }
1099
1100 static void usage_header()
1101 {
1102         printf("===============================================================================\n");
1103         printf("flac - Command-line FLAC encoder/decoder version %s\n", FLAC__VERSION_STRING);
1104         printf("Copyright (C) 2000,2001,2002,2003,2004,2005  Josh Coalson\n");
1105         printf("\n");
1106         printf("This program is free software; you can redistribute it and/or\n");
1107         printf("modify it under the terms of the GNU General Public License\n");
1108         printf("as published by the Free Software Foundation; either version 2\n");
1109         printf("of the License, or (at your option) any later version.\n");
1110         printf("\n");
1111         printf("This program is distributed in the hope that it will be useful,\n");
1112         printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
1113         printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n");
1114         printf("GNU General Public License for more details.\n");
1115         printf("\n");
1116         printf("You should have received a copy of the GNU General Public License\n");
1117         printf("along with this program; if not, write to the Free Software\n");
1118         printf("Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n");
1119         printf("===============================================================================\n");
1120 }
1121
1122 static void usage_summary()
1123 {
1124         printf("Usage:\n");
1125         printf("\n");
1126         printf(" Encoding: flac [<general-options>] [<encoding/format-options>] [INPUTFILE [...]]\n");
1127         printf(" Decoding: flac -d [<general-options>] [<format-options>] [FLACFILE [...]]\n");
1128         printf("  Testing: flac -t [<general-options>] [FLACFILE [...]]\n");
1129         printf("Analyzing: flac -a [<general-options>] [<analysis-options>] [FLACFILE [...]]\n");
1130         printf("\n");
1131 }
1132
1133 void short_usage()
1134 {
1135         usage_header();
1136         printf("\n");
1137         printf("This is the short help; for all options use 'flac --help'; for even more\n");
1138         printf("instructions use 'flac --explain'\n");
1139         printf("\n");
1140         printf("To encode:\n");
1141         printf("  flac [-#] [INPUTFILE [...]]\n");
1142         printf("\n");
1143         printf("  -# is -0 (fastest compression) to -8 (highest compression); -5 is the default\n");
1144         printf("\n");
1145         printf("To decode:\n");
1146         printf("  flac -d [INPUTFILE [...]]\n");
1147         printf("\n");
1148         printf("To test:\n");
1149         printf("  flac -t [INPUTFILE [...]]\n");
1150 }
1151
1152 void show_help()
1153 {
1154         usage_header();
1155         usage_summary();
1156         printf("general options:\n");
1157         printf("  -v, --version                Show the flac version number\n");
1158         printf("  -h, --help                   Show this screen\n");
1159         printf("  -H, --explain                Show detailed explanation of usage and options\n");
1160         printf("  -d, --decode                 Decode (the default behavior is to encode)\n");
1161         printf("  -t, --test                   Same as -d except no decoded file is written\n");
1162         printf("  -a, --analyze                Same as -d except an analysis file is written\n");
1163         printf("  -c, --stdout                 Write output to stdout\n");
1164         printf("  -s, --silent                 Do not write runtime encode/decode statistics\n");
1165         printf("      --totally-silent         Do not print anything, including errors\n");
1166         printf("  -f, --force                  Force overwriting of output files\n");
1167         printf("  -o, --output-name=FILENAME   Force the output file name\n");
1168         printf("      --output-prefix=STRING   Prepend STRING to output names\n");
1169         printf("      --delete-input-file      Deletes after a successful encode/decode\n");
1170         printf("      --skip={#|mm:ss.ss}      Skip the given initial samples for each input\n");
1171         printf("      --until={#|[+|-]mm:ss.ss}  Stop at the given sample for each input file\n");
1172 #ifdef FLAC__HAS_OGG
1173         printf("      --ogg                    Use Ogg as transport layer\n");
1174         printf("      --serial-number          Serial number to use for the FLAC stream\n");
1175 #endif
1176         printf("analysis options:\n");
1177         printf("      --residual-text          Include residual signal in text output\n");
1178         printf("      --residual-gnuplot       Generate gnuplot files of residual distribution\n");
1179         printf("decoding options:\n");
1180         printf("  -F, --decode-through-errors  Continue decoding through stream errors\n");
1181         printf("      --cue=[#.#][-[#.#]]      Set the beginning and ending cuepoints to decode\n");
1182         printf("encoding options:\n");
1183         printf("  -V, --verify                 Verify a correct encoding\n");
1184         printf("      --lax                    Allow encoder to generate non-Subset files\n");
1185         printf("      --sector-align           Align multiple files on sector boundaries\n");
1186         printf("      --replay-gain            Calculate ReplayGain & store in FLAC tags\n");
1187         printf("      --cuesheet=FILENAME      Import cuesheet and store in CUESHEET block\n");
1188         printf("  -T, --tag=FIELD=VALUE        Add a FLAC tag; may appear multiple times\n");
1189         printf("  -S, --seekpoint={#|X|#x|#s}  Add seek point(s)\n");
1190         printf("  -P, --padding=#              Write a PADDING block of length #\n");
1191         printf("  -0, --compression-level-0, --fast  Synonymous with -l 0 -b 1152 -r 2,2\n");
1192         printf("  -1, --compression-level-1          Synonymous with -l 0 -b 1152 -M -r 2,2\n");
1193         printf("  -2, --compression-level-2          Synonymous with -l 0 -b 1152 -m -r 3\n");
1194         printf("  -3, --compression-level-3          Synonymous with -l 6 -b 4608 -r 3,3\n");
1195         printf("  -4, --compression-level-4          Synonymous with -l 8 -b 4608 -M -r 3,3\n");
1196         printf("  -5, --compression-level-5          Synonymous with -l 8 -b 4608 -m -r 3,3\n");
1197         printf("  -6, --compression-level-6          Synonymous with -l 8 -b 4608 -m -r 4\n");
1198         printf("  -7, --compression-level-7          Synonymous with -l 8 -b 4608 -m -e -r 6\n");
1199         printf("  -8, --compression-level-8, --best  Synonymous with -l 12 -b 4608 -m -e -r 6\n");
1200         printf("  -b, --blocksize=#                  Specify blocksize in samples\n");
1201         printf("  -m, --mid-side                     Try mid-side coding for each frame\n");
1202         printf("  -M, --adaptive-mid-side            Adaptive mid-side coding for all frames\n");
1203         printf("  -e, --exhaustive-model-search      Do exhaustive model search (expensive!)\n");
1204         printf("  -l, --max-lpc-order=#              Max LPC order; 0 => only fixed predictors\n");
1205         printf("  -p, --qlp-coeff-precision-search   Exhaustively search LP coeff quantization\n");
1206         printf("  -q, --qlp-coeff-precision=#        Specify precision in bits\n");
1207         printf("  -r, --rice-partition-order=[#,]#   Set [min,]max residual partition order\n");
1208         printf("format options:\n");
1209         printf("      --endian={big|little}    Set byte order for samples\n");
1210         printf("      --channels=#             Number of channels\n");
1211         printf("      --bps=#                  Number of bits per sample\n");
1212         printf("      --sample-rate=#          Sample rate in Hz\n");
1213         printf("      --sign={signed|unsigned} Sign of samples\n");
1214         printf("      --input-size=#           Size of the raw input in bytes\n");
1215         printf("      --force-aiff-format      Force decoding to AIFF format\n");
1216         printf("      --force-raw-format       Treat input or output as raw samples\n");
1217         printf("negative options:\n");
1218         printf("      --no-adaptive-mid-side\n");
1219         printf("      --no-decode-through-errors\n");
1220         printf("      --no-delete-input-file\n");
1221         printf("      --no-exhaustive-model-search\n");
1222         printf("      --no-lax\n");
1223         printf("      --no-mid-side\n");
1224 #ifdef FLAC__HAS_OGG
1225         printf("      --no-ogg\n");
1226 #endif
1227         printf("      --no-padding\n");
1228         printf("      --no-qlp-coeff-prec-search\n");
1229         printf("      --no-replay-gain\n");
1230         printf("      --no-residual-gnuplot\n");
1231         printf("      --no-residual-text\n");
1232         printf("      --no-sector-align\n");
1233         printf("      --no-seektable\n");
1234         printf("      --no-silent\n");
1235         printf("      --no-force\n");
1236         printf("      --no-verify\n");
1237 }
1238
1239 void show_explain()
1240 {
1241         usage_header();
1242         usage_summary();
1243         printf("For encoding:\n");
1244         printf("  The input file(s) may be a PCM RIFF WAVE file, AIFF (or uncompressed AIFF-C)\n");
1245         printf("  file, or raw samples.\n");
1246         printf("  The output file(s) will be in native FLAC or Ogg FLAC format\n");
1247         printf("For decoding, the reverse is true.\n");
1248         printf("\n");
1249         printf("A single INPUTFILE may be - for stdin.  No INPUTFILE implies stdin.  Use of\n");
1250         printf("stdin implies -c (write to stdout).  Normally you should use:\n");
1251         printf("   flac [options] -o outfilename  or  flac -d [options] -o outfilename\n");
1252         printf("instead of:\n");
1253         printf("   flac [options] > outfilename   or  flac -d [options] > outfilename\n");
1254         printf("since the former allows flac to seek backwards to write the STREAMINFO or\n");
1255         printf("WAVE/AIFF header contents when necessary.\n");
1256         printf("\n");
1257         printf("flac checks for the presence of a AIFF/WAVE header to decide whether or not to\n");
1258         printf("treat an input file as AIFF/WAVE format or raw samples.  If any input file is\n");
1259         printf("raw you must specify the format options {-fb|fl} -fc -fp and -fs, which will\n");
1260         printf("apply to all raw files.  You can force AIFF/WAVE files to be treated as raw\n");
1261         printf("files using -fr.\n");
1262         printf("\n");
1263         printf("general options:\n");
1264         printf("  -v, --version                Show the flac version number\n");
1265         printf("  -h, --help                   Show basic usage a list of all options\n");
1266         printf("  -H, --explain                Show this screen\n");
1267         printf("  -d, --decode                 Decode (the default behavior is to encode)\n");
1268         printf("  -t, --test                   Same as -d except no decoded file is written\n");
1269         printf("  -a, --analyze                Same as -d except an analysis file is written\n");
1270         printf("  -c, --stdout                 Write output to stdout\n");
1271         printf("  -s, --silent                 Do not write runtime encode/decode statistics\n");
1272         printf("      --totally-silent         Do not print anything of any kind, including\n");
1273         printf("                               warnings or errors.  The exit code will be the\n");
1274         printf("                               only way to determine successful completion.\n");
1275         printf("  -f, --force                  Force overwriting of output files\n");
1276         printf("  -o, --output-name=FILENAME   Force the output file name; usually flac just\n");
1277         printf("                               changes the extension.  May only be used when\n");
1278         printf("                               encoding a single file.  May not be used in\n");
1279         printf("                               conjunction with --output-prefix.\n");
1280         printf("      --output-prefix=STRING   Prefix each output file name with the given\n");
1281         printf("                               STRING.  This can be useful for encoding or\n");
1282         printf("                               decoding files to a different directory.  Make\n");
1283         printf("                               sure if your STRING is a path name that it ends\n");
1284         printf("                               with a '/' slash.\n");
1285         printf("      --delete-input-file      Automatically delete the input file after a\n");
1286         printf("                               successful encode or decode.  If there was an\n");
1287         printf("                               error (including a verify error) the input file\n");
1288         printf("                               is left intact.\n");
1289         printf("      --skip={#|mm:ss.ss}      Skip the first # samples of each input file; can\n");
1290         printf("                               be used both for encoding and decoding.  The\n");
1291         printf("                               alternative form mm:ss.ss can be used to specify\n");
1292         printf("                               minutes, seconds, and fractions of a second.\n");
1293         printf("      --until={#|[+|-]mm:ss.ss}  Stop at the given sample number for each input\n");
1294         printf("                               file.  The given sample number is not included\n");
1295         printf("                               in the decoded output.  The alternative form\n");
1296         printf("                               mm:ss.ss can be used to specify minutes,\n");
1297         printf("                               seconds, and fractions of a second.  If a `+'\n");
1298         printf("                               sign is at the beginning, the --until point is\n");
1299         printf("                               relative to the --skip point.  If a `-' sign is\n");
1300         printf("                               at the beginning, the --until point is relative\n");
1301         printf("                               to end of the audio.\n");
1302 #ifdef FLAC__HAS_OGG
1303         printf("      --ogg                    When encoding, generate Ogg FLAC output instead\n");
1304         printf("                               of native FLAC.  Ogg FLAC streams are FLAC\n");
1305         printf("                               streams wrapped in an Ogg transport layer.  The\n");
1306         printf("                               resulting file should have an '.ogg' extension\n");
1307         printf("                               and will still be decodable by flac.  When\n");
1308         printf("                               decoding, force the input to be treated as\n");
1309         printf("                               Ogg FLAC.  This is useful when piping input\n");
1310         printf("                               from stdin or when the filename does not end in\n");
1311         printf("                               '.ogg'.\n");
1312         printf("      --serial-number          Serial number to use for the FLAC stream.  When\n");
1313         printf("                               encoding and no serial number is given, flac\n");
1314         printf("                               uses '0'.  When decoding and no number is\n");
1315         printf("                               given, flac uses the serial number of the first\n");
1316         printf("                               page.\n");
1317 #endif
1318         printf("analysis options:\n");
1319         printf("      --residual-text          Include residual signal in text output.  This\n");
1320         printf("                               will make the file very big, much larger than\n");
1321         printf("                               even the decoded file.\n");
1322         printf("      --residual-gnuplot       Generate gnuplot files of residual distribution\n");
1323         printf("                               of each subframe\n");
1324         printf("decoding options:\n");
1325         printf("  -F, --decode-through-errors  By default flac stops decoding with an error\n");
1326         printf("                               and removes the partially decoded file if it\n");
1327         printf("                               encounters a bitstream error.  With -F, errors\n");
1328         printf("                               are still printed but flac will continue\n");
1329         printf("                               decoding to completion.  Note that errors may\n");
1330         printf("                               cause the decoded audio to be missing some\n");
1331         printf("                               samples or have silent sections.\n");
1332         printf("      --cue=[#.#][-[#.#]]      Set the beginning and ending cuepoints to\n");
1333         printf("                               decode.  The optional first #.# is the track and\n");
1334         printf("                               index point at which decoding will start; the\n");
1335         printf("                               default is the beginning of the stream.  The\n");
1336         printf("                               optional second #.# is the track and index point\n");
1337         printf("                               at which decoding will end; the default is the\n");
1338         printf("                               end of the stream.  If the cuepoint does not\n");
1339         printf("                               exist, the closest one before it (for the start\n");
1340         printf("                               point) or after it (for the end point) will be\n");
1341         printf("                               used.  The cuepoints are merely translated into\n");
1342         printf("                               sample numbers then used as --skip and --until.\n");
1343         printf("encoding options:\n");
1344         printf("  -V, --verify                 Verify a correct encoding by decoding the\n");
1345         printf("                               output in parallel and comparing to the\n");
1346         printf("                               original\n");
1347         printf("      --lax                    Allow encoder to generate non-Subset files\n");
1348         printf("      --sector-align           Align encoding of multiple CD format WAVE files\n");
1349         printf("                               on sector boundaries.\n");
1350         printf("      --replay-gain            Calculate ReplayGain values and store them as\n");
1351         printf("                               FLAC tags.  Title gains/peaks will be computed\n");
1352         printf("                               for each file, and an album gain/peak will be\n");
1353         printf("                               computed for all files.  All input files must\n");
1354         printf("                               have the same resolution, sample rate, and\n");
1355         printf("                               number of channels.  The sample rate must be\n");
1356         printf("                               one of 8, 11.025, 12, 16, 22.05, 24, 32, 44.1,\n");
1357         printf("                               or 48 kHz.  NOTE: this option may also leave a\n");
1358         printf("                               few extra bytes in the PADDING block.\n");
1359         printf("      --cuesheet=FILENAME      Import the given cuesheet file and store it in\n");
1360         printf("                               a CUESHEET metadata block.  This option may only\n");
1361         printf("                               be used when encoding a single file.  A\n");
1362         printf("                               seekpoint will be added for each index point in\n");
1363         printf("                               the cuesheet to the SEEKTABLE unless\n");
1364         printf("                               --no-cued-seekpoints is specified.\n");
1365         printf("  -T, --tag=FIELD=VALUE        Add a FLAC tag.  Make sure to quote the\n");
1366         printf("                               comment if necessary.  This option may appear\n");
1367         printf("                               more than once to add several comments.  NOTE:\n");
1368         printf("                               all tags will be added to all encoded files.\n");
1369         printf("  -S, --seekpoint={#|X|#x|#s}  Include a point or points in a SEEKTABLE\n");
1370         printf("       #  : a specific sample number for a seek point\n");
1371         printf("       X  : a placeholder point (always goes at the end of the SEEKTABLE)\n");
1372         printf("       #x : # evenly spaced seekpoints, the first being at sample 0\n");
1373         printf("       #s : a seekpoint every # seconds; # does not have to be a whole number\n");
1374         printf("     You may use many -S options; the resulting SEEKTABLE will be the unique-\n");
1375         printf("           ified union of all such values.\n");
1376         printf("     With no -S options, flac defaults to '-S 10s'.  Use -S- for no SEEKTABLE.\n");
1377         printf("     Note: -S #x and -S #s will not work if the encoder can't determine the\n");
1378         printf("           input size before starting.\n");
1379         printf("     Note: if you use -S # and # is >= samples in the input, there will be\n");
1380         printf("           either no seek point entered (if the input size is determinable\n");
1381         printf("           before encoding starts) or a placeholder point (if input size is not\n");
1382         printf("           determinable)\n");
1383         printf("  -P, --padding=#              Tell the encoder to write a PADDING metadata\n");
1384         printf("                               block of the given length (in bytes) after the\n");
1385         printf("                               STREAMINFO block.  This is useful if you plan\n");
1386         printf("                               to tag the file later with an APPLICATION\n");
1387         printf("                               block; instead of having to rewrite the entire\n");
1388         printf("                               file later just to insert your block, you can\n");
1389         printf("                               write directly over the PADDING block.  Note\n");
1390         printf("                               that the total length of the PADDING block will\n");
1391         printf("                               be 4 bytes longer than the length given because\n");
1392         printf("                               of the 4 metadata block header bytes.  You can\n");
1393         printf("                               force no PADDING block at all to be written with\n");
1394         printf("                               --no-padding.  The encoder writes a PADDING\n");
1395         printf("                               block of 4096 bytes by default.\n");
1396         printf("  -b, --blocksize=#            Specify the blocksize in samples; the default is\n");
1397         printf("                               1152 for -l 0, else 4608; must be one of 192,\n");
1398         printf("                               576, 1152, 2304, 4608, 256, 512, 1024, 2048,\n");
1399         printf("                               4096, 8192, 16384, or 32768 (unless --lax is\n");
1400         printf("                               used)\n");
1401         printf("  -0, --compression-level-0, --fast  Synonymous with -l 0 -b 1152 -r 2,2\n");
1402         printf("  -1, --compression-level-1          Synonymous with -l 0 -b 1152 -M -r 2,2\n");
1403         printf("  -2, --compression-level-2          Synonymous with -l 0 -b 1152 -m -r 3\n");
1404         printf("  -3, --compression-level-3          Synonymous with -l 6 -b 4608 -r 3,3\n");
1405         printf("  -4, --compression-level-4          Synonymous with -l 8 -b 4608 -M -r 3,3\n");
1406         printf("  -5, --compression-level-5          Synonymous with -l 8 -b 4608 -m -r 3,3\n");
1407         printf("                                     -5 is the default setting\n");
1408         printf("  -6, --compression-level-6          Synonymous with -l 8 -b 4608 -m -r 4\n");
1409         printf("  -7, --compression-level-7          Synonymous with -l 8 -b 4608 -m -e -r 6\n");
1410         printf("  -8, --compression-level-8, --best  Synonymous with -l 12 -b 4608 -m -e -r 6\n");
1411         printf("  -m, --mid-side                     Try mid-side coding for each frame\n");
1412         printf("                                     (stereo only)\n");
1413         printf("  -M, --adaptive-mid-side            Adaptive mid-side coding for all frames\n");
1414         printf("                                     (stereo only)\n");
1415         printf("  -e, --exhaustive-model-search      Do exhaustive model search (expensive!)\n");
1416         printf("  -l, --max-lpc-order=#              Max LPC order; 0 => only fixed predictors\n");
1417         printf("  -p, --qlp-coeff-precision-search   Do exhaustive search of LP coefficient\n");
1418         printf("                                     quantization (expensive!); overrides -q;\n");
1419         printf("                                     does nothing if using -l 0\n");
1420         printf("  -q, --qlp-coeff-precision=#        Specify precision in bits of quantized\n");
1421         printf("                                     linear-predictor coefficients; 0 => let\n");
1422         printf("                                     encoder decide (the minimun is %u, the\n", FLAC__MIN_QLP_COEFF_PRECISION);
1423         printf("                                     default is -q 0)\n");
1424         printf("  -r, --rice-partition-order=[#,]#   Set [min,]max residual partition order\n");
1425         printf("                                     (# is 0..16; min defaults to 0; the\n");
1426         printf("                                     default is -r 0; above 4 doesn't usually\n");
1427         printf("                                     help much)\n");
1428         printf("format options:\n");
1429         printf("      --endian={big|little}    Set byte order for samples\n");
1430         printf("      --channels=#             Number of channels\n");
1431         printf("      --bps=#                  Number of bits per sample\n");
1432         printf("      --sample-rate=#          Sample rate in Hz\n");
1433         printf("      --sign={signed|unsigned} Sign of samples (the default is signed)\n");
1434         printf("      --input-size=#           Size of the raw input in bytes.  If you are\n");
1435         printf("                               encoding raw samples from stdin, you must set\n");
1436         printf("                               this option in order to be able to use --skip,\n");
1437         printf("                               --until, --cue-sheet, or other options that need\n");
1438         printf("                               to know the size of the input beforehand.  If\n");
1439         printf("                               the size given is greater than what is found in\n");
1440         printf("                               the input stream, the encoder will complain\n");
1441         printf("                               about an unexpected end-of-file.  If the size\n");
1442         printf("                               given is less, samples will be truncated.\n");
1443         printf("      --force-aiff-format      Force the decoder to output AIFF format.  This\n");
1444         printf("                               option is not needed if the output filename (as\n");
1445         printf("                               set by -o) ends with .aif or .aiff; this option\n");
1446         printf("                               has no effect when encoding since input AIFF is\n");
1447         printf("                               auto-detected.\n");
1448         printf("      --force-raw-format       Force input (when encoding) or output (when\n");
1449         printf("                               decoding) to be treated as raw samples\n");
1450         printf("negative options:\n");
1451         printf("      --no-adaptive-mid-side\n");
1452         printf("      --no-decode-through-errors\n");
1453         printf("      --no-delete-input-file\n");
1454         printf("      --no-exhaustive-model-search\n");
1455         printf("      --no-lax\n");
1456         printf("      --no-mid-side\n");
1457 #ifdef FLAC__HAS_OGG
1458         printf("      --no-ogg\n");
1459 #endif
1460         printf("      --no-padding\n");
1461         printf("      --no-qlp-coeff-prec-search\n");
1462         printf("      --no-residual-gnuplot\n");
1463         printf("      --no-residual-text\n");
1464         printf("      --no-sector-align\n");
1465         printf("      --no-seektable\n");
1466         printf("      --no-silent\n");
1467         printf("      --no-force\n");
1468         printf("      --no-verify\n");
1469 }
1470
1471 void format_mistake(const char *infilename, const char *wrong, const char *right)
1472 {
1473         flac__utils_printf(stderr, 1, "WARNING: %s is not a %s file; treating as a %s file\n", infilename, wrong, right);
1474 }
1475
1476 int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_last_file)
1477 {
1478         FILE *encode_infile;
1479         FLAC__byte lookahead[12];
1480         unsigned lookahead_length = 0;
1481         FileFormat fmt = RAW;
1482         FLAC__bool is_aifc = false;
1483         int retval;
1484         long infilesize;
1485         encode_options_t common_options;
1486         const char *outfilename = get_encoded_outfilename(infilename);
1487
1488         if(0 == outfilename) {
1489                 flac__utils_printf(stderr, 1, "ERROR: filename too long: %s", infilename);
1490                 return 1;
1491         }
1492
1493         /*
1494          * Error if output file already exists (and -f not used).
1495          * Use grabbag__file_get_filesize() as a cheap way to check.
1496          */
1497         if(!option_values.test_only && !option_values.force_file_overwrite && grabbag__file_get_filesize(outfilename) != (off_t)(-1)) {
1498                 flac__utils_printf(stderr, 1, "ERROR: output file %s already exists, use -f to override\n", outfilename);
1499                 return 1;
1500         }
1501
1502         if(0 == strcmp(infilename, "-")) {
1503                 infilesize = -1;
1504                 encode_infile = grabbag__file_get_binary_stdin();
1505         }
1506         else {
1507                 infilesize = grabbag__file_get_filesize(infilename);
1508                 if(0 == (encode_infile = fopen(infilename, "rb"))) {
1509                         flac__utils_printf(stderr, 1, "ERROR: can't open input file %s\n", infilename);
1510                         return 1;
1511                 }
1512         }
1513
1514         if(!option_values.force_raw_format) {
1515                 /* first set format based on name */
1516                 if(strlen(infilename) >= 4 && 0 == strcasecmp(infilename+(strlen(infilename)-4), ".wav"))
1517                         fmt= WAV;
1518                 else if(strlen(infilename) >= 4 && 0 == strcasecmp(infilename+(strlen(infilename)-4), ".aif"))
1519                         fmt= AIF;
1520                 else if(strlen(infilename) >= 5 && 0 == strcasecmp(infilename+(strlen(infilename)-5), ".aiff"))
1521                         fmt= AIF;
1522
1523                 /* attempt to guess the file type based on the first 12 bytes */
1524                 if((lookahead_length = fread(lookahead, 1, 12, encode_infile)) < 12) {
1525                         if(fmt != RAW)
1526                                 format_mistake(infilename, fmt == AIF ? "AIFF" : "WAVE", "raw");
1527                         fmt= RAW;
1528                 }
1529                 else {
1530                         if(!strncmp((const char *)lookahead, "RIFF", 4) && !strncmp((const char *)lookahead+8, "WAVE", 4))
1531                                 fmt= WAV;
1532                         else if(!strncmp((const char *)lookahead, "FORM", 4) && !strncmp((const char *)lookahead+8, "AIFF", 4))
1533                                 fmt= AIF;
1534                         else if(!strncmp((const char *)lookahead, "FORM", 4) && !strncmp((const char *)lookahead+8, "AIFC", 4)) {
1535                                 fmt= AIF;
1536                                 is_aifc = true;
1537                         }
1538                         else {
1539                                 if(fmt != RAW)
1540                                         format_mistake(infilename, fmt == AIF ? "AIFF" : "WAVE", "raw");
1541                                 fmt= RAW;
1542                         }
1543                 }
1544         }
1545
1546         if(option_values.format_input_size >= 0) {
1547                 if (fmt != RAW || infilesize >= 0) {
1548                         flac__utils_printf(stderr, 1, "ERROR: can only use --input-size when encoding raw samples from stdin\n");
1549                         return 1;
1550                 }
1551                 else {
1552                         infilesize = option_values.format_input_size;
1553                 }
1554         }
1555
1556         if(option_values.sector_align && fmt == RAW && infilesize < 0) {
1557                 flac__utils_printf(stderr, 1, "ERROR: can't --sector-align when the input size is unknown\n");
1558                 return 1;
1559         }
1560
1561         if(fmt == RAW) {
1562                 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)
1563                         return usage_error("ERROR: for encoding a raw file you must specify a value for --endian, --sign, --channels, --bps, and --sample-rate\n");
1564         }
1565
1566         if(encode_infile == stdin || option_values.force_to_stdout) {
1567                 if(option_values.replay_gain)
1568                         return usage_error("ERROR: --replay-gain cannot be used when encoding to stdout\n");
1569         }
1570
1571         if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &common_options.skip_specification) || common_options.skip_specification.is_relative)
1572                 return usage_error("ERROR: invalid value for --skip\n");
1573
1574         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 */
1575                 return usage_error("ERROR: invalid value for --until\n");
1576         /* if there is no "--until" we want to default to "--until=-0" */
1577         if(0 == option_values.until_specification)
1578                 common_options.until_specification.is_relative = true;
1579
1580         common_options.verify = option_values.verify;
1581 #ifdef FLAC__HAS_OGG
1582         common_options.use_ogg = option_values.use_ogg;
1583         /* set a random serial number if one has not yet been specified */
1584         if(!option_values.has_serial_number) {
1585                 srand(time(0));
1586                 option_values.serial_number = rand();
1587                 option_values.has_serial_number = true;
1588         }
1589         common_options.serial_number = option_values.serial_number++;
1590 #endif
1591         common_options.lax = option_values.lax;
1592         common_options.do_mid_side = option_values.do_mid_side;
1593         common_options.loose_mid_side = option_values.loose_mid_side;
1594         common_options.do_exhaustive_model_search = option_values.do_exhaustive_model_search;
1595         common_options.do_escape_coding = option_values.do_escape_coding;
1596         common_options.do_qlp_coeff_prec_search = option_values.do_qlp_coeff_prec_search;
1597         common_options.min_residual_partition_order = option_values.min_residual_partition_order;
1598         common_options.max_residual_partition_order = option_values.max_residual_partition_order;
1599         common_options.rice_parameter_search_dist = option_values.rice_parameter_search_dist;
1600         common_options.max_lpc_order = option_values.max_lpc_order;
1601         common_options.blocksize = (unsigned)option_values.blocksize;
1602         common_options.qlp_coeff_precision = option_values.qlp_coeff_precision;
1603         common_options.padding = option_values.padding;
1604         common_options.requested_seek_points = option_values.requested_seek_points;
1605         common_options.num_requested_seek_points = option_values.num_requested_seek_points;
1606         common_options.cuesheet_filename = option_values.cuesheet_filename;
1607         common_options.cued_seekpoints = option_values.cued_seekpoints;
1608         common_options.is_first_file = is_first_file;
1609         common_options.is_last_file = is_last_file;
1610         common_options.align_reservoir = align_reservoir;
1611         common_options.align_reservoir_samples = &align_reservoir_samples;
1612         common_options.replay_gain = option_values.replay_gain;
1613         common_options.sector_align = option_values.sector_align;
1614         common_options.vorbis_comment = option_values.vorbis_comment;
1615         common_options.debug.disable_constant_subframes = option_values.debug.disable_constant_subframes;
1616         common_options.debug.disable_fixed_subframes = option_values.debug.disable_fixed_subframes;
1617         common_options.debug.disable_verbatim_subframes = option_values.debug.disable_verbatim_subframes;
1618
1619         if(fmt == RAW) {
1620                 raw_encode_options_t options;
1621
1622                 options.common = common_options;
1623                 options.is_big_endian = option_values.format_is_big_endian;
1624                 options.is_unsigned_samples = option_values.format_is_unsigned_samples;
1625                 options.channels = option_values.format_channels;
1626                 options.bps = option_values.format_bps;
1627                 options.sample_rate = option_values.format_sample_rate;
1628
1629                 retval = flac__encode_raw(encode_infile, infilesize, infilename, outfilename, lookahead, lookahead_length, options);
1630         }
1631         else {
1632                 wav_encode_options_t options;
1633
1634                 options.common = common_options;
1635
1636                 if(fmt == AIF)
1637                         retval = flac__encode_aif(encode_infile, infilesize, infilename, outfilename, lookahead, lookahead_length, options, is_aifc);
1638                 else
1639                         retval = flac__encode_wav(encode_infile, infilesize, infilename, outfilename, lookahead, lookahead_length, options);
1640         }
1641
1642         if(retval == 0 && strcmp(infilename, "-")) {
1643                 if(strcmp(outfilename, "-")) {
1644                         if(option_values.replay_gain) {
1645                                 float title_gain, title_peak;
1646                                 const char *error;
1647                                 grabbag__replaygain_get_title(&title_gain, &title_peak);
1648                                 if(0 != (error = grabbag__replaygain_store_to_file_title(outfilename, title_gain, title_peak, /*preserve_modtime=*/true))) {
1649                                         flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain title tags\n", outfilename);
1650                                 }
1651                         }
1652                         grabbag__file_copy_metadata(infilename, outfilename);
1653                 }
1654                 if(option_values.delete_input)
1655                         unlink(infilename);
1656         }
1657
1658         return retval;
1659 }
1660
1661 int decode_file(const char *infilename)
1662 {
1663         int retval;
1664         FLAC__bool treat_as_ogg = false;
1665         decode_options_t common_options;
1666         const char *outfilename = get_decoded_outfilename(infilename);
1667
1668         if(0 == outfilename) {
1669                 flac__utils_printf(stderr, 1, "ERROR: filename too long: %s", infilename);
1670                 return 1;
1671         }
1672
1673         /*
1674          * Error if output file already exists (and -f not used).
1675          * Use grabbag__file_get_filesize() as a cheap way to check.
1676          */
1677         if(!option_values.test_only && !option_values.force_file_overwrite && grabbag__file_get_filesize(outfilename) != (off_t)(-1)) {
1678                 flac__utils_printf(stderr, 1, "ERROR: output file %s already exists, use -f to override\n", outfilename);
1679                 return 1;
1680         }
1681
1682         if(!option_values.test_only && !option_values.analyze) {
1683                 if(option_values.force_raw_format && (option_values.format_is_big_endian < 0 || option_values.format_is_unsigned_samples < 0))
1684                         return usage_error("ERROR: for decoding to a raw file you must specify a value for --endian and --sign\n");
1685         }
1686
1687         if(option_values.use_ogg)
1688                 treat_as_ogg = true;
1689         else if(strlen(infilename) >= 4 && 0 == strcasecmp(infilename+(strlen(infilename)-4), ".ogg"))
1690                 treat_as_ogg = true;
1691         else
1692                 treat_as_ogg = false;
1693
1694 #ifndef FLAC__HAS_OGG
1695         if(treat_as_ogg) {
1696                 flac__utils_printf(stderr, 1, "%s: Ogg support has not been built into this copy of flac\n", infilename);
1697                 return 1;
1698         }
1699 #endif
1700
1701         if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &common_options.skip_specification) || common_options.skip_specification.is_relative)
1702                 return usage_error("ERROR: invalid value for --skip\n");
1703
1704         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 */
1705                 return usage_error("ERROR: invalid value for --until\n");
1706         /* if there is no "--until" we want to default to "--until=-0" */
1707         if(0 == option_values.until_specification)
1708                 common_options.until_specification.is_relative = true;
1709
1710         if(option_values.cue_specification) {
1711                 if(!flac__utils_parse_cue_specification(option_values.cue_specification, &common_options.cue_specification))
1712                         return usage_error("ERROR: invalid value for --cue\n");
1713                 common_options.has_cue_specification = true;
1714         }
1715         else
1716                 common_options.has_cue_specification = false;
1717
1718         common_options.continue_through_decode_errors = option_values.continue_through_decode_errors;
1719         common_options.replaygain_synthesis_spec = option_values.replaygain_synthesis_spec;
1720 #ifdef FLAC__HAS_OGG
1721         common_options.is_ogg = treat_as_ogg;
1722         common_options.use_first_serial_number = !option_values.has_serial_number;
1723         common_options.serial_number = option_values.serial_number;
1724 #endif
1725
1726         if(!option_values.force_raw_format) {
1727                 wav_decode_options_t options;
1728
1729                 options.common = common_options;
1730
1731                 if(
1732                         option_values.force_aiff_format ||
1733                         (strlen(outfilename) >= 4 && 0 == strcasecmp(outfilename+(strlen(outfilename)-4), ".aif")) ||
1734                         (strlen(outfilename) >= 5 && 0 == strcasecmp(outfilename+(strlen(outfilename)-5), ".aiff"))
1735                 )
1736                         retval = flac__decode_aiff(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, options);
1737                 else
1738                         retval = flac__decode_wav(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, options);
1739         }
1740         else {
1741                 raw_decode_options_t options;
1742
1743                 options.common = common_options;
1744                 options.is_big_endian = option_values.format_is_big_endian;
1745                 options.is_unsigned_samples = option_values.format_is_unsigned_samples;
1746
1747                 retval = flac__decode_raw(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, options);
1748         }
1749
1750         if(retval == 0 && strcmp(infilename, "-")) {
1751                 if(strcmp(outfilename, "-"))
1752                         grabbag__file_copy_metadata(infilename, outfilename);
1753                 if(option_values.delete_input && !option_values.test_only && !option_values.analyze)
1754                         unlink(infilename);
1755         }
1756
1757         return retval;
1758 }
1759
1760 const char *get_encoded_outfilename(const char *infilename)
1761 {
1762         const char *suffix = (option_values.use_ogg? ".ogg" : ".flac");
1763         return get_outfilename(infilename, suffix);
1764 }
1765
1766 const char *get_decoded_outfilename(const char *infilename)
1767 {
1768         const char *suffix;
1769         if(option_values.analyze) {
1770                 suffix = ".ana";
1771         }
1772         else if(option_values.force_raw_format) {
1773                 suffix = ".raw";
1774         }
1775         else if(option_values.force_aiff_format) {
1776                 suffix = ".aiff";
1777         }
1778         else {
1779                 suffix = ".wav";
1780         }
1781         return get_outfilename(infilename, suffix);
1782 }
1783
1784 const char *get_outfilename(const char *infilename, const char *suffix)
1785 {
1786         if(0 == option_values.cmdline_forced_outfilename) {
1787                 static char buffer[4096]; /* @@@ bad MAGIC NUMBER */
1788
1789                 if(0 == strcmp(infilename, "-") || option_values.force_to_stdout) {
1790                         strcpy(buffer, "-");
1791                 }
1792                 else {
1793                         char *p;
1794                         if (flac__strlcpy(buffer, option_values.output_prefix? option_values.output_prefix : "", sizeof buffer) >= sizeof buffer)
1795                                 return 0;
1796                         if (flac__strlcat(buffer, infilename, sizeof buffer) >= sizeof buffer)
1797                                 return 0;
1798                         if(0 == (p = strrchr(buffer, '.'))) {
1799                                 if (flac__strlcat(buffer, suffix, sizeof buffer) >= sizeof buffer)
1800                                         return 0;
1801                         }
1802                         else {
1803                                 if(0 == strcmp(p, suffix)) {
1804                                         *p = '\0';
1805                                         if (flac__strlcat(buffer, "_new", sizeof buffer) >= sizeof buffer)
1806                                                 return 0;
1807                                 }
1808                                 else {
1809                                         *p = '\0';
1810                                 }
1811                                 if (flac__strlcat(buffer, suffix, sizeof buffer) >= sizeof buffer)
1812                                         return 0;
1813                         }
1814                 }
1815                 return buffer;
1816         }
1817         else
1818                 return option_values.cmdline_forced_outfilename;
1819 }
1820
1821 void die(const char *message)
1822 {
1823         FLAC__ASSERT(0 != message);
1824         flac__utils_printf(stderr, 1, "ERROR: %s\n", message);
1825         exit(1);
1826 }
1827
1828 char *local_strdup(const char *source)
1829 {
1830         char *ret;
1831         FLAC__ASSERT(0 != source);
1832         if(0 == (ret = strdup(source)))
1833                 die("out of memory during strdup()");
1834         return ret;
1835 }