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