minor syntax
[platform/upstream/flac.git] / src / flac / encode.c
index 52fc9e2..5d7fd81 100644 (file)
@@ -1,5 +1,5 @@
 /* flac - Command-line FLAC encoder/decoder
- * Copyright (C) 2000,2001,2002,2003,2004  Josh Coalson
+ * Copyright (C) 2000,2001,2002,2003,2004,2005,2006  Josh Coalson
  *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  */
 
+#if HAVE_CONFIG_H
+#  include <config.h>
+#endif
+
 #if defined _WIN32 && !defined __CYGWIN__
 /* where MSVC puts unlink() */
 # include <io.h>
 #else
 # include <unistd.h>
 #endif
+#if defined _MSC_VER || defined __MINGW32__
+#include <sys/types.h> /* for off_t */
+#if _MSC_VER <= 1200 /* @@@ [2G limit] */
+#define fseeko fseek
+#define ftello ftell
+#endif
+#endif
+#include <errno.h>
 #include <limits.h> /* for LONG_MAX */
 #include <math.h> /* for floor() */
 #include <stdio.h> /* for FILE etc. */
 #include <stdlib.h> /* for malloc */
-#include <string.h> /* for strcmp() */
+#include <string.h> /* for strcmp(), strerror( */
 #include "FLAC/all.h"
 #include "share/grabbag.h"
 #include "encode.h"
 
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#ifdef FLAC__HAS_OGG
-#include "OggFLAC/stream_encoder.h"
-#include "OggFLAC/file_encoder.h"
-#endif
-
 #ifdef min
 #undef min
 #endif
@@ -58,6 +61,7 @@ typedef struct {
 #endif
        FLAC__bool verify;
        FLAC__bool is_stdout;
+       FLAC__bool outputfile_opened; /* true if we successfully opened the output file and we want it to be deleted if there is an error */
        const char *inbasefilename;
        const char *outfilename;
 
@@ -71,31 +75,27 @@ typedef struct {
        FLAC__uint64 total_samples_to_encode;
        FLAC__uint64 bytes_written;
        FLAC__uint64 samples_written;
-       unsigned blocksize;
        unsigned stats_mask;
 
-       /*
-        * We use *.stream for encoding to stdout
-        * We use *.file for encoding to a regular file
-        */
-       union {
-               union {
-                       FLAC__StreamEncoder *stream;
-                       FLAC__FileEncoder *file;
-               } flac;
-#ifdef FLAC__HAS_OGG
-               union {
-                       OggFLAC__StreamEncoder *stream;
-                       OggFLAC__FileEncoder *file;
-               } ogg;
-#endif
-       } encoder;
+       FLAC__StreamEncoder *encoder;
 
        FILE *fin;
-       FILE *fout;
        FLAC__StreamMetadata *seek_table_template;
 } EncoderSession;
 
+/* this is data attached to the FLAC decoder when encoding from a FLAC file */
+typedef struct {
+       EncoderSession *encoder_session;
+       off_t filesize;
+       const FLAC__byte *lookahead;
+       unsigned lookahead_length;
+       size_t num_metadata_blocks;
+       FLAC__StreamMetadata *metadata_blocks[1024]; /*@@@ BAD MAGIC number */
+       FLAC__uint64 samples_left_to_process;
+       FLAC__bool fatal_error;
+} FLACDecoderData;
+
+const int FLAC_ENCODE__DEFAULT_PADDING = 8192;
 
 static FLAC__bool is_big_endian_host_;
 
@@ -114,17 +114,6 @@ static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
 extern FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
 extern FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
 extern FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
-extern FLAC__bool FLAC__file_encoder_disable_constant_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
-extern FLAC__bool FLAC__file_encoder_disable_fixed_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
-extern FLAC__bool FLAC__file_encoder_disable_verbatim_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
-#ifdef FLAC__HAS_OGG
-extern FLAC__bool OggFLAC__stream_encoder_disable_constant_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
-extern FLAC__bool OggFLAC__stream_encoder_disable_fixed_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
-extern FLAC__bool OggFLAC__stream_encoder_disable_verbatim_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
-extern FLAC__bool OggFLAC__file_encoder_disable_constant_subframes(OggFLAC__FileEncoder *encoder, FLAC__bool value);
-extern FLAC__bool OggFLAC__file_encoder_disable_fixed_subframes(OggFLAC__FileEncoder *encoder, FLAC__bool value);
-extern FLAC__bool OggFLAC__file_encoder_disable_verbatim_subframes(OggFLAC__FileEncoder *encoder, FLAC__bool value);
-#endif
 
 /*
  * local routines
@@ -133,21 +122,24 @@ static FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg
 static void EncoderSession_destroy(EncoderSession *e);
 static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero);
 static int EncoderSession_finish_error(EncoderSession *e);
-static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate);
+static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, FLAC__uint32 channel_mask, unsigned channels, unsigned bps, unsigned sample_rate, FLACDecoderData *flac_decoder_data);
 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
 static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
-static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps);
-#ifdef FLAC__HAS_OGG
-static FLAC__StreamEncoderWriteStatus ogg_stream_encoder_write_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
-static void ogg_stream_encoder_metadata_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
-static void ogg_file_encoder_progress_callback(const OggFLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
-#endif
-static FLAC__StreamEncoderWriteStatus flac_stream_encoder_write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
-static void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
-static void flac_file_encoder_progress_callback(const FLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
-static FLAC__bool parse_cuesheet_(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset);
+static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata);
+static FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift, size_t *channel_map);
+static void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
+static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
+static FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
+static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
+static FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
+static FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data);
+static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
+static void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
+static void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
+static FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset);
 static void print_stats(const EncoderSession *encoder_session);
+static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
 static void print_error_with_state(const EncoderSession *e, const char *message);
 static void print_verify_error(EncoderSession *e);
 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
@@ -155,20 +147,23 @@ static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bo
 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
+static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
+static unsigned count_channel_mask_bits(FLAC__uint32 mask);
+static FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels);
 
 /*
  * public routines
  */
-int
-flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const char *outfilename,
-       const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
+int flac__encode_aif(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options, FLAC__bool is_aifc)
 {
        EncoderSession encoder_session;
        FLAC__uint16 x;
        FLAC__uint32 xx;
-       unsigned int channels= 0U, bps= 0U, sample_rate= 0U, sample_frames= 0U;
+       unsigned int channels= 0U, bps= 0U, shift= 0U, sample_rate= 0U, sample_frames= 0U;
+       size_t channel_map[FLAC__MAX_CHANNELS];
        FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
        int info_align_carry= -1, info_align_zero= -1;
+       FLAC__bool is_big_endian_pcm = true;
 
        (void)infilesize; /* silence compiler warning about unused parameter */
        (void)lookahead; /* silence compiler warning about unused parameter */
@@ -190,11 +185,18 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
        )
                return 1;
 
+       /* initialize default channel map that preserves channel order */
+       {
+               size_t i;
+               for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++)
+                       channel_map[i] = i;
+       }
+
        /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
 
        while(1) {
                size_t c= 0U;
-               char chunk_id[4];
+               char chunk_id[5] = { '\0', '\0', '\0', '\0', '\0' }; /* one extra byte for terminating NUL so we can also treat it like a C string */
 
                /* chunk identifier; really conservative about behavior of fread() and feof() */
                if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
@@ -204,20 +206,21 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                        return EncoderSession_finish_error(&encoder_session);
                }
 
-               if(got_comm_chunk==false && !strncmp(chunk_id, "COMM", 4)) { /* common chunk */
+               if(got_comm_chunk==false && !memcmp(chunk_id, "COMM", 4)) { /* common chunk */
                        unsigned long skip;
+                       const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18);
 
                        /* COMM chunk size */
                        if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
                                return EncoderSession_finish_error(&encoder_session);
-                       else if(xx<18U) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
+                       else if(xx<minimum_comm_size) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: non-standard %s 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx);
                                return EncoderSession_finish_error(&encoder_session);
                        }
-                       else if(xx!=18U) {
-                               flac__utils_printf(stderr, 1, "%s: WARNING: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
+                       else if(!is_aifc && xx!=minimum_comm_size) {
+                               flac__utils_printf(stderr, 1, "%s: WARNING: non-standard %s 'COMM' chunk has length = %u, expected %u\n", encoder_session.inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx, minimum_comm_size);
                        }
-                       skip= (xx-18U)+(xx & 1U);
+                       skip= (xx-minimum_comm_size)+(xx & 1U);
 
                        /* number of channels */
                        if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
@@ -226,6 +229,10 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned int)x);
                                return EncoderSession_finish_error(&encoder_session);
                        }
+                       else if(x>2U && !options.common.channel_map_none) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u for AIFF\n", encoder_session.inbasefilename, (unsigned int)x);
+                               return EncoderSession_finish_error(&encoder_session);
+                       }
                        else if(options.common.sector_align && x!=2U) {
                                flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
                                return EncoderSession_finish_error(&encoder_session);
@@ -240,15 +247,17 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                        /* bits per sample */
                        if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
                                return EncoderSession_finish_error(&encoder_session);
-                       else if(x!=8U && x!=16U && x!=24U) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits per sample %u\n", encoder_session.inbasefilename, (unsigned int)x);
+                       else if(x<4U || x>24U) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, (unsigned int)x);
                                return EncoderSession_finish_error(&encoder_session);
                        }
                        else if(options.common.sector_align && x!=16U) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
+                               flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits-per-sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
                                return EncoderSession_finish_error(&encoder_session);
                        }
                        bps= x;
+                       shift= (bps%8)? 8-(bps%8) : 0; /* SSND data is always byte-aligned, left-justified but format_input() will double-check */
+                       bps+= shift;
 
                        /* sample rate */
                        if(!read_sane_extended(infile, &xx, false, encoder_session.inbasefilename))
@@ -263,15 +272,53 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                        }
                        sample_rate= xx;
 
-                       /* skip any extra data in the COMM chunk */
-                       FLAC__ASSERT(skip<=LONG_MAX);
-                       while(skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
-                               unsigned int need= min(skip, sizeof ucbuffer_);
-                               if(fread(ucbuffer_, 1U, need, infile)<need) {
-                                       flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping extra COMM data\n", encoder_session.inbasefilename);
+                       /* check compression type for AIFF-C */
+                       if(is_aifc) {
+                               if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
+                                       return EncoderSession_finish_error(&encoder_session);
+                               if(xx == 0x736F7774) /* "sowt" */
+                                       is_big_endian_pcm = false;
+                               else if(xx == 0x4E4F4E45) /* "NONE" */
+                                       ; /* nothing to do, we already default to big-endian */
+                               else {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR: can't handle AIFF-C compression type \"%c%c%c%c\"\n", encoder_session.inbasefilename, (char)(xx>>24), (char)((xx>>16)&8), (char)((xx>>8)&8), (char)(xx&8));
                                        return EncoderSession_finish_error(&encoder_session);
                                }
-                               skip-= need;
+                       }
+
+                       /* set channel mapping */
+                       /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
+                       /* front left, front right, center, LFE, back left, back right, surround left, surround right */
+                       /* specs say the channel ordering is:
+                        *                             1     2   3   4   5   6
+                        * ___________________________________________________
+                        * 2         stereo            l     r
+                        * 3                           l     r   c
+                        * 4                           l     c   r   S
+                        * quad (ambiguous with 4ch)  Fl    Fr   Bl  Br
+                        * 5                          Fl     Fr  Fc  Sl  Sr
+                        * 6                           l     lc  c   r   rc  S
+                        * l:left r:right c:center Fl:front-left Fr:front-right Bl:back-left Br:back-right Lc:left-center Rc:right-center S:surround
+                        * so we only have unambiguous mappings for 2, 3, and 5 channels
+                        */
+                       if(
+                               options.common.channel_map_none ||
+                               channels == 1 || /* 1 channel: (mono) */
+                               channels == 2 || /* 2 channels: left, right */
+                               channels == 3 || /* 3 channels: left, right, center */
+                               channels == 5    /* 5 channels: front left, front right, center, surround left, surround right */
+                       ) {
+                               /* keep default channel order */
+                       }
+                       else {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u for AIFF\n", encoder_session.inbasefilename, channels);
+                               return EncoderSession_finish_error(&encoder_session);
+                       }
+
+                       /* skip any extra data in the COMM chunk */
+                       if(!fskip_ahead(infile, skip)) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping extra COMM data\n", encoder_session.inbasefilename);
+                               return EncoderSession_finish_error(&encoder_session);
                        }
 
                        /*
@@ -285,7 +332,7 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
 
                        got_comm_chunk= true;
                }
-               else if(got_ssnd_chunk==false && !strncmp(chunk_id, "SSND", 4)) { /* sound data chunk */
+               else if(got_ssnd_chunk==false && !memcmp(chunk_id, "SSND", 4)) { /* sound data chunk */
                        unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
                        size_t bytes_per_frame= channels*(bps>>3);
                        FLAC__uint64 total_samples_in_input, trim = 0;
@@ -318,7 +365,9 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                        }
                        block_size= xx;
 
-                       if(fseek(infile, offset, SEEK_CUR)) {
+                       /* skip any SSND offset bytes */
+                       FLAC__ASSERT(offset<=LONG_MAX);
+                       if(!fskip_ahead(infile, offset)) {
                                flac__utils_printf(stderr, 1, "%s: ERROR: skipping offset in SSND chunk\n", encoder_session.inbasefilename);
                                return EncoderSession_finish_error(&encoder_session);
                        }
@@ -341,25 +390,9 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                        FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
 
                        if(encoder_session.skip>0U) {
-                               FLAC__uint64 remaining= encoder_session.skip*bytes_per_frame;
-
-                               /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
-                               /* is guaranteed to be less than LONG_MAX */
-                               while(remaining>0U)
-                               {
-                                       unsigned long skip= (unsigned long)(remaining % (1U<<30));
-
-                                       FLAC__ASSERT(skip<=LONG_MAX);
-                                       while(skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
-                                               unsigned int need= min(skip, sizeof ucbuffer_);
-                                               if(fread(ucbuffer_, 1U, need, infile)<need) {
-                                                       flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
-                                                       return EncoderSession_finish_error(&encoder_session);
-                                               }
-                                               skip-= need;
-                                       }
-
-                                       remaining-= skip;
+                               if(!fskip_ahead(infile, encoder_session.skip*bytes_per_frame)) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
+                                       return EncoderSession_finish_error(&encoder_session);
                                }
                        }
 
@@ -383,7 +416,7 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                        /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
                        encoder_session.unencoded_size= encoder_session.total_samples_to_encode*bytes_per_frame+54;
 
-                       if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
+                       if(!EncoderSession_init_encoder(&encoder_session, options.common, /*channel_mask=*/0, channels, bps-shift, sample_rate, /*flac_decoder_data=*/0))
                                return EncoderSession_finish_error(&encoder_session);
 
                        /* first do any samples in the reservoir */
@@ -426,7 +459,8 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                                        }
                                        else {
                                                unsigned int frames= bytes_read/bytes_per_frame;
-                                               format_input(input_, frames, true, false, channels, bps);
+                                               if(!format_input(input_, frames, is_big_endian_pcm, /*is_unsigned_samples=*/false, channels, bps, shift, channel_map))
+                                                       return EncoderSession_finish_error(&encoder_session);
 
                                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, frames)) {
                                                        print_error_with_state(&encoder_session, "ERROR during encoding");
@@ -439,27 +473,10 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                        }
 
                        if(trim>0) {
-                               FLAC__uint64 remaining= (unsigned int)trim*bytes_per_frame;
-
                                FLAC__ASSERT(!options.common.sector_align);
-
-                               /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
-                               /* is guaranteed to be less than LONG_MAX */
-                               while(remaining>0U)
-                               {
-                                       unsigned long skip= (unsigned long)(remaining % (1U<<30));
-
-                                       FLAC__ASSERT(skip<=LONG_MAX);
-                                       while(skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
-                                               unsigned int need= min(skip, sizeof ucbuffer_);
-                                               if(fread(ucbuffer_, 1U, need, infile)<need) {
-                                                       flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
-                                                       return EncoderSession_finish_error(&encoder_session);
-                                               }
-                                               skip-= need;
-                                       }
-
-                                       remaining-= skip;
+                               if(!fskip_ahead(infile, trim*bytes_per_frame)) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
+                                       return EncoderSession_finish_error(&encoder_session);
                                }
                        }
 
@@ -473,7 +490,7 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
 
                                                info_align_zero= pad_frames;
                                                for(i= 0U; i<channels; ++i)
-                                                       memset(input_[i], 0, pad_frames*(bps>>3));
+                                                       memset(input_[i], 0, sizeof(input_[0][0])*pad_frames);
 
                                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, pad_frames)) {
                                                        print_error_with_state(&encoder_session, "ERROR during encoding");
@@ -495,7 +512,8 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                                                }
                                                else {
                                                        info_align_carry= *options.common.align_reservoir_samples;
-                                                       format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, true, false, channels, bps);
+                                                       if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, is_big_endian_pcm, /*is_unsigned_samples=*/false, channels, bps, shift, channel_map))
+                                                               return EncoderSession_finish_error(&encoder_session);
                                                }
                                        }
                                }
@@ -513,10 +531,10 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                        got_ssnd_chunk= true;
                }
                else { /* other chunk */
-                       if(!strncmp(chunk_id, "COMM", 4)) {
+                       if(!memcmp(chunk_id, "COMM", 4)) {
                                flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_session.inbasefilename);
                        }
-                       else if(!strncmp(chunk_id, "SSND", 4)) {
+                       else if(!memcmp(chunk_id, "SSND", 4)) {
                                flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_session.inbasefilename);
                        }
                        else {
@@ -530,13 +548,9 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
                                unsigned long skip= xx+(xx & 1U);
 
                                FLAC__ASSERT(skip<=LONG_MAX);
-                               while(skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
-                                       unsigned int need= min(skip, sizeof ucbuffer_);
-                                       if(fread(ucbuffer_, 1U, need, infile)<need) {
-                                               fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_session.inbasefilename);
-                                               return EncoderSession_finish_error(&encoder_session);
-                                       }
-                                       skip-= need;
+                               if(!fskip_ahead(infile, skip)) {
+                                       fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_session.inbasefilename);
+                                       return EncoderSession_finish_error(&encoder_session);
                                }
                        }
                }
@@ -550,14 +564,15 @@ flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const ch
        return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
 }
 
-int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
+int flac__encode_wav(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
 {
        EncoderSession encoder_session;
        FLAC__bool is_unsigned_samples = false;
-       unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
+       unsigned channels = 0, bps = 0, sample_rate = 0, shift = 0;
        size_t bytes_per_wide_sample, bytes_read;
-       FLAC__uint16 x;
-       FLAC__uint32 xx;
+       size_t channel_map[FLAC__MAX_CHANNELS];
+       FLAC__uint16 x, format; /* format is the wFormatTag word from the 'fmt ' chunk */
+       FLAC__uint32 xx, channel_mask = 0;
        FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
        unsigned align_remainder = 0;
        int info_align_carry = -1, info_align_zero = -1;
@@ -582,6 +597,13 @@ int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, cons
        )
                return 1;
 
+       /* initialize default channel map that preserves channel order */
+       {
+               size_t i;
+               for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++)
+                       channel_map[i] = i;
+       }
+
        /*
         * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
         */
@@ -591,87 +613,254 @@ int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, cons
                if(feof(infile))
                        break;
                if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
-                       unsigned block_align;
+                       unsigned block_align, data_bytes;
+
+                       /* see
+                        *   http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
+                        *   http://windowssdk.msdn.microsoft.com/en-us/library/ms713497.aspx
+                        *   http://msdn.microsoft.com/library/default.asp?url=/library/en-us/audio_r/hh/Audio_r/aud-prop_d40f094e-44f9-4baa-8a15-03e4fb369501.xml.asp
+                        *
+                        * WAVEFORMAT is
+                        * 4 byte: subchunk size
+                        * 2 byte: format type: 1 for WAVE_FORMAT_PCM, 65534 for WAVE_FORMAT_EXTENSIBLE
+                        * 2 byte: # channels
+                        * 4 byte: sample rate (Hz)
+                        * 4 byte: avg bytes per sec
+                        * 2 byte: block align
+                        * 2 byte: bits per sample (not necessarily all significant)
+                        * WAVEFORMAT adds
+                        * 2 byte: extension size in bytes (usually 0 for WAVEFORMATEX and 22 for WAVEFORMATEXTENSIBLE with PCM)
+                        * WAVEFORMATEXTENSIBLE adds
+                        * 2 byte: valid bits per sample
+                        * 4 byte: channel mask
+                        * 16 byte: subformat GUID, first 2 bytes have format type, 1 being PCM
+                        *
+                        * Current spec says WAVEFORMATEX with PCM must have bps == 8 or 16, or any multiple of 8 for WAVEFORMATEXTENSIBLE.
+                        * Lots of old broken WAVEs/apps have don't follow it, e.g. 20 bps but a block align of 3/6 for mono/stereo.
+                        *
+                        * Block align for WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE is also supposed to be channels*bps/8
+                        *
+                        * If the channel mask has more set bits than # of channels, the extra MSBs are ignored.
+                        * If the channel mask has less set bits than # of channels, the extra channels are unassigned to any speaker.
+                        *
+                        * Data is supposed to be unsigned for bps <= 8 else signed.
+                        */
 
                        /* fmt sub-chunk size */
                        if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
                                return EncoderSession_finish_error(&encoder_session);
-                       if(xx < 16) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
+                       data_bytes = xx;
+                       if(data_bytes < 16) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, data_bytes);
                                return EncoderSession_finish_error(&encoder_session);
                        }
-                       else if(xx != 16 && xx != 18) {
-                               flac__utils_printf(stderr, 1, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
-                       }
-                       data_bytes = xx;
-                       /* compression code */
-                       if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
+                       /* format code */
+                       if(!read_little_endian_uint16(infile, &format, false, encoder_session.inbasefilename))
                                return EncoderSession_finish_error(&encoder_session);
-                       if(x != 1) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported compression type %u\n", encoder_session.inbasefilename, (unsigned)x);
+                       if(format != 1 /*WAVE_FORMAT_PCM*/ && format != 65534 /*WAVE_FORMAT_EXTENSIBLE*/) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", encoder_session.inbasefilename, (unsigned)format);
                                return EncoderSession_finish_error(&encoder_session);
                        }
                        /* number of channels */
                        if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
                                return EncoderSession_finish_error(&encoder_session);
-                       if(x == 0 || x > FLAC__MAX_CHANNELS) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned)x);
+                       channels = (unsigned)x;
+                       if(channels == 0 || channels > FLAC__MAX_CHANNELS) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u\n", encoder_session.inbasefilename, channels);
                                return EncoderSession_finish_error(&encoder_session);
                        }
-                       else if(options.common.sector_align && x != 2) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
+                       else if(options.common.sector_align && channels != 2) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, channels);
                                return EncoderSession_finish_error(&encoder_session);
                        }
-                       channels = x;
                        /* sample rate */
                        if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
                                return EncoderSession_finish_error(&encoder_session);
-                       if(!FLAC__format_sample_rate_is_valid(xx)) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned)xx);
+                       sample_rate = xx;
+                       if(!FLAC__format_sample_rate_is_valid(sample_rate)) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, sample_rate);
                                return EncoderSession_finish_error(&encoder_session);
                        }
-                       else if(options.common.sector_align && xx != 44100) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned)xx);
+                       else if(options.common.sector_align && sample_rate != 44100) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, sample_rate);
                                return EncoderSession_finish_error(&encoder_session);
                        }
-                       sample_rate = xx;
                        /* avg bytes per second (ignored) */
                        if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
                                return EncoderSession_finish_error(&encoder_session);
                        /* block align */
                        if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
                                return EncoderSession_finish_error(&encoder_session);
-                       block_align = x;
+                       block_align = (unsigned)x;
                        /* bits per sample */
                        if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
                                return EncoderSession_finish_error(&encoder_session);
-                       if(x != 8 && x != 16 && x != 24) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, (unsigned)x);
-                               return EncoderSession_finish_error(&encoder_session);
+                       bps = (unsigned)x;
+                       is_unsigned_samples = (bps <= 8);
+                       if(format == 1) {
+                               if(bps != 8 && bps != 16) {
+                                       if(bps == 24 || bps == 32) {
+                                               /* let these slide with a warning since they're unambiguous */
+                                               flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file has format type %u but bits-per-sample=%u\n", encoder_session.inbasefilename, (unsigned)format, bps);
+                                       }
+                                       else {
+                                               /* @@@ we could add an option to specify left- or right-justified blocks so we knew how to set 'shift' */
+                                               flac__utils_printf(stderr, 1, "%s: ERROR: legacy WAVE file has format type %u but bits-per-sample=%u\n", encoder_session.inbasefilename, (unsigned)format, bps);
+                                               return EncoderSession_finish_error(&encoder_session);
+                                       }
+                               }
+#if 0 /* @@@ reinstate once we can get an answer about whether the samples are left- or right-justified */
+                               if((bps+7)/8 * channels == block_align) {
+                                       if(bps % 8) {
+                                               /* assume legacy file is byte aligned with some LSBs zero; this is double-checked in format_input() */
+                                               flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", encoder_session.inbasefilename, (unsigned)format, block_align, bps, channels);
+                                               shift = 8 - (bps % 8);
+                                               bps += shift;
+                                       }
+                                       else
+                                               shift = 0;
+                               }
+                               else {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR: illegal WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", encoder_session.inbasefilename, (unsigned)format, block_align, bps, channels);
+                                       return EncoderSession_finish_error(&encoder_session);
+                               }
+#else
+                               shift = 0;
+#endif
+                               if(channels > 2 && !options.common.channel_map_none) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR: WAVE has >2 channels but is not WAVE_FORMAT_EXTENSIBLE; cannot assign channels\n", encoder_session.inbasefilename);
+                                       return EncoderSession_finish_error(&encoder_session);
+                               }
+                               FLAC__ASSERT(data_bytes >= 16);
+                               data_bytes -= 16;
                        }
-                       else if(options.common.sector_align && x != 16) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
+                       else {
+                               if(data_bytes < 40) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with size %u\n", encoder_session.inbasefilename, data_bytes);
+                                       return EncoderSession_finish_error(&encoder_session);
+                               }
+                               /* cbSize */
+                               if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
+                                       return EncoderSession_finish_error(&encoder_session);
+                               if(x < 22) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with cbSize %u\n", encoder_session.inbasefilename, (unsigned)x);
+                                       return EncoderSession_finish_error(&encoder_session);
+                               }
+                               /* valid bps */
+                               if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
+                                       return EncoderSession_finish_error(&encoder_session);
+                               if((unsigned)x > bps) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", encoder_session.inbasefilename, (unsigned)x, bps);
+                                       return EncoderSession_finish_error(&encoder_session);
+                               }
+                               shift = bps - (unsigned)x;
+                               /* channel mask */
+                               if(!read_little_endian_uint32(infile, &channel_mask, false, encoder_session.inbasefilename))
+                                       return EncoderSession_finish_error(&encoder_session);
+                               /* for mono/stereo and unassigned channels, we fake the mask */
+                               if(channel_mask == 0) {
+                                       if(channels == 1)
+                                               channel_mask = 0x0001;
+                                       else if(channels == 2)
+                                               channel_mask = 0x0003;
+                               }
+                               /* set channel mapping */
+                               /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
+                               /* front left, front right, center, LFE, back left, back right, surround left, surround right */
+                               /* the default mapping is sufficient for 1-6 channels and 7-8 are currently unspecified anyway */
+#if 0
+                               /* @@@ example for dolby/vorbis order, for reference later in case it becomes important */
+                               if(
+                                       options.common.channel_map_none ||
+                                       channel_mask == 0x0001 || /* 1 channel: (mono) */
+                                       channel_mask == 0x0003 || /* 2 channels: front left, front right */
+                                       channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
+                                       channel_mask == 0x0603    /* 4 channels: front left, front right, side left, side right */
+                               ) {
+                                       /* keep default channel order */
+                               }
+                               else if(
+                                       channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
+                                       channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
+                                       channel_mask == 0x0607    /* 5 channels: front left, front right, front center, side left, side right */
+                               ) {
+                                       /* to dolby order: front left, center, front right [, surround left, surround right ] */
+                                       channel_map[1] = 2;
+                                       channel_map[2] = 1;
+                               }
+                               else if(
+                                       channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
+                                       channel_mask == 0x060f    /* 6 channels: front left, front right, front center, LFE, side left, side right */
+                               ) {
+                                       /* to dolby order: front left, center, front right, surround left, surround right, LFE */
+                                       channel_map[1] = 2;
+                                       channel_map[2] = 1;
+                                       channel_map[3] = 5;
+                                       channel_map[4] = 3;
+                                       channel_map[5] = 4;
+                               }
+#else
+                               if(
+                                       options.common.channel_map_none ||
+                                       channel_mask == 0x0001 || /* 1 channel: (mono) */
+                                       channel_mask == 0x0003 || /* 2 channels: front left, front right */
+                                       channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
+                                       channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
+                                       channel_mask == 0x0603 || /* 4 channels: front left, front right, side left, side right */
+                                       channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
+                                       channel_mask == 0x0607 || /* 5 channels: front left, front right, front center, side left, side right */
+                                       channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
+                                       channel_mask == 0x060f    /* 6 channels: front left, front right, front center, LFE, side left, side right */
+                               ) {
+                                       /* keep default channel order */
+                               }
+#endif
+                               else {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk with unsupported channel mask=0x%04X\n", encoder_session.inbasefilename, (unsigned)channel_mask);
+                                       return EncoderSession_finish_error(&encoder_session);
+                               }
+                               if(!options.common.channel_map_none) {
+                                       if(count_channel_mask_bits(channel_mask) < channels) {
+                                               flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has unassigned channels (#channels=%u)\n", encoder_session.inbasefilename, (unsigned)channel_mask, channels);
+                                               return EncoderSession_finish_error(&encoder_session);
+                                       }
+#if 0
+                                       /* supporting this is too difficult with channel mapping; e.g. what if mask is 0x003f but #channels=4?
+                                        * there would be holes in the order that would have to be filled in, or the mask would have to be
+                                        * limited and the logic above rerun to see if it still fits into the FLAC mapping.
+                                        */
+                                       else if(count_channel_mask_bits(channel_mask) > channels)
+                                               channel_mask = limit_channel_mask(channel_mask, channels);
+#else
+                                       else if(count_channel_mask_bits(channel_mask) > channels) {
+                                               flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has extra bits for non-existant channels (#channels=%u)\n", encoder_session.inbasefilename, (unsigned)channel_mask, channels);
+                                               return EncoderSession_finish_error(&encoder_session);
+                                       }
+#endif
+                               }
+                               /* first part of GUID */
+                               if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
+                                       return EncoderSession_finish_error(&encoder_session);
+                               if(x != 1) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE chunk with non-PCM format %u\n", encoder_session.inbasefilename, (unsigned)x);
+                                       return EncoderSession_finish_error(&encoder_session);
+                               }
+                               data_bytes -= 26;
+                       }
+
+                       if(bps-shift < 4 || bps-shift > 24) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, bps-shift);
                                return EncoderSession_finish_error(&encoder_session);
                        }
-                       bps = x;
-                       if(bps * channels != block_align * 8) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR: unsupported block alignment (%u), for bits-per-sample=%u, channels=%u\n", encoder_session.inbasefilename, block_align, bps, channels);
+                       else if(options.common.sector_align && bps-shift != 16) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits-per-sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, bps-shift);
                                return EncoderSession_finish_error(&encoder_session);
                        }
-                       is_unsigned_samples = (x == 8);
 
                        /* skip any extra data in the fmt sub-chunk */
-                       data_bytes -= 16;
-                       if(data_bytes > 0) {
-                               unsigned left, need;
-                               for(left = data_bytes; left > 0; ) {
-                                       need = min(left, CHUNK_OF_SAMPLES);
-                                       if(fread(ucbuffer_, 1U, need, infile) < need) {
-                                               flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
-                                               return EncoderSession_finish_error(&encoder_session);
-                                       }
-                                       left -= need;
-                               }
+                       if(!fskip_ahead(infile, data_bytes)) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping extra 'fmt' data\n", encoder_session.inbasefilename);
+                               return EncoderSession_finish_error(&encoder_session);
                        }
 
                        /*
@@ -688,6 +877,7 @@ int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, cons
                else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
                        FLAC__uint64 total_samples_in_input, trim = 0;
                        FLAC__bool pad = false;
+                       unsigned data_bytes;
 
                        /* data size */
                        if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
@@ -711,17 +901,9 @@ int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, cons
                        FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
 
                        if(encoder_session.skip > 0) {
-                               if(fseek(infile, bytes_per_wide_sample * (unsigned)encoder_session.skip, SEEK_CUR) < 0) {
-                                       /* can't seek input, read ahead manually... */
-                                       unsigned left, need;
-                                       for(left = (unsigned)encoder_session.skip; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
-                                               need = min(left, CHUNK_OF_SAMPLES);
-                                               if(fread(ucbuffer_, bytes_per_wide_sample, need, infile) < need) {
-                                                       flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
-                                                       return EncoderSession_finish_error(&encoder_session);
-                                               }
-                                               left -= need;
-                                       }
+                               if(!fskip_ahead(infile, encoder_session.skip * bytes_per_wide_sample)) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
+                                       return EncoderSession_finish_error(&encoder_session);
                                }
                        }
 
@@ -745,7 +927,7 @@ int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, cons
                        /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
                        encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample + 44;
 
-                       if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
+                       if(!EncoderSession_init_encoder(&encoder_session, options.common, channel_mask, channels, bps-shift, sample_rate, /*flac_decoder_data=*/0))
                                return EncoderSession_finish_error(&encoder_session);
 
                        /*
@@ -793,7 +975,8 @@ int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, cons
                                        }
                                        else {
                                                unsigned wide_samples = bytes_read / bytes_per_wide_sample;
-                                               format_input(input_, wide_samples, false, is_unsigned_samples, channels, bps);
+                                               if(!format_input(input_, wide_samples, /*is_big_endian=*/false, is_unsigned_samples, channels, bps, shift, channel_map))
+                                                       return EncoderSession_finish_error(&encoder_session);
 
                                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
                                                        print_error_with_state(&encoder_session, "ERROR during encoding");
@@ -805,17 +988,10 @@ int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, cons
                        }
 
                        if(trim > 0) {
-                               if(fseek(infile, bytes_per_wide_sample * (unsigned)trim, SEEK_CUR) < 0) {
-                                       /* can't seek input, read ahead manually... */
-                                       unsigned left, need;
-                                       for(left = (unsigned)trim; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
-                                               need = min(left, CHUNK_OF_SAMPLES);
-                                               if(fread(ucbuffer_, bytes_per_wide_sample, need, infile) < need) {
-                                                       flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
-                                                       return EncoderSession_finish_error(&encoder_session);
-                                               }
-                                               left -= need;
-                                       }
+                               FLAC__ASSERT(!options.common.sector_align);
+                               if(!fskip_ahead(infile, trim * bytes_per_wide_sample)) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
+                                       return EncoderSession_finish_error(&encoder_session);
                                }
                        }
 
@@ -829,9 +1005,8 @@ int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, cons
                                                unsigned channel;
 
                                                info_align_zero = wide_samples;
-                                               data_bytes = wide_samples * (bps >> 3);
                                                for(channel = 0; channel < channels; channel++)
-                                                       memset(input_[channel], 0, data_bytes);
+                                                       memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
 
                                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
                                                        print_error_with_state(&encoder_session, "ERROR during encoding");
@@ -849,11 +1024,11 @@ int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, cons
                                                }
                                                else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
                                                        flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
-                                                       data_bytes = 0;
                                                }
                                                else {
                                                        info_align_carry = *options.common.align_reservoir_samples;
-                                                       format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, is_unsigned_samples, channels, bps);
+                                                       if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, /*is_big_endian=*/false, is_unsigned_samples, channels, bps, shift, channel_map))
+                                                               return EncoderSession_finish_error(&encoder_session);
                                                }
                                        }
                                }
@@ -896,18 +1071,9 @@ int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, cons
                                unsigned long skip = xx+(xx & 1U);
 
                                FLAC__ASSERT(skip<=LONG_MAX);
-                               if(fseek(infile, skip, SEEK_CUR) < 0) {
-                                       /* can't seek input, read ahead manually... */
-                                       unsigned left, need;
-                                       const unsigned chunk = sizeof(ucbuffer_);
-                                       for(left = skip; left > 0; ) {
-                                               need = min(left, chunk);
-                                               if(fread(ucbuffer_, 1, need, infile) < need) {
-                                                       flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_session.inbasefilename);
-                                                       return EncoderSession_finish_error(&encoder_session);
-                                               }
-                                               left -= need;
-                                       }
+                               if(!fskip_ahead(infile, skip)) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_session.inbasefilename);
+                                       return EncoderSession_finish_error(&encoder_session);
                                }
                        }
                }
@@ -916,14 +1082,14 @@ int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, cons
        return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
 }
 
-int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, raw_encode_options_t options)
+int flac__encode_raw(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, raw_encode_options_t options)
 {
        EncoderSession encoder_session;
        size_t bytes_read;
        const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
        unsigned align_remainder = 0;
        int info_align_carry = -1, info_align_zero = -1;
-       FLAC__uint64 total_samples_in_input = 0;;
+       FLAC__uint64 total_samples_in_input = 0;
 
        FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
        FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
@@ -962,7 +1128,7 @@ int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, cons
        else {
                /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
                FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
-               total_samples_in_input = (unsigned)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
+               total_samples_in_input = (FLAC__uint64)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
        }
 
        /*
@@ -974,11 +1140,13 @@ int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, cons
        encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
        FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
 
+       infilesize -= (off_t)encoder_session.skip * bytes_per_wide_sample;
        encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
        if(encoder_session.until > 0) {
                const FLAC__uint64 trim = total_samples_in_input - encoder_session.until;
                FLAC__ASSERT(total_samples_in_input > 0);
                FLAC__ASSERT(!options.common.sector_align);
+               infilesize -= (off_t)trim * bytes_per_wide_sample;
                encoder_session.total_samples_to_encode -= trim;
        }
        if(infilesize >= 0 && options.common.sector_align) {
@@ -999,18 +1167,9 @@ int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, cons
                if(skip_bytes > lookahead_length) {
                        skip_bytes -= lookahead_length;
                        lookahead_length = 0;
-                       if(fseek(infile, (long)skip_bytes, SEEK_CUR) < 0) {
-                               /* can't seek input, read ahead manually... */
-                               unsigned left, need;
-                               const unsigned chunk = sizeof(ucbuffer_);
-                               for(left = skip_bytes; left > 0; ) {
-                                       need = min(left, chunk);
-                                       if(fread(ucbuffer_, 1, need, infile) < need) {
-                                               flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
-                                               return EncoderSession_finish_error(&encoder_session);
-                                       }
-                                       left -= need;
-                               }
+                       if(!fskip_ahead(infile, skip_bytes)) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
+                               return EncoderSession_finish_error(&encoder_session);
                        }
                }
                else {
@@ -1019,7 +1178,7 @@ int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, cons
                }
        }
 
-       if(!EncoderSession_init_encoder(&encoder_session, options.common, options.channels, options.bps, options.sample_rate))
+       if(!EncoderSession_init_encoder(&encoder_session, options.common, /*channel_mask=*/0, options.channels, options.bps, options.sample_rate, /*flac_decoder_data=*/0))
                return EncoderSession_finish_error(&encoder_session);
 
        /*
@@ -1042,7 +1201,7 @@ int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, cons
                }
                else {
                        *options.common.align_reservoir_samples = align_remainder;
-                       infilesize -= (long)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
+                       infilesize -= (off_t)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
                        FLAC__ASSERT(infilesize >= 0);
                }
        }
@@ -1077,7 +1236,8 @@ int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, cons
                        }
                        else {
                                unsigned wide_samples = bytes_read / bytes_per_wide_sample;
-                               format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
+                               if(!format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0, /*channel_map=*/0))
+                                       return EncoderSession_finish_error(&encoder_session);
 
                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
                                        print_error_with_state(&encoder_session, "ERROR during encoding");
@@ -1087,12 +1247,12 @@ int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, cons
                }
        }
        else {
-               const FLAC__uint64 max_input_bytes = encoder_session.total_samples_to_encode * bytes_per_wide_sample;
+               const FLAC__uint64 max_input_bytes = infilesize;
                FLAC__uint64 total_input_bytes_read = 0;
                while(total_input_bytes_read < max_input_bytes) {
                        {
                                size_t wanted = (CHUNK_OF_SAMPLES * bytes_per_wide_sample);
-                               wanted = min(wanted, (size_t)(max_input_bytes - total_input_bytes_read));
+                               wanted = (size_t) min((FLAC__uint64)wanted, max_input_bytes - total_input_bytes_read);
 
                                if(lookahead_length > 0) {
                                        FLAC__ASSERT(lookahead_length <= wanted);
@@ -1129,7 +1289,8 @@ int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, cons
                                }
                                else {
                                        unsigned wide_samples = bytes_read / bytes_per_wide_sample;
-                                       format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
+                                       if(!format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0, /*channel_map=*/0))
+                                               return EncoderSession_finish_error(&encoder_session);
 
                                        if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
                                                print_error_with_state(&encoder_session, "ERROR during encoding");
@@ -1148,12 +1309,11 @@ int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, cons
                if(options.common.is_last_file) {
                        unsigned wide_samples = 588 - align_remainder;
                        if(wide_samples < 588) {
-                               unsigned channel, data_bytes;
+                               unsigned channel;
 
                                info_align_zero = wide_samples;
-                               data_bytes = wide_samples * (options.bps >> 3);
                                for(channel = 0; channel < options.channels; channel++)
-                                       memset(input_[channel], 0, data_bytes);
+                                       memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
 
                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
                                        print_error_with_state(&encoder_session, "ERROR during encoding");
@@ -1174,7 +1334,8 @@ int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, cons
                                }
                                else {
                                        info_align_carry = *options.common.align_reservoir_samples;
-                                       format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, options.is_unsigned_samples, options.channels, options.bps);
+                                       if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0, /*channel_map=*/0))
+                                               return EncoderSession_finish_error(&encoder_session);
                                }
                        }
                }
@@ -1183,6 +1344,161 @@ int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, cons
        return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
 }
 
+int flac__encode_flac(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, flac_encode_options_t options, FLAC__bool input_is_ogg)
+{
+       EncoderSession encoder_session;
+       FLAC__StreamDecoder *decoder = 0;
+       FLACDecoderData decoder_data;
+       size_t i;
+       int retval;
+
+       if(!
+               EncoderSession_construct(
+                       &encoder_session,
+#ifdef FLAC__HAS_OGG
+                       options.common.use_ogg,
+#else
+                       /*use_ogg=*/false,
+#endif
+                       options.common.verify,
+                       infile,
+                       infilename,
+                       outfilename
+               )
+       )
+               return 1;
+
+       decoder_data.encoder_session = &encoder_session;
+       decoder_data.filesize = (infilesize == (off_t)(-1)? 0 : infilesize);
+       decoder_data.lookahead = lookahead;
+       decoder_data.lookahead_length = lookahead_length;
+       decoder_data.num_metadata_blocks = 0;
+       decoder_data.samples_left_to_process = 0;
+       decoder_data.fatal_error = false;
+
+       /*
+        * set up FLAC decoder for the input
+        */
+       if (0 == (decoder = FLAC__stream_decoder_new())) {
+               flac__utils_printf(stderr, 1, "%s: ERROR: creating decoder for FLAC input\n", encoder_session.inbasefilename);
+               return EncoderSession_finish_error(&encoder_session);
+       }
+       if (!(
+               FLAC__stream_decoder_set_md5_checking(decoder, false) &&
+               FLAC__stream_decoder_set_metadata_respond_all(decoder)
+       )) {
+               flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", encoder_session.inbasefilename);
+               goto fubar1; /*@@@ yuck */
+       }
+
+       if (input_is_ogg) {
+               if (FLAC__stream_decoder_init_ogg_stream(decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/&decoder_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
+                       flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for Ogg FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
+                       goto fubar1; /*@@@ yuck */
+               }
+       }
+       else if (FLAC__stream_decoder_init_stream(decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/&decoder_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
+               flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
+               goto fubar1; /*@@@ yuck */
+       }
+
+       if (!FLAC__stream_decoder_process_until_end_of_metadata(decoder) || decoder_data.fatal_error) {
+               if (decoder_data.fatal_error)
+                       flac__utils_printf(stderr, 1, "%s: ERROR: out of memory or too many metadata blocks while reading metadata in FLAC input\n", encoder_session.inbasefilename);
+               else
+                       flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
+               goto fubar1; /*@@@ yuck */
+       }
+
+       if (decoder_data.num_metadata_blocks == 0) {
+               flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, got no metadata blocks\n", encoder_session.inbasefilename);
+               goto fubar2; /*@@@ yuck */
+       }
+       else if (decoder_data.metadata_blocks[0]->type != FLAC__METADATA_TYPE_STREAMINFO) {
+               flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, first metadata block is not STREAMINFO\n", encoder_session.inbasefilename);
+               goto fubar2; /*@@@ yuck */
+       }
+       else if (decoder_data.metadata_blocks[0]->data.stream_info.total_samples == 0) {
+               flac__utils_printf(stderr, 1, "%s: ERROR: FLAC input has STREAMINFO with unknown total samples which is not supported\n", encoder_session.inbasefilename);
+               goto fubar2; /*@@@ yuck */
+       }
+
+       /*
+        * now that we have the STREAMINFO and know the sample rate,
+        * canonicalize the --skip string to a number of samples:
+        */
+       flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate);
+       FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
+       encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
+       FLAC__ASSERT(!options.common.sector_align); /* --sector-align with FLAC input is not supported */
+
+       {
+               FLAC__uint64 total_samples_in_input, trim = 0;
+
+               total_samples_in_input = decoder_data.metadata_blocks[0]->data.stream_info.total_samples;
+
+               /*
+                * now that we know the input size, canonicalize the
+                * --until string to an absolute sample number:
+                */
+               if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate, encoder_session.skip, total_samples_in_input))
+                       goto fubar2; /*@@@ yuck */
+               encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
+
+               encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
+               if(encoder_session.until > 0) {
+                       trim = total_samples_in_input - encoder_session.until;
+                       FLAC__ASSERT(total_samples_in_input > 0);
+                       encoder_session.total_samples_to_encode -= trim;
+               }
+
+               encoder_session.unencoded_size = decoder_data.filesize;
+
+               /* (channel mask will get copied over from the source VORBIS_COMMENT if it exists) */
+               if(!EncoderSession_init_encoder(&encoder_session, options.common, /*channel_mask=*/0, decoder_data.metadata_blocks[0]->data.stream_info.channels, decoder_data.metadata_blocks[0]->data.stream_info.bits_per_sample, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate, &decoder_data))
+                       return EncoderSession_finish_error(&encoder_session);
+
+               /*
+                * have to wait until the FLAC encoder is set up for writing
+                * before any seeking in the input FLAC file, because the seek
+                * itself will usually call the decoder's write callback, and
+                * our decoder's write callback passes samples to our FLAC
+                * encoder
+                */
+               decoder_data.samples_left_to_process = encoder_session.total_samples_to_encode;
+               if(encoder_session.skip > 0) {
+                       if(!FLAC__stream_decoder_seek_absolute(decoder, encoder_session.skip)) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR while skipping samples, FLAC decoder state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
+                               goto fubar2; /*@@@ yuck */
+                       }
+               }
+
+               /*
+                * now do samples from the file
+                */
+               while(!decoder_data.fatal_error && decoder_data.samples_left_to_process > 0) {
+                       if(!FLAC__stream_decoder_process_single(decoder)) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
+                               goto fubar2; /*@@@ yuck */
+                       }
+               }
+       }
+
+       FLAC__stream_decoder_delete(decoder);
+       retval = EncoderSession_finish_ok(&encoder_session, -1, -1);
+       /* have to wail until encoder is completely finished before deleting because of the final step of writing the seekpoint offsets */
+       for(i = 0; i < decoder_data.num_metadata_blocks; i++)
+               free(decoder_data.metadata_blocks[i]);
+       return retval;
+
+fubar2:
+       for(i = 0; i < decoder_data.num_metadata_blocks; i++)
+               free(decoder_data.metadata_blocks[i]);
+fubar1:
+       FLAC__stream_decoder_delete(decoder);
+       return EncoderSession_finish_error(&encoder_session);
+}
+
 FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FILE *infile, const char *infilename, const char *outfilename)
 {
        unsigned i;
@@ -1210,6 +1526,7 @@ FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC_
        e->verify = verify;
 
        e->is_stdout = (0 == strcmp(outfilename, "-"));
+       e->outputfile_opened = false;
 
        e->inbasefilename = grabbag__file_get_basename(infilename);
        e->outfilename = outfilename;
@@ -1219,65 +1536,23 @@ FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC_
        e->total_samples_to_encode = 0;
        e->bytes_written = 0;
        e->samples_written = 0;
-       e->blocksize = 0;
        e->stats_mask = 0;
 
-       e->encoder.flac.stream = 0;
-       e->encoder.flac.file = 0;
-#ifdef FLAC__HAS_OGG
-       e->encoder.ogg.stream = 0;
-       e->encoder.ogg.file = 0;
-#endif
+       e->encoder = 0;
 
        e->fin = infile;
-       e->fout = 0;
        e->seek_table_template = 0;
 
-       if(e->is_stdout) {
-               e->fout = grabbag__file_get_binary_stdout();
-       }
-
        if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
                flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
                return false;
        }
 
-#ifdef FLAC__HAS_OGG
-       if(e->use_ogg) {
-               if(e->is_stdout) {
-                       e->encoder.ogg.stream = OggFLAC__stream_encoder_new();
-                       if(0 == e->encoder.ogg.stream) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
-                               EncoderSession_destroy(e);
-                               return false;
-                       }
-               }
-               else {
-                       e->encoder.ogg.file = OggFLAC__file_encoder_new();
-                       if(0 == e->encoder.ogg.file) {
-                               flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
-                               EncoderSession_destroy(e);
-                               return false;
-                       }
-               }
-       }
-       else
-#endif
-       if(e->is_stdout) {
-               e->encoder.flac.stream = FLAC__stream_encoder_new();
-               if(0 == e->encoder.flac.stream) {
-                       flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
-                       EncoderSession_destroy(e);
-                       return false;
-               }
-       }
-       else {
-               e->encoder.flac.file = FLAC__file_encoder_new();
-               if(0 == e->encoder.flac.file) {
-                       flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
-                       EncoderSession_destroy(e);
-                       return false;
-               }
+       e->encoder = FLAC__stream_encoder_new();
+       if(0 == e->encoder) {
+               flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
+               EncoderSession_destroy(e);
+               return false;
        }
 
        return true;
@@ -1287,37 +1562,10 @@ void EncoderSession_destroy(EncoderSession *e)
 {
        if(e->fin != stdin)
                fclose(e->fin);
-       if(0 != e->fout && e->fout != stdout)
-               fclose(e->fout);
 
-#ifdef FLAC__HAS_OGG
-       if(e->use_ogg) {
-               if(e->is_stdout) {
-                       if(0 != e->encoder.ogg.stream) {
-                               OggFLAC__stream_encoder_delete(e->encoder.ogg.stream);
-                               e->encoder.ogg.stream = 0;
-                       }
-               }
-               else {
-                       if(0 != e->encoder.ogg.file) {
-                               OggFLAC__file_encoder_delete(e->encoder.ogg.file);
-                               e->encoder.ogg.file = 0;
-                       }
-               }
-       }
-       else
-#endif
-       if(e->is_stdout) {
-               if(0 != e->encoder.flac.stream) {
-                       FLAC__stream_encoder_delete(e->encoder.flac.stream);
-                       e->encoder.flac.stream = 0;
-               }
-       }
-       else {
-               if(0 != e->encoder.flac.file) {
-                       FLAC__file_encoder_delete(e->encoder.flac.file);
-                       e->encoder.flac.file = 0;
-               }
+       if(0 != e->encoder) {
+               FLAC__stream_encoder_delete(e->encoder);
+               e->encoder = 0;
        }
 
        if(0 != e->seek_table_template) {
@@ -1331,34 +1579,9 @@ int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_a
        FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
        int ret = 0;
 
-#ifdef FLAC__HAS_OGG
-       if(e->use_ogg) {
-               if(e->is_stdout) {
-                       if(e->encoder.ogg.stream) {
-                               fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
-                               OggFLAC__stream_encoder_finish(e->encoder.ogg.stream);
-                       }
-               }
-               else {
-                       if(e->encoder.ogg.file) {
-                               fse_state = OggFLAC__file_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.file);
-                               OggFLAC__file_encoder_finish(e->encoder.ogg.file);
-                       }
-               }
-       }
-       else
-#endif
-       if(e->is_stdout) {
-               if(e->encoder.flac.stream) {
-                       fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
-                       FLAC__stream_encoder_finish(e->encoder.flac.stream);
-               }
-       }
-       else {
-               if(e->encoder.flac.file) {
-                       fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
-                       FLAC__file_encoder_finish(e->encoder.flac.file);
-               }
+       if(e->encoder) {
+               fse_state = FLAC__stream_encoder_get_state(e->encoder);
+               FLAC__stream_encoder_finish(e->encoder);
        }
 
        if(e->total_samples_to_encode > 0) {
@@ -1386,32 +1609,15 @@ int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_a
 
 int EncoderSession_finish_error(EncoderSession *e)
 {
-       FLAC__StreamEncoderState fse_state;
+       FLAC__ASSERT(e->encoder);
 
        if(e->total_samples_to_encode > 0)
                flac__utils_printf(stderr, 2, "\n");
 
-#ifdef FLAC__HAS_OGG
-       if(e->use_ogg) {
-               if(e->is_stdout) {
-                       fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
-               }
-               else {
-                       fse_state = OggFLAC__file_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.file);
-               }
-       }
-       else
-#endif
-       if(e->is_stdout) {
-               fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
-       }
-       else {
-               fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
-       }
-
-       if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
+       if(FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
                print_verify_error(e);
-       else
+       else if(e->outputfile_opened)
+               /* only want to delete the file if we opened it; otherwise it could be an existing file and our overwrite failed */
                unlink(e->outfilename);
 
        EncoderSession_destroy(e);
@@ -1419,18 +1625,25 @@ int EncoderSession_finish_error(EncoderSession *e)
        return 1;
 }
 
-FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate)
+FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, FLAC__uint32 channel_mask, unsigned channels, unsigned bps, unsigned sample_rate, FLACDecoderData *flac_decoder_data)
 {
-       unsigned num_metadata;
+       unsigned num_metadata, i;
        FLAC__StreamMetadata padding, *cuesheet = 0;
-       FLAC__StreamMetadata *metadata[4];
+       FLAC__StreamMetadata *static_metadata[4+64]; /* MAGIC +64 is for pictures metadata in options.pictures */
+       FLAC__StreamMetadata **metadata = static_metadata;
+       FLAC__StreamEncoderInitStatus init_status;
        const FLAC__bool is_cdda = (channels == 1 || channels == 2) && (bps == 16) && (sample_rate == 44100);
+       char apodizations[2000];
+
+       FLAC__ASSERT(sizeof(options.pictures)/sizeof(options.pictures[0]) <= 64);
 
        e->replay_gain = options.replay_gain;
        e->channels = channels;
        e->bits_per_sample = bps;
        e->sample_rate = sample_rate;
 
+       apodizations[0] = '\0';
+
        if(e->replay_gain) {
                if(channels != 1 && channels != 2) {
                        flac__utils_printf(stderr, 1, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
@@ -1448,10 +1661,7 @@ FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t optio
                }
        }
 
-       if(channels != 2)
-               options.do_mid_side = options.loose_mid_side = false;
-
-       if(!parse_cuesheet_(&cuesheet, options.cuesheet_filename, e->inbasefilename, is_cdda, e->total_samples_to_encode))
+       if(!parse_cuesheet(&cuesheet, options.cuesheet_filename, e->inbasefilename, is_cdda, e->total_samples_to_encode))
                return false;
 
        if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? cuesheet : 0, e)) {
@@ -1461,167 +1671,321 @@ FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t optio
                return false;
        }
 
-       num_metadata = 0;
-       if(e->seek_table_template->data.seek_table.num_points > 0) {
-               e->seek_table_template->is_last = false; /* the encoder will set this for us */
-               metadata[num_metadata++] = e->seek_table_template;
-       }
-       if(0 != cuesheet)
-               metadata[num_metadata++] = cuesheet;
-       metadata[num_metadata++] = options.vorbis_comment;
-       if(options.padding > 0) {
-               padding.is_last = false; /* the encoder will set this for us */
-               padding.type = FLAC__METADATA_TYPE_PADDING;
-               padding.length = (unsigned)options.padding;
-               metadata[num_metadata++] = &padding;
-       }
-
-       e->blocksize = options.blocksize;
-       e->stats_mask = (options.do_exhaustive_model_search || options.do_qlp_coeff_prec_search)? 0x0f : 0x3f;
-
-#ifdef FLAC__HAS_OGG
-       if(e->use_ogg) {
-               if(e->is_stdout) {
-                       OggFLAC__stream_encoder_set_serial_number(e->encoder.ogg.stream, options.serial_number);
-                       OggFLAC__stream_encoder_set_verify(e->encoder.ogg.stream, options.verify);
-                       OggFLAC__stream_encoder_set_streamable_subset(e->encoder.ogg.stream, !options.lax);
-                       OggFLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.ogg.stream, options.do_mid_side);
-                       OggFLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.ogg.stream, options.loose_mid_side);
-                       OggFLAC__stream_encoder_set_channels(e->encoder.ogg.stream, channels);
-                       OggFLAC__stream_encoder_set_bits_per_sample(e->encoder.ogg.stream, bps);
-                       OggFLAC__stream_encoder_set_sample_rate(e->encoder.ogg.stream, sample_rate);
-                       OggFLAC__stream_encoder_set_blocksize(e->encoder.ogg.stream, options.blocksize);
-                       OggFLAC__stream_encoder_set_max_lpc_order(e->encoder.ogg.stream, options.max_lpc_order);
-                       OggFLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.ogg.stream, options.qlp_coeff_precision);
-                       OggFLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg.stream, options.do_qlp_coeff_prec_search);
-                       OggFLAC__stream_encoder_set_do_escape_coding(e->encoder.ogg.stream, options.do_escape_coding);
-                       OggFLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.ogg.stream, options.do_exhaustive_model_search);
-                       OggFLAC__stream_encoder_set_min_residual_partition_order(e->encoder.ogg.stream, options.min_residual_partition_order);
-                       OggFLAC__stream_encoder_set_max_residual_partition_order(e->encoder.ogg.stream, options.max_residual_partition_order);
-                       OggFLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.ogg.stream, options.rice_parameter_search_dist);
-                       OggFLAC__stream_encoder_set_total_samples_estimate(e->encoder.ogg.stream, e->total_samples_to_encode);
-                       OggFLAC__stream_encoder_set_metadata(e->encoder.ogg.stream, (num_metadata > 0)? metadata : 0, num_metadata);
-                       OggFLAC__stream_encoder_set_write_callback(e->encoder.ogg.stream, ogg_stream_encoder_write_callback);
-                       OggFLAC__stream_encoder_set_metadata_callback(e->encoder.ogg.stream, ogg_stream_encoder_metadata_callback);
-                       OggFLAC__stream_encoder_set_client_data(e->encoder.ogg.stream, e);
-
-                       OggFLAC__stream_encoder_disable_constant_subframes(e->encoder.ogg.stream, options.debug.disable_constant_subframes);
-                       OggFLAC__stream_encoder_disable_fixed_subframes(e->encoder.ogg.stream, options.debug.disable_fixed_subframes);
-                       OggFLAC__stream_encoder_disable_verbatim_subframes(e->encoder.ogg.stream, options.debug.disable_verbatim_subframes);
-
-                       if(OggFLAC__stream_encoder_init(e->encoder.ogg.stream) != FLAC__STREAM_ENCODER_OK) {
-                               print_error_with_state(e, "ERROR initializing encoder");
-                               if(0 != cuesheet)
-                                       FLAC__metadata_object_delete(cuesheet);
-                               return false;
+       if(flac_decoder_data) {
+               /*
+                * we're encoding from FLAC so we will use the FLAC file's
+                * metadata as the basic for the encoded file
+                */
+               {
+                       /*
+                        * first handle padding: if --no-padding was specified,
+                        * then delete all padding; else if -P was specified,
+                        * use that instead of existing padding (if any); else
+                        * if existing file has padding, move all existing
+                        * padding blocks to one padding block at the end; else
+                        * use default padding.
+                        */
+                       int p = -1;
+                       size_t i, j;
+                       for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
+                               if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_PADDING) {
+                                       if(p < 0)
+                                               p = 0;
+                                       p += flac_decoder_data->metadata_blocks[i]->length;
+                                       FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
+                                       flac_decoder_data->metadata_blocks[i] = 0;
+                               }
+                               else
+                                       flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
+                       }
+                       flac_decoder_data->num_metadata_blocks = j;
+                       if(options.padding > 0)
+                               p = options.padding;
+                       if(p < 0)
+                               p = e->total_samples_to_encode / e->sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8;
+                       if(options.padding != 0) {
+                               if(p > 0 && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
+                                       flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
+                                       if(0 == flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]) {
+                                               flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PADDING block\n", e->inbasefilename);
+                                               if(0 != cuesheet)
+                                                       FLAC__metadata_object_delete(cuesheet);
+                                               return false;
+                                       }
+                                       flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->is_last = false; /* the encoder will set this for us */
+                                       flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->length = p;
+                                       flac_decoder_data->num_metadata_blocks++;
+                               }
                        }
                }
-               else {
-                       OggFLAC__file_encoder_set_serial_number(e->encoder.ogg.file, options.serial_number);
-                       OggFLAC__file_encoder_set_filename(e->encoder.ogg.file, e->outfilename);
-                       OggFLAC__file_encoder_set_verify(e->encoder.ogg.file, options.verify);
-                       OggFLAC__file_encoder_set_streamable_subset(e->encoder.ogg.file, !options.lax);
-                       OggFLAC__file_encoder_set_do_mid_side_stereo(e->encoder.ogg.file, options.do_mid_side);
-                       OggFLAC__file_encoder_set_loose_mid_side_stereo(e->encoder.ogg.file, options.loose_mid_side);
-                       OggFLAC__file_encoder_set_channels(e->encoder.ogg.file, channels);
-                       OggFLAC__file_encoder_set_bits_per_sample(e->encoder.ogg.file, bps);
-                       OggFLAC__file_encoder_set_sample_rate(e->encoder.ogg.file, sample_rate);
-                       OggFLAC__file_encoder_set_blocksize(e->encoder.ogg.file, options.blocksize);
-                       OggFLAC__file_encoder_set_max_lpc_order(e->encoder.ogg.file, options.max_lpc_order);
-                       OggFLAC__file_encoder_set_qlp_coeff_precision(e->encoder.ogg.file, options.qlp_coeff_precision);
-                       OggFLAC__file_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg.file, options.do_qlp_coeff_prec_search);
-                       OggFLAC__file_encoder_set_do_escape_coding(e->encoder.ogg.file, options.do_escape_coding);
-                       OggFLAC__file_encoder_set_do_exhaustive_model_search(e->encoder.ogg.file, options.do_exhaustive_model_search);
-                       OggFLAC__file_encoder_set_min_residual_partition_order(e->encoder.ogg.file, options.min_residual_partition_order);
-                       OggFLAC__file_encoder_set_max_residual_partition_order(e->encoder.ogg.file, options.max_residual_partition_order);
-                       OggFLAC__file_encoder_set_rice_parameter_search_dist(e->encoder.ogg.file, options.rice_parameter_search_dist);
-                       OggFLAC__file_encoder_set_total_samples_estimate(e->encoder.ogg.file, e->total_samples_to_encode);
-                       OggFLAC__file_encoder_set_metadata(e->encoder.ogg.file, (num_metadata > 0)? metadata : 0, num_metadata);
-                       OggFLAC__file_encoder_set_progress_callback(e->encoder.ogg.file, ogg_file_encoder_progress_callback);
-                       OggFLAC__file_encoder_set_client_data(e->encoder.ogg.file, e);
-
-                       OggFLAC__file_encoder_disable_constant_subframes(e->encoder.ogg.file, options.debug.disable_constant_subframes);
-                       OggFLAC__file_encoder_disable_fixed_subframes(e->encoder.ogg.file, options.debug.disable_fixed_subframes);
-                       OggFLAC__file_encoder_disable_verbatim_subframes(e->encoder.ogg.file, options.debug.disable_verbatim_subframes);
-
-                       if(OggFLAC__file_encoder_init(e->encoder.ogg.file) != OggFLAC__FILE_ENCODER_OK) {
-                               print_error_with_state(e, "ERROR initializing encoder");
+               {
+                       /*
+                        * next handle vorbis comment: if any tags were specified
+                        * or there is no existing vorbis comment, we create a
+                        * new vorbis comment (discarding any existing one); else
+                        * we keep the existing one.  also need to make sure to
+                        * propagate any channel mask tag.
+                        */
+                       size_t i, j;
+                       FLAC__bool vc_found = false;
+                       for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
+                               if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
+                                       vc_found = true;
+                               if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT && options.vorbis_comment->data.vorbis_comment.num_comments > 0) {
+                                       (void) flac__utils_get_channel_mask_tag(flac_decoder_data->metadata_blocks[i], &channel_mask);
+                                       flac__utils_printf(stderr, 1, "%s: WARNING, replacing tags from input FLAC file with those given on the command-line\n", e->inbasefilename);
+                                       FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
+                                       flac_decoder_data->metadata_blocks[i] = 0;
+                               }
+                               else
+                                       flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
+                       }
+                       flac_decoder_data->num_metadata_blocks = j;
+                       if((!vc_found || options.vorbis_comment->data.vorbis_comment.num_comments > 0) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
+                               /* prepend ours */
+                               FLAC__StreamMetadata *vc = FLAC__metadata_object_clone(options.vorbis_comment);
+                               if(0 == vc || (channel_mask && !flac__utils_set_channel_mask_tag(vc, channel_mask))) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for VORBIS_COMMENT block\n", e->inbasefilename);
+                                       if(0 != cuesheet)
+                                               FLAC__metadata_object_delete(cuesheet);
+                                       return false;
+                               }
+                               for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
+                                       flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
+                               flac_decoder_data->metadata_blocks[1] = vc;
+                               flac_decoder_data->num_metadata_blocks++;
+                       }
+               }
+               {
+                       /*
+                        * next handle cuesheet: if --cuesheet was specified, use
+                        * it; else if file has existing CUESHEET and cuesheet's
+                        * lead-out offset is correct, keep it; else no CUESHEET
+                        */
+                       size_t i, j;
+                       for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
+                               FLAC__bool existing_cuesheet_is_bad = false;
+                               /* check if existing cuesheet matches the input audio */
+                               if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && 0 == cuesheet) {
+                                       const FLAC__StreamMetadata_CueSheet *cs = &flac_decoder_data->metadata_blocks[i]->data.cue_sheet;
+                                       if(e->total_samples_to_encode == 0) {
+                                               flac__utils_printf(stderr, 1, "%s: WARNING, cuesheet in input FLAC file cannot be kept if input size is not known, dropping it...\n", e->inbasefilename);
+                                               existing_cuesheet_is_bad = true;
+                                       }
+                                       else if(e->total_samples_to_encode != cs->tracks[cs->num_tracks-1].offset) {
+                                               flac__utils_printf(stderr, 1, "%s: WARNING, lead-out offset of cuesheet in input FLAC file does not match input length, dropping existing cuesheet...\n", e->inbasefilename);
+                                               existing_cuesheet_is_bad = true;
+                                       }
+                               }
+                               if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && (existing_cuesheet_is_bad || 0 != cuesheet)) {
+                                       if(0 != cuesheet)
+                                               flac__utils_printf(stderr, 1, "%s: WARNING, replacing cuesheet in input FLAC file with the one given on the command-line\n", e->inbasefilename);
+                                       FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
+                                       flac_decoder_data->metadata_blocks[i] = 0;
+                               }
+                               else
+                                       flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
+                       }
+                       flac_decoder_data->num_metadata_blocks = j;
+                       if(0 != cuesheet && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
+                               /* prepend ours */
+                               FLAC__StreamMetadata *cs = FLAC__metadata_object_clone(cuesheet);
+                               if(0 == cs) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for CUESHEET block\n", e->inbasefilename);
+                                       if(0 != cuesheet)
+                                               FLAC__metadata_object_delete(cuesheet);
+                                       return false;
+                               }
+                               for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
+                                       flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
+                               flac_decoder_data->metadata_blocks[1] = cs;
+                               flac_decoder_data->num_metadata_blocks++;
+                       }
+               }
+               {
+                       /*
+                        * finally handle seektable: if -S- was specified, no
+                        * SEEKTABLE; else if -S was specified, use it/them;
+                        * else if file has existing SEEKTABLE and input size is
+                        * preserved (no --skip/--until/etc specified), keep it;
+                        * else use default seektable options
+                        *
+                        * note: meanings of num_requested_seek_points:
+                        *  -1 : no -S option given, default to some value
+                        *   0 : -S- given (no seektable)
+                        *  >0 : one or more -S options given
+                        */
+                       size_t i, j;
+                       FLAC__bool existing_seektable = false;
+                       for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
+                               if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE)
+                                       existing_seektable = true;
+                               if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE && (e->total_samples_to_encode != flac_decoder_data->metadata_blocks[0]->data.stream_info.total_samples || options.num_requested_seek_points >= 0)) {
+                                       if(options.num_requested_seek_points > 0)
+                                               flac__utils_printf(stderr, 1, "%s: WARNING, replacing seektable in input FLAC file with the one given on the command-line\n", e->inbasefilename);
+                                       else if(options.num_requested_seek_points == 0)
+                                               ; /* no warning, silently delete existing SEEKTABLE since user specified --no-seektable (-S-) */
+                                       else
+                                               flac__utils_printf(stderr, 1, "%s: WARNING, can't use existing seektable in input FLAC since the input size is changing or unknown, dropping existing SEEKTABLE block...\n", e->inbasefilename);
+                                       FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
+                                       flac_decoder_data->metadata_blocks[i] = 0;
+                                       existing_seektable = false;
+                               }
+                               else
+                                       flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
+                       }
+                       flac_decoder_data->num_metadata_blocks = j;
+                       if((options.num_requested_seek_points > 0 || (options.num_requested_seek_points < 0 && !existing_seektable)) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
+                               /* prepend ours */
+                               FLAC__StreamMetadata *st = FLAC__metadata_object_clone(e->seek_table_template);
+                               if(0 == st) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for SEEKTABLE block\n", e->inbasefilename);
+                                       if(0 != cuesheet)
+                                               FLAC__metadata_object_delete(cuesheet);
+                                       return false;
+                               }
+                               for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
+                                       flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
+                               flac_decoder_data->metadata_blocks[1] = st;
+                               flac_decoder_data->num_metadata_blocks++;
+                       }
+               }
+               metadata = &flac_decoder_data->metadata_blocks[1]; /* don't include STREAMINFO */
+               num_metadata = flac_decoder_data->num_metadata_blocks - 1;
+       }
+       else {
+               /*
+                * we're not encoding from FLAC so we will build the metadata
+                * from scratch
+                */
+               num_metadata = 0;
+               if(e->seek_table_template->data.seek_table.num_points > 0) {
+                       e->seek_table_template->is_last = false; /* the encoder will set this for us */
+                       metadata[num_metadata++] = e->seek_table_template;
+               }
+               if(0 != cuesheet)
+                       metadata[num_metadata++] = cuesheet;
+               if(channel_mask) {
+                       if(!flac__utils_set_channel_mask_tag(options.vorbis_comment, channel_mask)) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR adding channel mask tag\n", e->inbasefilename);
                                if(0 != cuesheet)
                                        FLAC__metadata_object_delete(cuesheet);
                                return false;
                        }
                }
+               metadata[num_metadata++] = options.vorbis_comment;
+               for(i = 0; i < options.num_pictures; i++)
+                       metadata[num_metadata++] = options.pictures[i];
+               if(options.padding != 0) {
+                       padding.is_last = false; /* the encoder will set this for us */
+                       padding.type = FLAC__METADATA_TYPE_PADDING;
+                       padding.length = (unsigned)(options.padding>0? options.padding : (e->total_samples_to_encode / e->sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8));
+                       metadata[num_metadata++] = &padding;
+               }
+       }
+
+       /* check for a few things that have not already been checked.  the
+        * FLAC__stream_encoder_init*() will check it but only return
+        * FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA so we check some
+        * up front to give a better error message.
+        */
+       if(!verify_metadata(e, metadata, num_metadata)) {
+               if(0 != cuesheet)
+                       FLAC__metadata_object_delete(cuesheet);
+               return false;
+       }
+
+       FLAC__stream_encoder_set_verify(e->encoder, options.verify);
+       FLAC__stream_encoder_set_streamable_subset(e->encoder, !options.lax);
+       FLAC__stream_encoder_set_channels(e->encoder, channels);
+       FLAC__stream_encoder_set_bits_per_sample(e->encoder, bps);
+       FLAC__stream_encoder_set_sample_rate(e->encoder, sample_rate);
+       for(i = 0; i < options.num_compression_settings; i++) {
+               switch(options.compression_settings[i].type) {
+                       case CST_BLOCKSIZE:
+                               FLAC__stream_encoder_set_blocksize(e->encoder, options.compression_settings[i].value.t_unsigned);
+                               break;
+                       case CST_COMPRESSION_LEVEL:
+                               FLAC__stream_encoder_set_compression_level(e->encoder, options.compression_settings[i].value.t_unsigned);
+                               apodizations[0] = '\0';
+                               break;
+                       case CST_DO_MID_SIDE:
+                               FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder, options.compression_settings[i].value.t_bool);
+                               break;
+                       case CST_LOOSE_MID_SIDE:
+                               FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder, options.compression_settings[i].value.t_bool);
+                               break;
+                       case CST_APODIZATION:
+                               if(strlen(apodizations)+strlen(options.compression_settings[i].value.t_string)+2 >= sizeof(apodizations)) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR: too many apodization functions requested\n", e->inbasefilename);
+                                       if(0 != cuesheet)
+                                               FLAC__metadata_object_delete(cuesheet);
+                                       return false;
+                               }
+                               else {
+                                       strcat(apodizations, options.compression_settings[i].value.t_string);
+                                       strcat(apodizations, ";");
+                               }
+                               break;
+                       case CST_MAX_LPC_ORDER:
+                               FLAC__stream_encoder_set_max_lpc_order(e->encoder, options.compression_settings[i].value.t_unsigned);
+                               break;
+                       case CST_QLP_COEFF_PRECISION:
+                               FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder, options.compression_settings[i].value.t_unsigned);
+                               break;
+                       case CST_DO_QLP_COEFF_PREC_SEARCH:
+                               FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder, options.compression_settings[i].value.t_bool);
+                               break;
+                       case CST_DO_ESCAPE_CODING:
+                               FLAC__stream_encoder_set_do_escape_coding(e->encoder, options.compression_settings[i].value.t_bool);
+                               break;
+                       case CST_DO_EXHAUSTIVE_MODEL_SEARCH:
+                               FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder, options.compression_settings[i].value.t_bool);
+                               break;
+                       case CST_MIN_RESIDUAL_PARTITION_ORDER:
+                               FLAC__stream_encoder_set_min_residual_partition_order(e->encoder, options.compression_settings[i].value.t_unsigned);
+                               break;
+                       case CST_MAX_RESIDUAL_PARTITION_ORDER:
+                               FLAC__stream_encoder_set_max_residual_partition_order(e->encoder, options.compression_settings[i].value.t_unsigned);
+                               break;
+                       case CST_RICE_PARAMETER_SEARCH_DIST:
+                               FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder, options.compression_settings[i].value.t_unsigned);
+                               break;
+               }
+       }
+       if(*apodizations)
+               FLAC__stream_encoder_set_apodization(e->encoder, apodizations);
+       FLAC__stream_encoder_set_total_samples_estimate(e->encoder, e->total_samples_to_encode);
+       FLAC__stream_encoder_set_metadata(e->encoder, (num_metadata > 0)? metadata : 0, num_metadata);
+
+       FLAC__stream_encoder_disable_constant_subframes(e->encoder, options.debug.disable_constant_subframes);
+       FLAC__stream_encoder_disable_fixed_subframes(e->encoder, options.debug.disable_fixed_subframes);
+       FLAC__stream_encoder_disable_verbatim_subframes(e->encoder, options.debug.disable_verbatim_subframes);
+
+#ifdef FLAC__HAS_OGG
+       if(e->use_ogg) {
+               FLAC__stream_encoder_set_ogg_serial_number(e->encoder, options.serial_number);
+
+               init_status = FLAC__stream_encoder_init_ogg_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
        }
        else
 #endif
-       if(e->is_stdout) {
-               FLAC__stream_encoder_set_verify(e->encoder.flac.stream, options.verify);
-               FLAC__stream_encoder_set_streamable_subset(e->encoder.flac.stream, !options.lax);
-               FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.flac.stream, options.do_mid_side);
-               FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.flac.stream, options.loose_mid_side);
-               FLAC__stream_encoder_set_channels(e->encoder.flac.stream, channels);
-               FLAC__stream_encoder_set_bits_per_sample(e->encoder.flac.stream, bps);
-               FLAC__stream_encoder_set_sample_rate(e->encoder.flac.stream, sample_rate);
-               FLAC__stream_encoder_set_blocksize(e->encoder.flac.stream, options.blocksize);
-               FLAC__stream_encoder_set_max_lpc_order(e->encoder.flac.stream, options.max_lpc_order);
-               FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.flac.stream, options.qlp_coeff_precision);
-               FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.stream, options.do_qlp_coeff_prec_search);
-               FLAC__stream_encoder_set_do_escape_coding(e->encoder.flac.stream, options.do_escape_coding);
-               FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.flac.stream, options.do_exhaustive_model_search);
-               FLAC__stream_encoder_set_min_residual_partition_order(e->encoder.flac.stream, options.min_residual_partition_order);
-               FLAC__stream_encoder_set_max_residual_partition_order(e->encoder.flac.stream, options.max_residual_partition_order);
-               FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.flac.stream, options.rice_parameter_search_dist);
-               FLAC__stream_encoder_set_total_samples_estimate(e->encoder.flac.stream, e->total_samples_to_encode);
-               FLAC__stream_encoder_set_metadata(e->encoder.flac.stream, (num_metadata > 0)? metadata : 0, num_metadata);
-               FLAC__stream_encoder_set_write_callback(e->encoder.flac.stream, flac_stream_encoder_write_callback);
-               FLAC__stream_encoder_set_metadata_callback(e->encoder.flac.stream, flac_stream_encoder_metadata_callback);
-               FLAC__stream_encoder_set_client_data(e->encoder.flac.stream, e);
-
-               FLAC__stream_encoder_disable_constant_subframes(e->encoder.flac.stream, options.debug.disable_constant_subframes);
-               FLAC__stream_encoder_disable_fixed_subframes(e->encoder.flac.stream, options.debug.disable_fixed_subframes);
-               FLAC__stream_encoder_disable_verbatim_subframes(e->encoder.flac.stream, options.debug.disable_verbatim_subframes);
-
-               if(FLAC__stream_encoder_init(e->encoder.flac.stream) != FLAC__STREAM_ENCODER_OK) {
-                       print_error_with_state(e, "ERROR initializing encoder");
-                       if(0 != cuesheet)
-                               FLAC__metadata_object_delete(cuesheet);
-                       return false;
-               }
+       {
+               init_status = FLAC__stream_encoder_init_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
        }
-       else {
-               FLAC__file_encoder_set_filename(e->encoder.flac.file, e->outfilename);
-               FLAC__file_encoder_set_verify(e->encoder.flac.file, options.verify);
-               FLAC__file_encoder_set_streamable_subset(e->encoder.flac.file, !options.lax);
-               FLAC__file_encoder_set_do_mid_side_stereo(e->encoder.flac.file, options.do_mid_side);
-               FLAC__file_encoder_set_loose_mid_side_stereo(e->encoder.flac.file, options.loose_mid_side);
-               FLAC__file_encoder_set_channels(e->encoder.flac.file, channels);
-               FLAC__file_encoder_set_bits_per_sample(e->encoder.flac.file, bps);
-               FLAC__file_encoder_set_sample_rate(e->encoder.flac.file, sample_rate);
-               FLAC__file_encoder_set_blocksize(e->encoder.flac.file, options.blocksize);
-               FLAC__file_encoder_set_max_lpc_order(e->encoder.flac.file, options.max_lpc_order);
-               FLAC__file_encoder_set_qlp_coeff_precision(e->encoder.flac.file, options.qlp_coeff_precision);
-               FLAC__file_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.file, options.do_qlp_coeff_prec_search);
-               FLAC__file_encoder_set_do_escape_coding(e->encoder.flac.file, options.do_escape_coding);
-               FLAC__file_encoder_set_do_exhaustive_model_search(e->encoder.flac.file, options.do_exhaustive_model_search);
-               FLAC__file_encoder_set_min_residual_partition_order(e->encoder.flac.file, options.min_residual_partition_order);
-               FLAC__file_encoder_set_max_residual_partition_order(e->encoder.flac.file, options.max_residual_partition_order);
-               FLAC__file_encoder_set_rice_parameter_search_dist(e->encoder.flac.file, options.rice_parameter_search_dist);
-               FLAC__file_encoder_set_total_samples_estimate(e->encoder.flac.file, e->total_samples_to_encode);
-               FLAC__file_encoder_set_metadata(e->encoder.flac.file, (num_metadata > 0)? metadata : 0, num_metadata);
-               FLAC__file_encoder_set_progress_callback(e->encoder.flac.file, flac_file_encoder_progress_callback);
-               FLAC__file_encoder_set_client_data(e->encoder.flac.file, e);
-
-               FLAC__file_encoder_disable_constant_subframes(e->encoder.flac.file, options.debug.disable_constant_subframes);
-               FLAC__file_encoder_disable_fixed_subframes(e->encoder.flac.file, options.debug.disable_fixed_subframes);
-               FLAC__file_encoder_disable_verbatim_subframes(e->encoder.flac.file, options.debug.disable_verbatim_subframes);
-
-               if(FLAC__file_encoder_init(e->encoder.flac.file) != FLAC__FILE_ENCODER_OK) {
-                       print_error_with_state(e, "ERROR initializing encoder");
-                       if(0 != cuesheet)
-                               FLAC__metadata_object_delete(cuesheet);
-                       return false;
-               }
+
+       if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
+               print_error_with_init_status(e, "ERROR initializing encoder", init_status);
+               if(FLAC__stream_encoder_get_state(e->encoder) != FLAC__STREAM_ENCODER_IO_ERROR)
+                       e->outputfile_opened = true;
+               if(0 != cuesheet)
+                       FLAC__metadata_object_delete(cuesheet);
+               return false;
        }
+       else
+               e->outputfile_opened = true;
+
+       e->stats_mask = (FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x0f : 0x3f;
 
        if(0 != cuesheet)
                FLAC__metadata_object_delete(cuesheet);
@@ -1637,23 +2001,7 @@ FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const b
                }
        }
 
-#ifdef FLAC__HAS_OGG
-       if(e->use_ogg) {
-               if(e->is_stdout) {
-                       return OggFLAC__stream_encoder_process(e->encoder.ogg.stream, buffer, samples);
-               }
-               else {
-                       return OggFLAC__file_encoder_process(e->encoder.ogg.file, buffer, samples);
-               }
-       }
-       else
-#endif
-       if(e->is_stdout) {
-               return FLAC__stream_encoder_process(e->encoder.flac.stream, buffer, samples);
-       }
-       else {
-               return FLAC__file_encoder_process(e->encoder.flac.file, buffer, samples);
-       }
+       return FLAC__stream_encoder_process(e->encoder, buffer, samples);
 }
 
 FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e)
@@ -1744,20 +2092,77 @@ FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec,
        return true;
 }
 
-void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps)
+FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata)
+{
+       FLAC__bool metadata_picture_has_type1 = false;
+       FLAC__bool metadata_picture_has_type2 = false;
+       unsigned i;
+
+       FLAC__ASSERT(0 != metadata);
+       for(i = 0; i < num_metadata; i++) {
+               const FLAC__StreamMetadata *m = metadata[i];
+               if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
+                       if(!FLAC__format_seektable_is_legal(&m->data.seek_table)) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: SEEKTABLE metadata block is invalid\n", e->inbasefilename);
+                               return false;
+                       }
+               }
+               else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
+                       if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0)) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: CUESHEET metadata block is invalid\n", e->inbasefilename);
+                               return false;
+                       }
+               }
+               else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
+                       const char *error = 0;
+                       if(!FLAC__format_picture_is_legal(&m->data.picture, &error)) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: PICTURE metadata block is invalid: %s\n", e->inbasefilename, error);
+                               return false;
+                       }
+                       if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
+                               if(metadata_picture_has_type1) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 1 (32x32 icon) in the file\n", e->inbasefilename);
+                                       return false;
+                               }
+                               metadata_picture_has_type1 = true;
+                       }
+                       else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
+                               if(metadata_picture_has_type2) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 2 (icon) in the file\n", e->inbasefilename);
+                                       return false;
+                               }
+                               metadata_picture_has_type2 = true;
+                       }
+               }
+       }
+
+       return true;
+}
+
+FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift, size_t *channel_map)
 {
        unsigned wide_sample, sample, channel, byte;
+       FLAC__int32 *out[FLAC__MAX_CHANNELS];
+
+       if(0 == channel_map) {
+               for(channel = 0; channel < channels; channel++)
+                       out[channel] = dest[channel];
+       }
+       else {
+               for(channel = 0; channel < channels; channel++)
+                       out[channel] = dest[channel_map[channel]];
+       }
 
        if(bps == 8) {
                if(is_unsigned_samples) {
                        for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
                                for(channel = 0; channel < channels; channel++, sample++)
-                                       dest[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
+                                       out[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
                }
                else {
                        for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
                                for(channel = 0; channel < channels; channel++, sample++)
-                                       dest[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
+                                       out[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
                }
        }
        else if(bps == 16) {
@@ -1773,12 +2178,12 @@ void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_
                if(is_unsigned_samples) {
                        for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
                                for(channel = 0; channel < channels; channel++, sample++)
-                                       dest[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
+                                       out[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
                }
                else {
                        for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
                                for(channel = 0; channel < channels; channel++, sample++)
-                                       dest[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
+                                       out[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
                }
        }
        else if(bps == 24) {
@@ -1794,116 +2199,172 @@ void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_
                if(is_unsigned_samples) {
                        for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
                                for(channel = 0; channel < channels; channel++, sample++) {
-                                       dest[channel][wide_sample]  = ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
-                                       dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
-                                       dest[channel][wide_sample] |= ucbuffer_[byte++];
-                                       dest[channel][wide_sample] -= 0x800000;
+                                       out[channel][wide_sample]  = ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
+                                       out[channel][wide_sample] |= ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
+                                       out[channel][wide_sample] |= ucbuffer_[byte++];
+                                       out[channel][wide_sample] -= 0x800000;
                                }
                }
                else {
                        for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
                                for(channel = 0; channel < channels; channel++, sample++) {
-                                       dest[channel][wide_sample]  = scbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
-                                       dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
-                                       dest[channel][wide_sample] |= ucbuffer_[byte++];
+                                       out[channel][wide_sample]  = scbuffer_[byte++]; out[channel][wide_sample] <<= 8;
+                                       out[channel][wide_sample] |= ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
+                                       out[channel][wide_sample] |= ucbuffer_[byte++];
                                }
                }
        }
        else {
                FLAC__ASSERT(0);
        }
+       if(shift > 0) {
+               FLAC__int32 mask = (1<<shift)-1;
+               for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
+                       for(channel = 0; channel < channels; channel++) {
+                               if(out[channel][wide_sample] & mask) {
+                                       flac__utils_printf(stderr, 1, "ERROR during read, sample data (channel#%u sample#%u = %d) has non-zero least-significant bits\n  WAVE/AIFF header said the last %u bits are not significant and should be zero.\n", channel, wide_sample, out[channel][wide_sample], shift);
+                                       return false;
+                               }
+                               out[channel][wide_sample] >>= shift;
+                       }
+       }
+       return true;
 }
 
-#ifdef FLAC__HAS_OGG
-FLAC__StreamEncoderWriteStatus ogg_stream_encoder_write_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
+void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
 {
        EncoderSession *encoder_session = (EncoderSession*)client_data;
 
-       (void)encoder;
+       (void)encoder, (void)total_frames_estimate;
 
-       encoder_session->bytes_written += bytes;
-       /*
-        * With Ogg FLAC we don't get one write callback per frame and
-        * we don't have a good number for 'samples', so we estimate based
-        * on the frame number and the knowledge that all blocks (except
-        * the last) are the same size.
-        */
-       (void)samples;
-       encoder_session->samples_written = (current_frame+1) * encoder_session->blocksize;
+       encoder_session->bytes_written = bytes_written;
+       encoder_session->samples_written = samples_written;
 
-       if(encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
+       if(encoder_session->total_samples_to_encode > 0 && !((frames_written-1) & encoder_session->stats_mask))
                print_stats(encoder_session);
+}
 
-       if(flac__utils_fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
-               return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
+FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
+{
+       size_t n = 0;
+       FLACDecoderData *data = (FLACDecoderData*)client_data;
+       (void)decoder;
+
+       if (data->fatal_error)
+               return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
+
+       /* use up lookahead first */
+       if (data->lookahead_length) {
+               n = min(data->lookahead_length, *bytes);
+               memcpy(buffer, data->lookahead, n);
+               buffer += n;
+               data->lookahead += n;
+               data->lookahead_length -= n;
+       }
+
+       /* get the rest from file */
+       if (*bytes > n) {
+               *bytes = n + fread(buffer, 1, *bytes-n, data->encoder_session->fin);
+               if(ferror(data->encoder_session->fin))
+                       return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
+               else if(0 == *bytes)
+                       return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
+               else
+                       return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
+       }
        else
-               return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+               return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
 }
 
-void ogg_stream_encoder_metadata_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
+FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
 {
-       // do nothing, for compatibilty.  soon we will be using the ogg file encoder anyway.
-       (void)encoder, (void)metadata, (void)client_data;
+       FLACDecoderData *data = (FLACDecoderData*)client_data;
+       (void)decoder;
+
+       if(fseeko(data->encoder_session->fin, (off_t)absolute_byte_offset, SEEK_SET) < 0)
+               return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
+       else
+               return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
 }
 
-void ogg_file_encoder_progress_callback(const OggFLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
+FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
 {
-       EncoderSession *encoder_session = (EncoderSession*)client_data;
-
-       (void)encoder;
+       FLACDecoderData *data = (FLACDecoderData*)client_data;
+       off_t pos;
+       (void)decoder;
 
-       /*
-        * With Ogg FLAC we don't get a value for 'samples_written', so we
-        * estimate based on the frames written and the knowledge that all
-        * blocks (except the last) are the same size.
-        */
-       samples_written = frames_written * encoder_session->blocksize;
-       flac_file_encoder_progress_callback(0, bytes_written, samples_written, frames_written, total_frames_estimate, client_data);
+       if((pos = ftello(data->encoder_session->fin)) < 0)
+               return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
+       else {
+               *absolute_byte_offset = (FLAC__uint64)pos;
+               return FLAC__STREAM_DECODER_TELL_STATUS_OK;
+       }
 }
 
-#endif
-
-FLAC__StreamEncoderWriteStatus flac_stream_encoder_write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
+FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
 {
-       EncoderSession *encoder_session = (EncoderSession*)client_data;
-
-       (void)encoder;
+       FLACDecoderData *data = (FLACDecoderData*)client_data;
+       (void)decoder;
 
-       encoder_session->bytes_written += bytes;
-       encoder_session->samples_written += samples;
+       if(0 == data->filesize)
+               return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
+       else {
+               *stream_length = (FLAC__uint64)data->filesize;
+               return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
+       }
+}
 
-       if(samples && encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
-               print_stats(encoder_session);
+FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data)
+{
+       FLACDecoderData *data = (FLACDecoderData*)client_data;
+       (void)decoder;
 
-       if(flac__utils_fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
-               return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
-       else
-               return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+       return feof(data->encoder_session->fin)? true : false;
 }
 
-void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
+FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
 {
-       /*
-        * Nothing to do; if we get here, we're decoding to stdout, in
-        * which case we can't seek backwards to write new metadata.
-        */
-       (void)encoder, (void)metadata, (void)client_data;
+       FLACDecoderData *data = (FLACDecoderData*)client_data;
+       FLAC__uint64 n = min(data->samples_left_to_process, frame->header.blocksize);
+       (void)decoder;
+
+       if(!EncoderSession_process(data->encoder_session, buffer, (unsigned)n)) {
+               print_error_with_state(data->encoder_session, "ERROR during encoding");
+               data->fatal_error = true;
+               return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
+       }
+
+       data->samples_left_to_process -= n;
+       return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
 }
 
-void flac_file_encoder_progress_callback(const FLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
+void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
 {
-       EncoderSession *encoder_session = (EncoderSession*)client_data;
+       FLACDecoderData *data = (FLACDecoderData*)client_data;
+       (void)decoder;
 
-       (void)encoder, (void)total_frames_estimate;
+       if (data->fatal_error)
+               return;
 
-       encoder_session->bytes_written = bytes_written;
-       encoder_session->samples_written = samples_written;
+       if (
+               data->num_metadata_blocks == sizeof(data->metadata_blocks)/sizeof(data->metadata_blocks[0]) ||
+               0 == (data->metadata_blocks[data->num_metadata_blocks] = FLAC__metadata_object_clone(metadata))
+       )
+               data->fatal_error = true;
+       else
+               data->num_metadata_blocks++;
+}
 
-       if(encoder_session->total_samples_to_encode > 0 && !((frames_written-1) & encoder_session->stats_mask))
-               print_stats(encoder_session);
+void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
+{
+       FLACDecoderData *data = (FLACDecoderData*)client_data;
+       (void)decoder;
+
+       flac__utils_printf(stderr, 1, "%s: ERROR got %s while decoding FLAC input\n", data->encoder_session->inbasefilename, FLAC__StreamDecoderErrorStatusString[status]);
+       data->fatal_error = true;
 }
 
-FLAC__bool parse_cuesheet_(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset)
+FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset)
 {
        FILE *f;
        unsigned last_line_read;
@@ -1918,7 +2379,7 @@ FLAC__bool parse_cuesheet_(FLAC__StreamMetadata **cuesheet, const char *cuesheet
        }
 
        if(0 == (f = fopen(cuesheet_filename, "r"))) {
-               flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading\n", inbasefilename, cuesheet_filename);
+               flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading: %s\n", inbasefilename, cuesheet_filename, strerror(errno));
                return false;
        }
 
@@ -1931,6 +2392,17 @@ FLAC__bool parse_cuesheet_(FLAC__StreamMetadata **cuesheet, const char *cuesheet
                return false;
        }
 
+       if(!FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/false, &error_message)) {
+               flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\": %s\n", inbasefilename, cuesheet_filename, error_message);
+               return false;
+       }
+
+       /* if we're expecting CDDA, warn about non-compliance */
+       if(is_cdda && !FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/true, &error_message)) {
+               flac__utils_printf(stderr, 1, "%s: WARNING cuesheet \"%s\" is not audio CD compliant: %s\n", inbasefilename, cuesheet_filename, error_message);
+               (*cuesheet)->data.cue_sheet.is_cd = false;
+       }
+
        return true;
 }
 
@@ -1938,7 +2410,7 @@ void print_stats(const EncoderSession *encoder_session)
 {
        const FLAC__uint64 samples_written = min(encoder_session->total_samples_to_encode, encoder_session->samples_written);
 #if defined _MSC_VER || defined __MINGW32__
-       /* with VC++ you have to spoon feed it the casting */
+       /* with MSVC you have to spoon feed it the casting */
        const double progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)encoder_session->total_samples_to_encode;
        const double ratio = (double)(FLAC__int64)encoder_session->bytes_written / ((double)(FLAC__int64)encoder_session->unencoded_size * min(1.0, progress));
 #else
@@ -1946,7 +2418,6 @@ void print_stats(const EncoderSession *encoder_session)
        const double ratio = (double)encoder_session->bytes_written / ((double)encoder_session->unencoded_size * min(1.0, progress));
 #endif
 
-
        if(samples_written == encoder_session->total_samples_to_encode) {
                flac__utils_printf(stderr, 2, "\r%s:%s wrote %u bytes, ratio=%0.3f",
                        encoder_session->inbasefilename,
@@ -1960,66 +2431,65 @@ void print_stats(const EncoderSession *encoder_session)
        }
 }
 
-void print_error_with_state(const EncoderSession *e, const char *message)
+void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status)
 {
        const int ilen = strlen(e->inbasefilename) + 1;
-       const char *state_string;
+       const char *state_string = "";
 
        flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
 
-#ifdef FLAC__HAS_OGG
-       if(e->use_ogg) {
-               if(e->is_stdout) {
-                       state_string = OggFLAC__stream_encoder_get_resolved_state_string(e->encoder.ogg.stream);
+       flac__utils_printf(stderr, 1, "%*s init_status = %s\n", ilen, "", FLAC__StreamEncoderInitStatusString[init_status]);
+
+       if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR) {
+               state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
+
+               flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
+
+               /* print out some more info for some errors: */
+               if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
+                       flac__utils_printf(stderr, 1,
+                               "\n"
+                               "An error occurred while writing; the most common cause is that the disk is full.\n"
+                       );
                }
-               else {
-                       state_string = OggFLAC__file_encoder_get_resolved_state_string(e->encoder.ogg.file);
+               else if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_IO_ERROR])) {
+                       flac__utils_printf(stderr, 1,
+                               "\n"
+                               "An error occurred opening the output file; it is likely that the output\n"
+                               "directory does not exist or is not writable, the output file already exists and\n"
+                               "is not writable, or the disk is full.\n"
+                       );
                }
        }
-       else
-#endif
-       if(e->is_stdout) {
-               state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder.flac.stream);
-       }
-       else {
-               state_string = FLAC__file_encoder_get_resolved_state_string(e->encoder.flac.file);
-       }
-
-       flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
-
-       /* print out some more info for some errors: */
-       if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_NOT_STREAMABLE])) {
+       else if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE) {
                flac__utils_printf(stderr, 1,
                        "\n"
                        "The encoding parameters specified do not conform to the FLAC Subset and may not\n"
-                       "be streamable or playable in hardware devices.  Add --lax to the command-line\n"
-                       "options to encode with these parameters.\n"
+                       "be streamable or playable in hardware devices.  If you really understand the\n"
+                       "consequences, you can add --lax to the command-line options to encode with\n"
+                       "these parameters anyway.  See http://flac.sourceforge.net/format.html#subset\n"
                );
        }
-       else if(
-               0 == strcmp(state_string, FLAC__FileEncoderStateString[FLAC__FILE_ENCODER_FATAL_ERROR_WHILE_WRITING])
-#ifdef FLAC__HAS_OGG
-               || 0 == strcmp(state_string, OggFLAC__FileEncoderStateString[OggFLAC__FILE_ENCODER_FATAL_ERROR_WHILE_WRITING])
-#endif
-       ) {
+}
+
+void print_error_with_state(const EncoderSession *e, const char *message)
+{
+       const int ilen = strlen(e->inbasefilename) + 1;
+       const char *state_string;
+
+       flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
+
+       state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
+
+       flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
+
+       /* print out some more info for some errors: */
+       if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
                flac__utils_printf(stderr, 1,
                        "\n"
                        "An error occurred while writing; the most common cause is that the disk is full.\n"
                );
        }
-       else if(
-               0 == strcmp(state_string, FLAC__FileEncoderStateString[FLAC__FILE_ENCODER_ERROR_OPENING_FILE])
-#ifdef FLAC__HAS_OGG
-               || 0 == strcmp(state_string, OggFLAC__FileEncoderStateString[OggFLAC__FILE_ENCODER_ERROR_OPENING_FILE])
-#endif
-       ) {
-               flac__utils_printf(stderr, 1,
-                       "\n"
-                       "An error occurred opening the output file; it is likely that the output\n"
-                       "directory does not exist or is not writable, the output file already exists and\n"
-                       "is not writable, or the disk is full.\n"
-               );
-       }
 }
 
 void print_verify_error(EncoderSession *e)
@@ -2031,35 +2501,21 @@ void print_verify_error(EncoderSession *e)
        FLAC__int32 expected;
        FLAC__int32 got;
 
-#ifdef FLAC__HAS_OGG
-       if(e->use_ogg) {
-               if(e->is_stdout) {
-                       OggFLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.ogg.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
-               }
-               else {
-                       OggFLAC__file_encoder_get_verify_decoder_error_stats(e->encoder.ogg.file, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
-               }
-       }
-       else
-#endif
-       if(e->is_stdout) {
-               FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.flac.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
-       }
-       else {
-               FLAC__file_encoder_get_verify_decoder_error_stats(e->encoder.flac.file, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
-       }
+       FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
 
        flac__utils_printf(stderr, 1, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
        flac__utils_printf(stderr, 1, "       Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)absolute_sample, frame_number, channel, sample, expected, got);
        flac__utils_printf(stderr, 1, "       In all known cases, verify errors are caused by hardware problems,\n");
-       flac__utils_printf(stderr, 1, "       usually overclocking or bad RAM.  Delete %s\n", e->inbasefilename);
+       flac__utils_printf(stderr, 1, "       usually overclocking or bad RAM.  Delete %s\n", e->outfilename);
        flac__utils_printf(stderr, 1, "       and repeat the flac command exactly as before.  If it does not give a\n");
        flac__utils_printf(stderr, 1, "       verify error in the exact same place each time you try it, then there is\n");
-       flac__utils_printf(stderr, 1, "       a problem with your hardware.  If it does, keep the bad FLAC file and\n");
-       flac__utils_printf(stderr, 1, "       submit a bug report to:\n");
-       flac__utils_printf(stderr, 1, "           http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
-       flac__utils_printf(stderr, 1, "       Make sure to include an email contact in the comment and/or use the\n");
-       flac__utils_printf(stderr, 1, "       \"Monitor\" feature to monitor the bug status.\n");
+       flac__utils_printf(stderr, 1, "       a problem with your hardware; please see the FAQ:\n");
+       flac__utils_printf(stderr, 1, "           http://flac.sourceforge.net/faq.html#tools__hardware_prob\n");
+       flac__utils_printf(stderr, 1, "       If it does fail in the exact same place every time, keep\n");
+       flac__utils_printf(stderr, 1, "       %s and submit a bug report to:\n", e->outfilename);
+       flac__utils_printf(stderr, 1, "           https://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
+       flac__utils_printf(stderr, 1, "       Make sure to upload the FLAC file and use the \"Monitor\" feature to\n");
+       flac__utils_printf(stderr, 1, "       monitor the bug status.\n");
        flac__utils_printf(stderr, 1, "Verify FAILED!  Do not trust %s\n", e->outfilename);
 }
 
@@ -2183,3 +2639,53 @@ FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, con
 
        return true;
 }
+
+FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset)
+{
+       static unsigned char dump[8192];
+
+       while(offset > 0) {
+               long need = (long)min(offset, LONG_MAX);
+               if(fseeko(f, need, SEEK_CUR) < 0) {
+                       need = (long)min(offset, sizeof(dump));
+                       if((long)fread(dump, 1, need, f) < need)
+                               return false;
+               }
+               offset -= need;
+       }
+#if 0 /* pure non-fseek() version */
+       while(offset > 0) {
+               const long need = (long)min(offset, sizeof(dump));
+               if(fread(dump, 1, need, f) < need)
+                       return false;
+               offset -= need;
+       }
+#endif
+       return true;
+}
+
+unsigned count_channel_mask_bits(FLAC__uint32 mask)
+{
+       unsigned count = 0;
+       while(mask) {
+               if(mask & 1)
+                       count++;
+               mask >>= 1;
+       }
+       return count;
+}
+
+FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels)
+{
+       FLAC__uint32 x = 0x80000000;
+       unsigned count = count_channel_mask_bits(mask);
+       while(x && count > channels) {
+               if(mask & x) {
+                       mask &= ~x;
+                       count--;
+               }
+               x >>= 1;
+       }
+       FLAC__ASSERT(count_channel_mask_bits(mask) == channels);
+       return mask;
+}