revamp --skip processing, allow new mm:ss.sss form
[flac.git] / src / flac / main.c
index ac5d8b5..44aae3f 100644 (file)
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
 #if !defined _MSC_VER && !defined __MINGW32__
 /* unlink is in stdio.h in VC++ */
 #include <unistd.h> /* for unlink() */
 #define strcasecmp stricmp
 #endif
 #include "FLAC/all.h"
+#include "share/grabbag.h"
 #include "analyze.h"
 #include "decode.h"
 #include "encode.h"
-#include "file.h"
+#include "utils.h"
 #include "vorbiscomment.h"
 
 #if 0
@@ -59,18 +65,21 @@ static void show_help();
 static void show_explain();
 static void format_mistake(const char *infilename, const char *wrong, const char *right);
 
-static int encode_file(const char *infilename, const char *forced_outfilename, FLAC__bool is_last_file);
-static int decode_file(const char *infilename, const char *forced_outfilename);
+static int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_last_file);
+static int decode_file(const char *infilename);
+
+static const char *get_encoded_outfilename(const char *infilename);
+static const char *get_decoded_outfilename(const char *infilename);
 
 static void die(const char *message);
 static char *local_strdup(const char *source);
 
 
 /*
- * FLAC__share__getopt format struct; note that for long options with no
+ * share__getopt format struct; note that for long options with no
  * short option equivalent we just set the 'val' field to 0.
  */
-static struct FLAC__share__option long_options_[] = {
+static struct share__option long_options_[] = {
        /*
         * general options
         */
@@ -95,6 +104,8 @@ static struct FLAC__share__option long_options_[] = {
        /*
         * encoding options
         */
+       { "cuesheet", 1, 0, 0 },
+       { "no-cued-seekpoints", 0, 0, 0 },
        { "tag", 1, 0, 'T' },
        { "compression-level-0", 0, 0, '0' },
        { "compression-level-1", 0, 0, '1' },
@@ -108,10 +119,11 @@ static struct FLAC__share__option long_options_[] = {
        { "compression-level-9", 0, 0, '9' },
        { "best", 0, 0, '8' },
        { "fast", 0, 0, '0' },
-       { "super-secret-impractical-compression-level", 0, 0, 0 },
+       { "super-secret-totally-impractical-compression-level", 0, 0, 0 },
        { "verify", 0, 0, 'V' },
        { "force-raw-format", 0, 0, 0 },
        { "lax", 0, 0, 0 },
+       { "replay-gain", 0, 0, 0 },
        { "sector-align", 0, 0, 0 },
        { "seekpoint", 1, 0, 'S' },
        { "padding", 1, 0, 'P' },
@@ -154,6 +166,7 @@ static struct FLAC__share__option long_options_[] = {
        { "no-silent", 0, 0, 0 },
        { "no-seektable", 0, 0, 0 },
        { "no-delete-input-file", 0, 0, 0 },
+       { "no-replay-gain", 0, 0, 0 },
        { "no-sector-align", 0, 0, 0 },
        { "no-lax", 0, 0, 0 },
 #ifdef FLAC__HAS_OGG
@@ -171,6 +184,12 @@ static struct FLAC__share__option long_options_[] = {
        { "no-verify", 0, 0, 0 },
        { "no-residual-gnuplot", 0, 0, 0 },
        { "no-residual-text", 0, 0, 0 },
+       /*
+        * undocumented debugging options for the test suite
+        */
+       { "disable-constant-subframes", 0, 0, 0 },
+       { "disable-fixed-subframes", 0, 0, 0 },
+       { "disable-verbatim-subframes", 0, 0, 0 },
 
        {0, 0, 0, 0}
 };
@@ -202,6 +221,7 @@ static struct {
        FLAC__bool force_to_stdout;
        FLAC__bool force_raw_format;
        FLAC__bool delete_input;
+       FLAC__bool replay_gain;
        FLAC__bool sector_align;
        const char *cmdline_forced_outfilename;
        const char *output_prefix;
@@ -209,7 +229,7 @@ static struct {
        int padding;
        unsigned max_lpc_order;
        unsigned qlp_coeff_precision;
-       FLAC__uint64 skip;
+       const char *skip_specification;
        int format_is_big_endian;
        int format_is_unsigned_samples;
        int format_channels;
@@ -219,13 +239,21 @@ static struct {
        int min_residual_partition_order;
        int max_residual_partition_order;
        int rice_parameter_search_dist;
-       char requested_seek_points[50000]; /* @@@ bad MAGIC NUMBER */
+       char requested_seek_points[50000]; /* @@@ bad MAGIC NUMBER but buffer overflow is checked */
        int num_requested_seek_points; /* -1 => no -S options were given, 0 => -S- was given */
+       const char *cuesheet_filename;
+       FLAC__bool cued_seekpoints;
 
        unsigned num_files;
        char **filenames;
 
        FLAC__StreamMetadata *vorbis_comment;
+
+       struct {
+               FLAC__bool disable_constant_subframes;
+               FLAC__bool disable_fixed_subframes;
+               FLAC__bool disable_verbatim_subframes;
+       } debug;
 } option_values;
 
 
@@ -237,8 +265,6 @@ static FLAC__int32 align_reservoir_0[588], align_reservoir_1[588]; /* for carryi
 static FLAC__int32 *align_reservoir[2] = { align_reservoir_0, align_reservoir_1 };
 static unsigned align_reservoir_samples = 0; /* 0 .. 587 */
 
-static const char *flac_suffix = ".flac", *ogg_suffix = ".ogg";
-
 
 int main(int argc, char *argv[])
 {
@@ -308,7 +334,7 @@ int do_it()
                }
                else {
                        if(option_values.test_only) {
-                               if(option_values.skip > 0)
+                               if(0 != option_values.skip_specification)
                                        return usage_error("ERROR: --skip is not allowed in test mode\n");
                        }
                }
@@ -351,21 +377,46 @@ int do_it()
                if(option_values.sector_align) {
                        if(option_values.mode_decode)
                                return usage_error("ERROR: --sector-align only allowed for encoding\n");
-                       else if(option_values.skip > 0)
+                       if(0 != option_values.skip_specification)
                                return usage_error("ERROR: --sector-align not allowed with --skip\n");
-                       else if(option_values.format_channels >= 0 && option_values.format_channels != 2)
+                       if(option_values.format_channels >= 0 && option_values.format_channels != 2)
                                return usage_error("ERROR: --sector-align can only be done with stereo input\n");
-                       else if(option_values.format_bps >= 0 && option_values.format_bps != 16)
+                       if(option_values.format_bps >= 0 && option_values.format_bps != 16)
                                return usage_error("ERROR: --sector-align can only be done with 16-bit samples\n");
-                       else if(option_values.format_sample_rate >= 0 && option_values.format_sample_rate != 44100)
+                       if(option_values.format_sample_rate >= 0 && option_values.format_sample_rate != 44100)
                                return usage_error("ERROR: --sector-align can only be done with a sample rate of 44100\n");
                }
+               if(option_values.replay_gain) {
+                       if(option_values.force_to_stdout)
+                               return usage_error("ERROR: --replay-gain not allowed with -c/--stdout\n");
+                       if(option_values.mode_decode)
+                               return usage_error("ERROR: --replay-gain only allowed for encoding\n");
+                       if(option_values.format_channels > 2)
+                               return usage_error("ERROR: --replay-gain can only be done with mono/stereo input\n");
+                       if(option_values.format_sample_rate >= 0 && !grabbag__replaygain_is_valid_sample_frequency(option_values.format_sample_rate))
+                               return usage_error("ERROR: invalid sample rate used with --replay-gain\n");
+                       /*
+                        * We want to reserve padding space for the ReplayGain
+                        * tags that we will set later, to avoid rewriting the
+                        * whole file.
+                        */
+                       if(option_values.padding < 0) {
+                               fprintf(stderr, "NOTE: --replay-gain may leave a small PADDING block even with --no-padding\n");
+                               option_values.padding = GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED;
+                       }
+                       else {
+                               option_values.padding += GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED;
+                       }
+               }
                if(option_values.num_files > 1 && option_values.cmdline_forced_outfilename) {
                        return usage_error("ERROR: -o/--output-name cannot be used with multiple files\n");
                }
                if(option_values.cmdline_forced_outfilename && option_values.output_prefix) {
                        return usage_error("ERROR: --output-prefix conflicts with -o/--output-name\n");
                }
+               if(!option_values.mode_decode && 0 != option_values.cuesheet_filename && option_values.num_files > 1) {
+                       return usage_error("ERROR: --cuesheet cannot be used when encoding multiple files\n");
+               }
        }
        if(option_values.verbose) {
                fprintf(stderr, "\n");
@@ -380,11 +431,7 @@ int do_it()
                        else
                                sprintf(padopt, " %d", option_values.padding);
                        fprintf(stderr,
-                               "options:%s%s"
-#ifdef FLAC__HAS_OGG
-                               "%s"
-#endif
-                               "%s -P%s -b %u%s -l %u%s%s%s -q %u -r %u,%u%s\n",
+                               "options:%s%s%s%s -P%s -b %u%s -l %u%s%s%s -q %u -r %u,%u%s\n",
                                option_values.delete_input?" --delete-input-file":"",
                                option_values.sector_align?" --sector-align":"",
                                option_values.use_ogg?" --ogg":"",
@@ -408,7 +455,7 @@ int do_it()
                FLAC__bool first = true;
 
                if(option_values.num_files == 0) {
-                       retval = decode_file("-", 0);
+                       retval = decode_file("-");
                }
                else {
                        unsigned i;
@@ -417,7 +464,7 @@ int do_it()
                        for(i = 0, retval = 0; i < option_values.num_files; i++) {
                                if(0 == strcmp(option_values.filenames[i], "-") && !first)
                                        continue;
-                               retval |= decode_file(option_values.filenames[i], 0);
+                               retval |= decode_file(option_values.filenames[i]);
                                first = false;
                        }
                }
@@ -426,7 +473,7 @@ int do_it()
                FLAC__bool first = true;
 
                if(option_values.num_files == 0) {
-                       retval = encode_file("-", 0, true);
+                       retval = encode_file("-", first, true);
                }
                else {
                        unsigned i;
@@ -435,9 +482,22 @@ int do_it()
                        for(i = 0, retval = 0; i < option_values.num_files; i++) {
                                if(0 == strcmp(option_values.filenames[i], "-") && !first)
                                        continue;
-                               retval |= encode_file(option_values.filenames[i], 0, i == (option_values.num_files-1));
+                               retval |= encode_file(option_values.filenames[i], first, i == (option_values.num_files-1));
                                first = false;
                        }
+                       if(option_values.replay_gain && retval == 0) {
+                               float album_gain, album_peak;
+                               grabbag__replaygain_get_album(&album_gain, &album_peak);
+                               for(i = 0; i < option_values.num_files; i++) {
+                                       const char *error, *outfilename = get_encoded_outfilename(option_values.filenames[i]);
+                                       if(0 == strcmp(option_values.filenames[i], "-"))
+                                               FLAC__ASSERT(0);
+                                       if(0 != (error = grabbag__replaygain_store_to_file_album(outfilename, album_gain, album_peak, /*preserve_modtime=*/true))) {
+                                               fprintf(stderr, "%s: ERROR writing ReplayGain album tags\n", outfilename);
+                                               retval = 1;
+                                       }
+                               }
+                       }
                }
        }
 
@@ -466,15 +526,16 @@ FLAC__bool init_options()
        option_values.force_to_stdout = false;
        option_values.force_raw_format = false;
        option_values.delete_input = false;
+       option_values.replay_gain = false;
        option_values.sector_align = false;
        option_values.cmdline_forced_outfilename = 0;
        option_values.output_prefix = 0;
        option_values.aopts.do_residual_text = false;
        option_values.aopts.do_residual_gnuplot = false;
-       option_values.padding = -1;
+       option_values.padding = 4096;
        option_values.max_lpc_order = 8;
        option_values.qlp_coeff_precision = 0;
-       option_values.skip = 0;
+       option_values.skip_specification = 0;
        option_values.format_is_big_endian = -1;
        option_values.format_is_unsigned_samples = -1;
        option_values.format_channels = -1;
@@ -486,6 +547,8 @@ FLAC__bool init_options()
        option_values.rice_parameter_search_dist = -1;
        option_values.requested_seek_points[0] = '\0';
        option_values.num_requested_seek_points = -1;
+       option_values.cuesheet_filename = 0;
+       option_values.cued_seekpoints = true;
 
        option_values.num_files = 0;
        option_values.filenames = 0;
@@ -493,6 +556,10 @@ FLAC__bool init_options()
        if(0 == (option_values.vorbis_comment = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT)))
                return false;
 
+       option_values.debug.disable_constant_subframes = false;
+       option_values.debug.disable_fixed_subframes = false;
+       option_values.debug.disable_verbatim_subframes = false;
+
        return true;
 }
 
@@ -504,17 +571,17 @@ int parse_options(int argc, char *argv[])
        /*@@@ E and R: are deprecated */
        const char *short_opts = "0123456789ab:cdeFhHl:mMo:pP:q:r:sS:tT:vV";
 
-       while ((short_option = FLAC__share__getopt_long(argc, argv, short_opts, long_options_, &option_index)) != -1) {
+       while ((short_option = share__getopt_long(argc, argv, short_opts, long_options_, &option_index)) != -1) {
                switch (short_option) {
                        case 0: /* long option with no equivalent short option */
-                               had_error |= (parse_option(short_option, long_options_[option_index].name, FLAC__share__optarg) != 0);
+                               had_error |= (parse_option(short_option, long_options_[option_index].name, share__optarg) != 0);
                                break;
                        case '?':
                        case ':':
                                had_error = true;
                                break;
                        default: /* short option */
-                               had_error |= (parse_option(short_option, 0, FLAC__share__optarg) != 0);
+                               had_error |= (parse_option(short_option, 0, share__optarg) != 0);
                                break;
                }
        }
@@ -523,16 +590,16 @@ int parse_options(int argc, char *argv[])
                return 1;
        }
 
-       FLAC__ASSERT(FLAC__share__optind <= argc);
+       FLAC__ASSERT(share__optind <= argc);
 
-       option_values.num_files = argc - FLAC__share__optind;
+       option_values.num_files = argc - share__optind;
 
        if(option_values.num_files > 0) {
                unsigned i = 0;
                if(0 == (option_values.filenames = malloc(sizeof(char *) * option_values.num_files)))
                        die("out of memory allocating space for file names list");
-               while(FLAC__share__optind < argc)
-                       option_values.filenames[i++] = local_strdup(argv[FLAC__share__optind++]);
+               while(share__optind < argc)
+                       option_values.filenames[i++] = local_strdup(argv[share__optind++]);
        }
 
        return 0;
@@ -553,9 +620,17 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                }
                else if(0 == strcmp(long_option, "skip")) {
                        FLAC__ASSERT(0 != option_argument);
-                       option_values.skip = (FLAC__uint64)atoi(option_argument); /* @@@ takes a pretty damn big file to overflow atoi() here, but it could happen */
+                       option_values.skip_specification = option_argument;
+               }
+               else if(0 == strcmp(long_option, "cuesheet")) {
+                       FLAC__ASSERT(0 != option_argument);
+                       option_values.cuesheet_filename = option_argument;
+               }
+               else if(0 == strcmp(long_option, "no-cued-seekpoints")) {
+                       option_values.cued_seekpoints = false;
                }
-               else if(0 == strcmp(long_option, "super-secret-impractical-compression-level")) {
+               else if(0 == strcmp(long_option, "super-secret-totally-impractical-compression-level")) {
+                       option_values.lax = true;
                        option_values.do_exhaustive_model_search = true;
                        option_values.do_escape_coding = true;
                        option_values.do_mid_side = true;
@@ -572,6 +647,9 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                else if(0 == strcmp(long_option, "lax")) {
                        option_values.lax = true;
                }
+               else if(0 == strcmp(long_option, "replay-gain")) {
+                       option_values.replay_gain = true;
+               }
                else if(0 == strcmp(long_option, "sector-align")) {
                        option_values.sector_align = true;
                }
@@ -636,6 +714,9 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                else if(0 == strcmp(long_option, "no-delete-input-file")) {
                        option_values.delete_input = false;
                }
+               else if(0 == strcmp(long_option, "no-replay-gain")) {
+                       option_values.replay_gain = false;
+               }
                else if(0 == strcmp(long_option, "no-sector-align")) {
                        option_values.sector_align = false;
                }
@@ -677,6 +758,15 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                else if(0 == strcmp(long_option, "no-residual-text")) {
                        option_values.aopts.do_residual_text = false;
                }
+               else if(0 == strcmp(long_option, "disable-constant-subframes")) {
+                       option_values.debug.disable_constant_subframes = true;
+               }
+               else if(0 == strcmp(long_option, "disable-fixed-subframes")) {
+                       option_values.debug.disable_fixed_subframes = true;
+               }
+               else if(0 == strcmp(long_option, "disable-verbatim-subframes")) {
+                       option_values.debug.disable_verbatim_subframes = true;
+               }
        }
        else {
                const char *violation;
@@ -823,8 +913,13 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                                if(option_values.num_requested_seek_points < 0)
                                        option_values.num_requested_seek_points = 0;
                                option_values.num_requested_seek_points++;
-                               strcat(option_values.requested_seek_points, option_argument);
-                               strcat(option_values.requested_seek_points, "<");
+                               if(strlen(option_values.requested_seek_points)+strlen(option_argument)+2 >= sizeof(option_values.requested_seek_points)) {
+                                       return usage_error("ERROR: too many seekpoints requested\n");
+                               }
+                               else {
+                                       strcat(option_values.requested_seek_points, option_argument);
+                                       strcat(option_values.requested_seek_points, ";");
+                               }
                                break;
                        case 'P':
                                FLAC__ASSERT(0 != option_argument);
@@ -886,8 +981,14 @@ int parse_option(int short_option, const char *long_option, const char *option_a
 
 void free_options()
 {
-       if(0 != option_values.filenames)
+       unsigned i;
+       if(0 != option_values.filenames) {
+               for(i = 0; i < option_values.num_files; i++) {
+                       if(0 != option_values.filenames[i])
+                               free(option_values.filenames[i]);
+               }
                free(option_values.filenames);
+       }
        if(0 != option_values.vorbis_comment)
                FLAC__metadata_object_delete(option_values.vorbis_comment);
 }
@@ -982,7 +1083,7 @@ void show_help()
        printf("  -o, --output-name=FILENAME   Force the output file name\n");
        printf("      --output-prefix=STRING   Prepend STRING to output names\n");
        printf("      --delete-input-file      Deletes after a successful encode/decode\n");
-       printf("      --skip=#                 Skip the first # samples of each input file\n");
+       printf("      --skip={#|mm:ss.ss}      Skip the given initial samples for each input\n");
        printf("analysis options:\n");
        printf("      --residual-text          Include residual signal in text output\n");
        printf("      --residual-gnuplot       Generate gnuplot files of residual distribution\n");
@@ -996,9 +1097,11 @@ void show_help()
 #endif
        printf("      --lax                    Allow encoder to generate non-Subset files\n");
        printf("      --sector-align           Align multiple files on sector boundaries\n");
-       printf("  -S, --seekpoint={#|X|#x}     Add seek point(s)\n");
-       printf("  -P, --padding=#              Write a PADDING block of length #\n");
+       printf("      --replay-gain            Calculate ReplayGain & store in Vorbis comments\n");
+       printf("      --cuesheet=FILENAME      Import cuesheet and store in CUESHEET block\n");
        printf("  -T, --tag=FIELD=VALUE        Add a Vorbis comment; may appear multiple times\n");
+       printf("  -S, --seekpoint={#|X|#x|#s}  Add seek point(s)\n");
+       printf("  -P, --padding=#              Write a PADDING block of length #\n");
        printf("  -0, --compression-level-0, --fast  Synonymous with -l 0 -b 1152 -r 2,2\n");
        printf("  -1, --compression-level-1          Synonymous with -l 0 -b 1152 -M -r 2,2\n");
        printf("  -2, --compression-level-2          Synonymous with -l 0 -b 1152 -m -r 3\n");
@@ -1047,6 +1150,7 @@ void show_help()
 #endif
        printf("      --no-padding\n");
        printf("      --no-qlp-coeff-prec-search\n");
+       printf("      --no-replay-gain\n");
        printf("      --no-residual-gnuplot\n");
        printf("      --no-residual-text\n");
        printf("      --no-sector-align\n");
@@ -1100,8 +1204,10 @@ void show_explain()
        printf("                               successful encode or decode.  If there was an\n");
        printf("                               error (including a verify error) the input file\n");
        printf("                               is left intact.\n");
-       printf("      --skip=#                 Skip the first # samples of each input file; can\n");
-       printf("                               be used both for encoding and decoding\n");
+       printf("      --skip={#|mm:ss.ss}      Skip the first # samples of each input file; can\n");
+       printf("                               be used both for encoding and decoding.  The\n");
+       printf("                               alternative form mm:ss.ss can be used to specify\n");
+       printf("                               minutes, seconds, and fractions of a second.\n");
        printf("analysis options:\n");
        printf("      --residual-text          Include residual signal in text output.  This\n");
        printf("                               will make the file very big, much larger than\n");
@@ -1139,15 +1245,35 @@ void show_explain()
        printf("      --lax                    Allow encoder to generate non-Subset files\n");
        printf("      --sector-align           Align encoding of multiple CD format WAVE files\n");
        printf("                               on sector boundaries.\n");
-       printf("  -S, --seekpoint={#|X|#x}     Include a point or points in a SEEKTABLE\n");
+       printf("      --replay-gain            Calculate ReplayGain values and store in Vorbis\n");
+       printf("                               comments.  Title gains/peaks will be computed\n");
+       printf("                               for each file, and an album gain/peak will be\n");
+       printf("                               computed for all files.  All input files must\n");
+       printf("                               have the same resolution, sample rate, and\n");
+       printf("                               number of channels.  The sample rate must be\n");
+       printf("                               one of 8, 11.025, 12, 16, 22.05, 24, 32, 44.1,\n");
+       printf("                               or 48 kHz.  NOTE: this option may also leave a\n");
+       printf("                               few extra bytes in the PADDING block.\n");
+       printf("      --cuesheet=FILENAME      Import the given cuesheet file and store it in\n");
+       printf("                               a CUESHEET metadata block.  This option may only\n");
+       printf("                               be used when encoding a single file.  A\n");
+       printf("                               seekpoint will be added for each index point in\n");
+       printf("                               the cuesheet to the SEEKTABLE unless\n");
+       printf("                               --no-cued-seekpoints is specified.\n");
+       printf("  -T, --tag=FIELD=VALUE        Add a Vorbis comment.  Make sure to quote the\n");
+       printf("                               comment if necessary.  This option may appear\n");
+       printf("                               more than once to add several comments.  NOTE:\n");
+       printf("                               all tags will be added to all encoded files.\n");
+       printf("  -S, --seekpoint={#|X|#x|#s}  Include a point or points in a SEEKTABLE\n");
        printf("       #  : a specific sample number for a seek point\n");
        printf("       X  : a placeholder point (always goes at the end of the SEEKTABLE)\n");
        printf("       #x : # evenly spaced seekpoints, the first being at sample 0\n");
+       printf("       #s : a seekpoint every # seconds; # does not have to be a whole number\n");
        printf("     You may use many -S options; the resulting SEEKTABLE will be the unique-\n");
        printf("           ified union of all such values.\n");
        printf("     With no -S options, flac defaults to '-S 100x'.  Use -S- for no SEEKTABLE.\n");
-       printf("     Note: -S #x will not work if the encoder can't determine the input size\n");
-       printf("           before starting.\n");
+       printf("     Note: -S #x and -S #s will not work if the encoder can't determine the\n");
+       printf("           input size before starting.\n");
        printf("     Note: if you use -S # and # is >= samples in the input, there will be\n");
        printf("           either no seek point entered (if the input size is determinable\n");
        printf("           before encoding starts) or a placeholder point (if input size is not\n");
@@ -1169,10 +1295,6 @@ void show_explain()
        printf("                               576, 1152, 2304, 4608, 256, 512, 1024, 2048,\n");
        printf("                               4096, 8192, 16384, or 32768 (unless --lax is\n");
        printf("                               used)\n");
-       printf("  -T, --tag=FIELD=VALUE        Add a Vorbis comment.  Make sure to quote the\n");
-       printf("                               comment if necessary.  This option may appear\n");
-       printf("                               more than once to add several comments.  NOTE:\n");
-       printf("                               all tags will be added to all encoded files.\n");
        printf("  -0, --compression-level-0, --fast  Synonymous with -l 0 -b 1152 -r 2,2\n");
        printf("  -1, --compression-level-1          Synonymous with -l 0 -b 1152 -M -r 2,2\n");
        printf("  -2, --compression-level-2          Synonymous with -l 0 -b 1152 -m -r 3\n");
@@ -1251,24 +1373,23 @@ format_mistake(const char *infilename, const char *wrong, const char *right)
        fprintf(stderr, "WARNING: %s is not a %s file; treating as a %s file\n", infilename, wrong, right);
 }
 
-int encode_file(const char *infilename, const char *forced_outfilename, FLAC__bool is_last_file)
+int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_last_file)
 {
        FILE *encode_infile;
-       char outfilename[4096]; /* @@@ bad MAGIC NUMBER */
-       char *p;
        FLAC__byte lookahead[12];
        unsigned lookahead_length = 0;
        FileFormat fmt= RAW;
        int retval;
        long infilesize;
        encode_options_t common_options;
+       const char *outfilename = get_encoded_outfilename(infilename);
 
        if(0 == strcmp(infilename, "-")) {
                infilesize = -1;
-               encode_infile = file__get_binary_stdin();
+               encode_infile = grabbag__file_get_binary_stdin();
        }
        else {
-               infilesize = flac__file_get_filesize(infilename);
+               infilesize = grabbag__file_get_filesize(infilename);
                if(0 == (encode_infile = fopen(infilename, "rb"))) {
                        fprintf(stderr, "ERROR: can't open input file %s\n", infilename);
                        return 1;
@@ -1313,30 +1434,15 @@ int encode_file(const char *infilename, const char *forced_outfilename, FLAC__bo
                        return usage_error("ERROR: for encoding a raw file you must specify a value for --endian, --sign, --channels, --bps, and --sample-rate\n");
        }
 
-       if(encode_infile == stdin || option_values.force_to_stdout)
-               strcpy(outfilename, "-");
-       else {
-               const char *suffix = (option_values.use_ogg? ogg_suffix : flac_suffix);
-               strcpy(outfilename, option_values.output_prefix? option_values.output_prefix : "");
-               strcat(outfilename, infilename);
-               if(0 == (p = strrchr(outfilename, '.')))
-                       strcat(outfilename, suffix);
-               else {
-                       if(0 == strcmp(p, suffix)) {
-                               strcpy(p, "_new");
-                               strcat(p, suffix);
-                       }
-                       else
-                               strcpy(p, suffix);
-               }
+       if(encode_infile == stdin || option_values.force_to_stdout) {
+               if(option_values.replay_gain)
+                       return usage_error("ERROR: --replay-gain cannot be used when encoding to stdout\n");
        }
-       if(0 == forced_outfilename)
-               forced_outfilename = outfilename;
-       if(0 != option_values.cmdline_forced_outfilename)
-               forced_outfilename = option_values.cmdline_forced_outfilename;
+
+       if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &common_options.skip_specification) || common_options.skip_specification.is_relative)
+               return usage_error("ERROR: invalid value for --skip\n");
 
        common_options.verbose = option_values.verbose;
-       common_options.skip = option_values.skip;
        common_options.verify = option_values.verify;
 #ifdef FLAC__HAS_OGG
        common_options.use_ogg = option_values.use_ogg;
@@ -1358,11 +1464,18 @@ int encode_file(const char *infilename, const char *forced_outfilename, FLAC__bo
        common_options.padding = option_values.padding;
        common_options.requested_seek_points = option_values.requested_seek_points;
        common_options.num_requested_seek_points = option_values.num_requested_seek_points;
+       common_options.cuesheet_filename = option_values.cuesheet_filename;
+       common_options.cued_seekpoints = option_values.cued_seekpoints;
+       common_options.is_first_file = is_first_file;
        common_options.is_last_file = is_last_file;
        common_options.align_reservoir = align_reservoir;
        common_options.align_reservoir_samples = &align_reservoir_samples;
+       common_options.replay_gain = option_values.replay_gain;
        common_options.sector_align = option_values.sector_align;
        common_options.vorbis_comment = option_values.vorbis_comment;
+       common_options.debug.disable_constant_subframes = option_values.debug.disable_constant_subframes;
+       common_options.debug.disable_fixed_subframes = option_values.debug.disable_fixed_subframes;
+       common_options.debug.disable_verbatim_subframes = option_values.debug.disable_verbatim_subframes;
 
        if(fmt == RAW) {
                raw_encode_options_t options;
@@ -1374,7 +1487,7 @@ int encode_file(const char *infilename, const char *forced_outfilename, FLAC__bo
                options.bps = option_values.format_bps;
                options.sample_rate = option_values.format_sample_rate;
 
-               retval = flac__encode_raw(encode_infile, infilesize, infilename, forced_outfilename, lookahead, lookahead_length, options);
+               retval = flac__encode_raw(encode_infile, infilesize, infilename, outfilename, lookahead, lookahead_length, options);
        }
        else {
                wav_encode_options_t options;
@@ -1382,14 +1495,23 @@ int encode_file(const char *infilename, const char *forced_outfilename, FLAC__bo
                options.common = common_options;
 
                if(fmt == AIF)
-                       retval = flac__encode_aif(encode_infile, infilesize, infilename, forced_outfilename, lookahead, lookahead_length, options);
+                       retval = flac__encode_aif(encode_infile, infilesize, infilename, outfilename, lookahead, lookahead_length, options);
                else
-                       retval = flac__encode_wav(encode_infile, infilesize, infilename, forced_outfilename, lookahead, lookahead_length, options);
+                       retval = flac__encode_wav(encode_infile, infilesize, infilename, outfilename, lookahead, lookahead_length, options);
        }
 
        if(retval == 0 && strcmp(infilename, "-")) {
-               if(strcmp(forced_outfilename, "-"))
-                       flac__file_copy_metadata(infilename, forced_outfilename);
+               if(strcmp(outfilename, "-")) {
+                       if(option_values.replay_gain) {
+                               float title_gain, title_peak;
+                               const char *error;
+                               grabbag__replaygain_get_title(&title_gain, &title_peak);
+                               if(0 != (error = grabbag__replaygain_store_to_file_title(outfilename, title_gain, title_peak, /*preserve_modtime=*/true))) {
+                                       fprintf(stderr, "%s: ERROR writing ReplayGain title tags\n", outfilename);
+                               }
+                       }
+                       grabbag__file_copy_metadata(infilename, outfilename);
+               }
                if(option_values.delete_input)
                        unlink(infilename);
        }
@@ -1397,42 +1519,18 @@ int encode_file(const char *infilename, const char *forced_outfilename, FLAC__bo
        return retval;
 }
 
-int decode_file(const char *infilename, const char *forced_outfilename)
+int decode_file(const char *infilename)
 {
-       static const char *suffixes[] = { ".wav", ".raw", ".ana" };
-       char outfilename[4096]; /* @@@ bad MAGIC NUMBER */
-       char *p;
        int retval;
        FLAC__bool treat_as_ogg = false;
        decode_options_t common_options;
+       const char *outfilename = get_decoded_outfilename(infilename);
 
        if(!option_values.test_only && !option_values.analyze) {
                if(option_values.force_raw_format && (option_values.format_is_big_endian < 0 || option_values.format_is_unsigned_samples < 0))
                        return usage_error("ERROR: for decoding to a raw file you must specify a value for --endian and --sign\n");
        }
 
-       if(0 == strcmp(infilename, "-") || option_values.force_to_stdout)
-               strcpy(outfilename, "-");
-       else {
-               const char *suffix = suffixes[option_values.analyze? 2 : option_values.force_raw_format? 1 : 0];
-               strcpy(outfilename, option_values.output_prefix? option_values.output_prefix : "");
-               strcat(outfilename, infilename);
-               if(0 == (p = strrchr(outfilename, '.')))
-                       strcat(outfilename, suffix);
-               else {
-                       if(0 == strcmp(p, suffix)) {
-                               strcpy(p, "_new");
-                               strcat(p, suffix);
-                       }
-                       else
-                               strcpy(p, suffix);
-               }
-       }
-       if(0 == forced_outfilename)
-               forced_outfilename = outfilename;
-       if(0 != option_values.cmdline_forced_outfilename)
-               forced_outfilename = option_values.cmdline_forced_outfilename;
-
        if(option_values.use_ogg)
                treat_as_ogg = true;
        else if(0 == strcasecmp(infilename+(strlen(infilename)-4), ".ogg"))
@@ -1447,6 +1545,9 @@ int decode_file(const char *infilename, const char *forced_outfilename)
        }
 #endif
 
+       if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &common_options.skip_specification) || common_options.skip_specification.is_relative)
+               return usage_error("ERROR: invalid value for --skip\n");
+
        common_options.verbose = option_values.verbose;
        common_options.continue_through_decode_errors = option_values.continue_through_decode_errors;
 #ifdef FLAC__HAS_OGG
@@ -1454,14 +1555,13 @@ int decode_file(const char *infilename, const char *forced_outfilename)
        common_options.use_first_serial_number = !option_values.has_serial_number;
        common_options.serial_number = option_values.serial_number;
 #endif
-       common_options.skip = option_values.skip;
 
        if(!option_values.force_raw_format) {
                wav_decode_options_t options;
 
                options.common = common_options;
 
-               retval = flac__decode_wav(infilename, option_values.test_only? 0 : forced_outfilename, option_values.analyze, option_values.aopts, options);
+               retval = flac__decode_wav(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, options);
        }
        else {
                raw_decode_options_t options;
@@ -1470,12 +1570,12 @@ int decode_file(const char *infilename, const char *forced_outfilename)
                options.is_big_endian = option_values.format_is_big_endian;
                options.is_unsigned_samples = option_values.format_is_unsigned_samples;
 
-               retval = flac__decode_raw(infilename, option_values.test_only? 0 : forced_outfilename, option_values.analyze, option_values.aopts, options);
+               retval = flac__decode_raw(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, options);
        }
 
        if(retval == 0 && strcmp(infilename, "-")) {
-               if(strcmp(forced_outfilename, "-"))
-                       flac__file_copy_metadata(infilename, forced_outfilename);
+               if(strcmp(outfilename, "-"))
+                       grabbag__file_copy_metadata(infilename, outfilename);
                if(option_values.delete_input && !option_values.test_only && !option_values.analyze)
                        unlink(infilename);
        }
@@ -1483,6 +1583,67 @@ int decode_file(const char *infilename, const char *forced_outfilename)
        return retval;
 }
 
+const char *get_encoded_outfilename(const char *infilename)
+{
+       if(0 == option_values.cmdline_forced_outfilename) {
+               static char buffer[4096]; /* @@@ bad MAGIC NUMBER */
+
+               if(0 == strcmp(infilename, "-") || option_values.force_to_stdout) {
+                       strcpy(buffer, "-");
+               }
+               else {
+                       const char *suffix = (option_values.use_ogg? ".ogg" : ".flac");
+                       char *p;
+                       strcpy(buffer, option_values.output_prefix? option_values.output_prefix : "");
+                       strcat(buffer, infilename);
+                       if(0 == (p = strrchr(buffer, '.')))
+                               strcat(buffer, suffix);
+                       else {
+                               if(0 == strcmp(p, suffix)) {
+                                       strcpy(p, "_new");
+                                       strcat(p, suffix);
+                               }
+                               else
+                                       strcpy(p, suffix);
+                       }
+               }
+               return buffer;
+       }
+       else
+               return option_values.cmdline_forced_outfilename;
+}
+
+const char *get_decoded_outfilename(const char *infilename)
+{
+       if(0 == option_values.cmdline_forced_outfilename) {
+               static char buffer[4096]; /* @@@ bad MAGIC NUMBER */
+
+               if(0 == strcmp(infilename, "-") || option_values.force_to_stdout) {
+                       strcpy(buffer, "-");
+               }
+               else {
+                       static const char *suffixes[] = { ".wav", ".raw", ".ana" };
+                       const char *suffix = suffixes[option_values.analyze? 2 : option_values.force_raw_format? 1 : 0];
+                       char *p;
+                       strcpy(buffer, option_values.output_prefix? option_values.output_prefix : "");
+                       strcat(buffer, infilename);
+                       if(0 == (p = strrchr(buffer, '.')))
+                               strcat(buffer, suffix);
+                       else {
+                               if(0 == strcmp(p, suffix)) {
+                                       strcpy(p, "_new");
+                                       strcat(p, suffix);
+                               }
+                               else
+                                       strcpy(p, suffix);
+                       }
+               }
+               return buffer;
+       }
+       else
+               return option_values.cmdline_forced_outfilename;
+}
+
 void die(const char *message)
 {
        FLAC__ASSERT(0 != message);