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