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