add support for --picture command to import PICTURE metadata
[platform/upstream/flac.git] / src / flac / decode.c
index e84de04..a7a122f 100644 (file)
@@ -1,5 +1,5 @@
 /* flac - Command-line FLAC encoder/decoder
- * Copyright (C) 2000,2001  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 */
+//@@@ [2G limit] hacks for MSVC6
+#define fseeko fseek
+#define ftello ftell
+#endif
+#include <errno.h>
 #include <math.h> /* for floor() */
-#include <stdio.h> /* for FILE et al. */
-#include <string.h> /* for strcmp() */
+#include <stdio.h> /* for FILE etc. */
+#include <string.h> /* for strcmp(), strerror() */
 #include "FLAC/all.h"
+#include "share/grabbag.h"
+#include "share/replaygain_synthesis.h"
 #include "decode.h"
-#include "file.h"
-#ifdef FLaC__HAS_OGG
-#include "ogg/ogg.h"
-#endif
 
-#ifdef FLaC__HAS_OGG
-typedef struct {
-       ogg_sync_state oy;
-       ogg_stream_state os;
-} ogg_info_struct;
+#ifdef FLAC__HAS_OGG
+#include "OggFLAC/stream_decoder.h"
 #endif
 
 typedef struct {
-       const char *inbasefilename;
-#ifdef FLaC__HAS_OGG
-       FILE *fin;
+#ifdef FLAC__HAS_OGG
+       FLAC__bool is_ogg;
 #endif
-       FILE *fout;
-       FLAC__bool abort_flag;
+
+       FLAC__bool is_aiff_out;
+       FLAC__bool is_wave_out;
+       FLAC__bool continue_through_decode_errors;
+
+       struct {
+               replaygain_synthesis_spec_t spec;
+               FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */
+               double scale;
+               DitherContext dither_context;
+       } replaygain;
+
+       FLAC__bool test_only;
        FLAC__bool analysis_mode;
        analysis_options aopts;
-       FLAC__bool test_only;
-       FLAC__bool is_wave_out;
+       utils__SkipUntilSpecification *skip_specification;
+       utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
+       utils__CueSpecification *cue_specification;
+
+       const char *inbasefilename;
+       const char *outfilename;
+
+       FLAC__uint64 samples_processed;
+       unsigned frame_counter;
+       FLAC__bool abort_flag;
+       FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
+       FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */
+
+       FLAC__bool iff_headers_need_fixup;
+
        FLAC__bool is_big_endian;
        FLAC__bool is_unsigned_samples;
+       FLAC__bool got_stream_info;
        FLAC__uint64 total_samples;
        unsigned bps;
        unsigned channels;
        unsigned sample_rate;
-       FLAC__bool verbose;
-       FLAC__uint64 skip;
-       FLAC__bool skip_count_too_high;
-       FLAC__uint64 samples_processed;
-       unsigned frame_counter;
-#ifdef FLaC__HAS_OGG
-       FLAC__bool is_ogg;
-#endif
+
        union {
-               FLAC__FileDecoder *file;
-               FLAC__StreamDecoder *stream;
-       } decoder;
-#ifdef FLaC__HAS_OGG
-       ogg_info_struct ogg;
+               FLAC__StreamDecoder *flac;
+#ifdef FLAC__HAS_OGG
+               OggFLAC__StreamDecoder *ogg;
 #endif
-} stream_info_struct;
+       } decoder;
+
+       FILE *fout;
+} DecoderSession;
+
 
-static FLAC__bool is_big_endian_host;
+static FLAC__bool is_big_endian_host_;
 
-/* local routines */
-static FLAC__bool init(const char *infilename, stream_info_struct *stream_info);
+
+/*
+ * local routines
+ */
+static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, const char *infilename, const char *outfilename);
+static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
+static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, decode_options_t decode_options, const char *infilename);
+static FLAC__bool DecoderSession_process(DecoderSession *d);
+static int DecoderSession_finish_ok(DecoderSession *d);
+static int DecoderSession_finish_error(DecoderSession *d);
+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 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples);
 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
-#ifdef FLaC__HAS_OGG
-static FLAC__StreamDecoderReadStatus read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
-#endif
+static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
+static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
+static FLAC__bool write_sane_extended(FILE *f, unsigned val);
+static FLAC__bool fixup_iff_headers(DecoderSession *d);
+static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
+static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
+static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
+static void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status);
+static void print_error_with_state(const DecoderSession *d, const char *message);
+static void print_stats(const DecoderSession *decoder_session);
+
+
 /*
- * We use 'void *' so that we can use the same callbacks for the
- * FLAC__StreamDecoder and FLAC__FileDecoder.  The 'decoder' argument is
- * actually never used in the callbacks.
+ * public routines
  */
-static FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data);
-static void metadata_callback(const void *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
-static void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
-static void print_stats(const stream_info_struct *stream_info);
+int flac__decode_aiff(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
+{
+       DecoderSession decoder_session;
+
+       if(!
+               DecoderSession_construct(
+                       &decoder_session,
+#ifdef FLAC__HAS_OGG
+                       options.common.is_ogg,
+#else
+                       /*is_ogg=*/false,
+#endif
+                       /*is_aiff_out=*/true,
+                       /*is_wave_out=*/false,
+                       options.common.continue_through_decode_errors,
+                       options.common.replaygain_synthesis_spec,
+                       analysis_mode,
+                       aopts,
+                       &options.common.skip_specification,
+                       &options.common.until_specification,
+                       options.common.has_cue_specification? &options.common.cue_specification : 0,
+                       infilename,
+                       outfilename
+               )
+       )
+               return 1;
+
+       if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
+               return DecoderSession_finish_error(&decoder_session);
 
+       if(!DecoderSession_process(&decoder_session))
+               return DecoderSession_finish_error(&decoder_session);
+
+       return DecoderSession_finish_ok(&decoder_session);
+}
 
 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
 {
-       FLAC__bool md5_failure = false;
-       stream_info_struct stream_info;
-
-       stream_info.abort_flag = false;
-       stream_info.analysis_mode = analysis_mode;
-       stream_info.aopts = aopts;
-       stream_info.test_only = (outfilename == 0);
-       stream_info.is_wave_out = true;
-       stream_info.verbose = options.common.verbose;
-       stream_info.skip = options.common.skip;
-       stream_info.skip_count_too_high = false;
-       stream_info.samples_processed = 0;
-       stream_info.frame_counter = 0;
-#ifdef FLaC__HAS_OGG
-       stream_info.is_ogg = options.common.is_ogg;
+       DecoderSession decoder_session;
+
+       if(!
+               DecoderSession_construct(
+                       &decoder_session,
+#ifdef FLAC__HAS_OGG
+                       options.common.is_ogg,
+#else
+                       /*is_ogg=*/false,
+#endif
+                       /*is_aiff_out=*/false,
+                       /*is_wave_out=*/true,
+                       options.common.continue_through_decode_errors,
+                       options.common.replaygain_synthesis_spec,
+                       analysis_mode,
+                       aopts,
+                       &options.common.skip_specification,
+                       &options.common.until_specification,
+                       options.common.has_cue_specification? &options.common.cue_specification : 0,
+                       infilename,
+                       outfilename
+               )
+       )
+               return 1;
+
+       if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
+               return DecoderSession_finish_error(&decoder_session);
+
+       if(!DecoderSession_process(&decoder_session))
+               return DecoderSession_finish_error(&decoder_session);
+
+       return DecoderSession_finish_ok(&decoder_session);
+}
+
+int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
+{
+       DecoderSession decoder_session;
+
+       decoder_session.is_big_endian = options.is_big_endian;
+       decoder_session.is_unsigned_samples = options.is_unsigned_samples;
+
+       if(!
+               DecoderSession_construct(
+                       &decoder_session,
+#ifdef FLAC__HAS_OGG
+                       options.common.is_ogg,
+#else
+                       /*is_ogg=*/false,
+#endif
+                       /*is_aiff_out=*/false,
+                       /*is_wave_out=*/false,
+                       options.common.continue_through_decode_errors,
+                       options.common.replaygain_synthesis_spec,
+                       analysis_mode,
+                       aopts,
+                       &options.common.skip_specification,
+                       &options.common.until_specification,
+                       options.common.has_cue_specification? &options.common.cue_specification : 0,
+                       infilename,
+                       outfilename
+               )
+       )
+               return 1;
+
+       if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
+               return DecoderSession_finish_error(&decoder_session);
+
+       if(!DecoderSession_process(&decoder_session))
+               return DecoderSession_finish_error(&decoder_session);
+
+       return DecoderSession_finish_ok(&decoder_session);
+}
+
+FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, const char *infilename, const char *outfilename)
+{
+#ifdef FLAC__HAS_OGG
+       d->is_ogg = is_ogg;
+#else
+       (void)is_ogg;
 #endif
-       stream_info.decoder.file = 0; /* this zeroes stream_info.decoder.stream also */
-       stream_info.inbasefilename = flac__file_get_basename(infilename);
-       stream_info.fout = 0; /* initialized with an open file later if necessary */
 
-       FLAC__ASSERT(!(stream_info.test_only && stream_info.analysis_mode));
+       d->is_aiff_out = is_aiff_out;
+       d->is_wave_out = is_wave_out;
+       d->continue_through_decode_errors = continue_through_decode_errors;
+       d->replaygain.spec = replaygain_synthesis_spec;
+       d->replaygain.apply = false;
+       d->replaygain.scale = 0.0;
+       /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
+       d->test_only = (0 == outfilename);
+       d->analysis_mode = analysis_mode;
+       d->aopts = aopts;
+       d->skip_specification = skip_specification;
+       d->until_specification = until_specification;
+       d->cue_specification = cue_specification;
 
-       if(!stream_info.test_only) {
+       d->inbasefilename = grabbag__file_get_basename(infilename);
+       d->outfilename = outfilename;
+
+       d->samples_processed = 0;
+       d->frame_counter = 0;
+       d->abort_flag = false;
+       d->aborting_due_to_until = false;
+       d->aborting_due_to_unparseable = false;
+
+       d->iff_headers_need_fixup = false;
+
+       d->total_samples = 0;
+       d->got_stream_info = false;
+       d->bps = 0;
+       d->channels = 0;
+       d->sample_rate = 0;
+
+       d->decoder.flac = 0;
+#ifdef FLAC__HAS_OGG
+       d->decoder.ogg = 0;
+#endif
+
+       d->fout = 0; /* initialized with an open file later if necessary */
+
+       FLAC__ASSERT(!(d->test_only && d->analysis_mode));
+
+       if(!d->test_only) {
                if(0 == strcmp(outfilename, "-")) {
-                       stream_info.fout = stdout;
+                       d->fout = grabbag__file_get_binary_stdout();
                }
                else {
-                       if(0 == (stream_info.fout = fopen(outfilename, "wb"))) {
-                               fprintf(stderr, "%s: ERROR: can't open output file %s\n", stream_info.inbasefilename, outfilename);
-                               return 1;
-                       }
-               }
-       }
-
-#ifdef FLaC__HAS_OGG
-       if(stream_info.is_ogg) {
-               if (0 == strcmp(infilename, "-")) {
-                       stream_info.fin = stdin;
-               } else {
-                       if (0 == (stream_info.fin = fopen(infilename, "rb"))) {
-                               fprintf(stderr, "%s: ERROR: can't open input file %s\n", stream_info.inbasefilename, infilename);
-                               if(stream_info.fout != stdout)
-                                       fclose(stream_info.fout);
-                               return 1;
+                       if(0 == (d->fout = fopen(outfilename, "wb"))) {
+                               flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
+                               DecoderSession_destroy(d, /*error_occurred=*/true);
+                               return false;
                        }
                }
        }
-#endif
 
        if(analysis_mode)
                flac__analyze_init(aopts);
 
-       if(!init(infilename, &stream_info))
-               goto wav_abort_;
+       return true;
+}
 
-       if(stream_info.skip > 0) {
-#ifdef FLaC__HAS_OGG
-               if(stream_info.is_ogg) { //@@@ (move this check into main.c)
-                       fprintf(stderr, "%s: ERROR, can't skip when decoding Ogg-FLAC yet; convert to native-FLAC first\n", stream_info.inbasefilename);
-                       goto wav_abort_;
-               }
-#endif
-               if(!FLAC__file_decoder_process_metadata(stream_info.decoder.file)) {
-                       fprintf(stderr, "%s: ERROR while decoding metadata, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                       goto wav_abort_;
-               }
-               if(stream_info.skip_count_too_high) {
-                       fprintf(stderr, "%s: ERROR trying to skip more samples than in stream\n", stream_info.inbasefilename);
-                       goto wav_abort_;
-               }
-               if(!FLAC__file_decoder_seek_absolute(stream_info.decoder.file, stream_info.skip)) {
-                       fprintf(stderr, "%s: ERROR seeking while skipping bytes, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                       goto wav_abort_;
-               }
-               if(!FLAC__file_decoder_process_remaining_frames(stream_info.decoder.file)) {
-                       if(stream_info.verbose) fprintf(stderr, "\n");
-                       fprintf(stderr, "%s: ERROR while decoding frames, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                       goto wav_abort_;
-               }
-               if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_END_OF_FILE) {
-                       if(stream_info.verbose) fprintf(stderr, "\n");
-                       fprintf(stderr, "%s: ERROR during decoding, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                       goto wav_abort_;
-               }
+void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
+{
+       if(0 != d->fout && d->fout != stdout) {
+               fclose(d->fout);
+               if(error_occurred)
+                       unlink(d->outfilename);
        }
-       else {
-#ifdef FLaC__HAS_OGG
-               if(stream_info.is_ogg) {
-                       if(!FLAC__stream_decoder_process_whole_stream(stream_info.decoder.stream)) {
-                               if(stream_info.verbose) fprintf(stderr, "\n");
-                               fprintf(stderr, "%s: ERROR while decoding data, state=%d:%s\n", stream_info.inbasefilename, FLAC__stream_decoder_get_state(stream_info.decoder.stream), FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(stream_info.decoder.stream)]);
-                               goto wav_abort_;
-                       }
-                       if(FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA && FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_END_OF_STREAM) {
-                               if(stream_info.verbose) fprintf(stderr, "\n");
-                               fprintf(stderr, "%s: ERROR during decoding, state=%d:%s\n", stream_info.inbasefilename, FLAC__stream_decoder_get_state(stream_info.decoder.stream), FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(stream_info.decoder.stream)]);
-                               goto wav_abort_;
-                       }
-               }
-               else
-#endif
-               {
-                       if(!FLAC__file_decoder_process_whole_file(stream_info.decoder.file)) {
-                               if(stream_info.verbose) fprintf(stderr, "\n");
-                               fprintf(stderr, "%s: ERROR while decoding data, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                               goto wav_abort_;
-                       }
-                       if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_END_OF_FILE) {
-                               if(stream_info.verbose) fprintf(stderr, "\n");
-                               fprintf(stderr, "%s: ERROR during decoding, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                               goto wav_abort_;
-                       }
+}
+
+FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, decode_options_t decode_options, const char *infilename)
+{
+       FLAC__StreamDecoderInitStatus init_status;
+       FLAC__uint32 test = 1;
+
+       is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
+
+#ifdef FLAC__HAS_OGG
+       if(decoder_session->is_ogg) {
+               decoder_session->decoder.ogg = OggFLAC__stream_decoder_new();
+
+               if(0 == decoder_session->decoder.ogg) {
+                       flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
+                       return false;
                }
-       }
 
-#ifdef FLaC__HAS_OGG
-       if(stream_info.is_ogg) {
-               if(stream_info.decoder.stream) {
-                       if(FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_UNINITIALIZED)
-                               FLAC__stream_decoder_finish(stream_info.decoder.stream);
-                       md5_failure = false;
-                       print_stats(&stream_info);
-                       FLAC__stream_decoder_delete(stream_info.decoder.stream);
+               OggFLAC__stream_decoder_set_md5_checking(decoder_session->decoder.ogg, true);
+               if(!decode_options.use_first_serial_number)
+                       OggFLAC__stream_decoder_set_serial_number(decoder_session->decoder.ogg, decode_options.serial_number);
+               if (0 != decoder_session->cue_specification)
+                       OggFLAC__stream_decoder_set_metadata_respond(decoder_session->decoder.ogg, FLAC__METADATA_TYPE_CUESHEET);
+               if (decoder_session->replaygain.spec.apply)
+                       OggFLAC__stream_decoder_set_metadata_respond(decoder_session->decoder.ogg, FLAC__METADATA_TYPE_VORBIS_COMMENT);
+
+               init_status = OggFLAC__stream_decoder_init_file(decoder_session->decoder.ogg, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
+               if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
+                       print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
+                       return false;
                }
        }
        else
+#else
+       (void)decode_options;
 #endif
        {
-               if(stream_info.decoder.file) {
-                       if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_UNINITIALIZED)
-                               md5_failure = !FLAC__file_decoder_finish(stream_info.decoder.file);
-                       print_stats(&stream_info);
-                       FLAC__file_decoder_delete(stream_info.decoder.file);
-               }
-       }
-       if(0 != stream_info.fout && stream_info.fout != stdout)
-               fclose(stream_info.fout);
-#ifdef FLaC__HAS_OGG
-       if(stream_info.is_ogg) {
-               if(0 != stream_info.fin && stream_info.fin != stdin)
-                       fclose(stream_info.fin);
-       }
-#endif
-       if(analysis_mode)
-               flac__analyze_finish(aopts);
-       if(md5_failure) {
-               fprintf(stderr, "\r%s: WARNING, MD5 signature mismatch\n", stream_info.inbasefilename);
-       }
-       else {
-               if(stream_info.verbose)
-                       fprintf(stderr, "\r%s: %s         \n", stream_info.inbasefilename, stream_info.test_only? "ok           ":analysis_mode?"done           ":"done");
-       }
-       return 0;
-wav_abort_:
-#ifdef FLaC__HAS_OGG
-       if(stream_info.is_ogg) {
-               if(stream_info.decoder.stream) {
-                       if(FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_UNINITIALIZED)
-                               FLAC__stream_decoder_finish(stream_info.decoder.stream);
-                       FLAC__stream_decoder_delete(stream_info.decoder.stream);
+               decoder_session->decoder.flac = FLAC__stream_decoder_new();
+
+               if(0 == decoder_session->decoder.flac) {
+                       flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
+                       return false;
                }
-       }
-       else
-#endif
-       {
-               if(stream_info.decoder.file) {
-                       if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_UNINITIALIZED)
-                               FLAC__file_decoder_finish(stream_info.decoder.file);
-                       FLAC__file_decoder_delete(stream_info.decoder.file);
+
+               FLAC__stream_decoder_set_md5_checking(decoder_session->decoder.flac, true);
+               if (0 != decoder_session->cue_specification)
+                       FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder.flac, FLAC__METADATA_TYPE_CUESHEET);
+               if (decoder_session->replaygain.spec.apply)
+                       FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder.flac, FLAC__METADATA_TYPE_VORBIS_COMMENT);
+
+               init_status = FLAC__stream_decoder_init_file(decoder_session->decoder.flac, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
+               if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
+                       print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
+                       return false;
                }
        }
-       if(0 != stream_info.fout && stream_info.fout != stdout) {
-               fclose(stream_info.fout);
-               unlink(outfilename);
-       }
-#ifdef FLaC__HAS_OGG
-       if(stream_info.is_ogg) {
-               if(0 != stream_info.fin && stream_info.fin != stdin)
-                       fclose(stream_info.fin);
-       }
-#endif
-       if(analysis_mode)
-               flac__analyze_finish(aopts);
-       return 1;
+
+       return true;
 }
 
-int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
+FLAC__bool DecoderSession_process(DecoderSession *d)
 {
-       FLAC__bool md5_failure = false;
-       stream_info_struct stream_info;
-
-       stream_info.abort_flag = false;
-       stream_info.analysis_mode = analysis_mode;
-       stream_info.aopts = aopts;
-       stream_info.test_only = (outfilename == 0);
-       stream_info.is_wave_out = false;
-       stream_info.is_big_endian = options.is_big_endian;
-       stream_info.is_unsigned_samples = options.is_unsigned_samples;
-       stream_info.verbose = options.common.verbose;
-       stream_info.skip = options.common.skip;
-       stream_info.skip_count_too_high = false;
-       stream_info.samples_processed = 0;
-       stream_info.frame_counter = 0;
-#ifdef FLaC__HAS_OGG
-       stream_info.is_ogg = options.common.is_ogg;
+#ifdef FLAC__HAS_OGG
+       if(d->is_ogg) {
+               if(!OggFLAC__stream_decoder_process_until_end_of_metadata(d->decoder.ogg)) {
+                       flac__utils_printf(stderr, 2, "\n");
+                       print_error_with_state(d, "ERROR while decoding metadata");
+                       return false;
+               }
+               if(OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_OK && OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_END_OF_STREAM) {
+                       flac__utils_printf(stderr, 2, "\n");
+                       print_error_with_state(d, "ERROR during metadata decoding");
+                       if(!d->continue_through_decode_errors)
+                               return false;
+               }
+       }
+       else
 #endif
-       stream_info.decoder.file = 0; /* this zeroes stream_info.decoder.stream also */
-       stream_info.inbasefilename = flac__file_get_basename(infilename);
-       stream_info.fout = 0; /* initialized with an open file later if necessary */
-
-       FLAC__ASSERT(!(stream_info.test_only && stream_info.analysis_mode));
-
-       if(!stream_info.test_only) {
-               if(0 == strcmp(outfilename, "-")) {
-                       stream_info.fout = stdout;
+       {
+               if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder.flac)) {
+                       flac__utils_printf(stderr, 2, "\n");
+                       print_error_with_state(d, "ERROR while decoding metadata");
+                       return false;
                }
-               else {
-                       if(0 == (stream_info.fout = fopen(outfilename, "wb"))) {
-                               fprintf(stderr, "%s: ERROR: can't open output file %s\n", stream_info.inbasefilename, outfilename);
-                               return 1;
-                       }
+               if(FLAC__stream_decoder_get_state(d->decoder.flac) > FLAC__STREAM_DECODER_END_OF_STREAM) {
+                       flac__utils_printf(stderr, 2, "\n");
+                       print_error_with_state(d, "ERROR during metadata decoding");
+                       if(!d->continue_through_decode_errors)
+                               return false;
                }
        }
+       if(d->abort_flag)
+               return false;
 
-#ifdef FLaC__HAS_OGG
-       if(stream_info.is_ogg) {
-               if (0 == strcmp(infilename, "-")) {
-                       stream_info.fin = stdin;
-               } else {
-                       if (0 == (stream_info.fin = fopen(infilename, "rb"))) {
-                               fprintf(stderr, "%s: ERROR: can't open input file %s\n", stream_info.inbasefilename, infilename);
-                               if(stream_info.fout != stdout)
-                                       fclose(stream_info.fout);
-                               return 1;
-                       }
+       /* write the WAVE/AIFF headers if necessary */
+       if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out)) {
+               if(!write_iff_headers(d->fout, d, d->total_samples)) {
+                       d->abort_flag = true;
+                       return false;
                }
        }
-#endif
 
-       if(analysis_mode)
-               flac__analyze_init(aopts);
+       if(d->skip_specification->value.samples > 0) {
+               const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
 
-       if(!init(infilename, &stream_info))
-               goto raw_abort_;
-
-       if(stream_info.skip > 0) {
-#ifdef FLaC__HAS_OGG
-               if(stream_info.is_ogg) { //@@@ (move this check into main.c)
-                       fprintf(stderr, "%s: ERROR, can't skip when decoding Ogg-FLAC yet; convert to native-FLAC first\n", stream_info.inbasefilename);
-                       goto raw_abort_;
+#ifdef FLAC__HAS_OGG
+               if(d->is_ogg) {
+                       if(!OggFLAC__stream_decoder_seek_absolute(d->decoder.ogg, skip)) {
+                               print_error_with_state(d, "ERROR seeking while skipping bytes");
+                               return false;
+                       }
+                       if(!OggFLAC__stream_decoder_process_until_end_of_stream(d->decoder.ogg) && !d->aborting_due_to_until) {
+                               flac__utils_printf(stderr, 2, "\n");
+                               print_error_with_state(d, "ERROR while decoding frames");
+                               return false;
+                       }
+                       if(OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_OK && OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until) {
+                               flac__utils_printf(stderr, 2, "\n");
+                               print_error_with_state(d, "ERROR during decoding");
+                               return false;
+                       }
                }
+               else
 #endif
-               if(!FLAC__file_decoder_process_metadata(stream_info.decoder.file)) {
-                       fprintf(stderr, "%s: ERROR while decoding metadata, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                       goto raw_abort_;
-               }
-               if(stream_info.skip_count_too_high) {
-                       fprintf(stderr, "%s: ERROR trying to skip more samples than in stream\n", stream_info.inbasefilename);
-                       goto raw_abort_;
-               }
-               if(!FLAC__file_decoder_seek_absolute(stream_info.decoder.file, stream_info.skip)) {
-                       fprintf(stderr, "%s: ERROR seeking while skipping bytes, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                       goto raw_abort_;
-               }
-               if(!FLAC__file_decoder_process_remaining_frames(stream_info.decoder.file)) {
-                       if(stream_info.verbose) fprintf(stderr, "\n");
-                       fprintf(stderr, "%s: ERROR while decoding frames, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                       goto raw_abort_;
-               }
-               if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_END_OF_FILE) {
-                       if(stream_info.verbose) fprintf(stderr, "\n");
-                       fprintf(stderr, "%s: ERROR during decoding, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                       goto raw_abort_;
+               {
+                       if(!FLAC__stream_decoder_seek_absolute(d->decoder.flac, skip)) {
+                               print_error_with_state(d, "ERROR seeking while skipping bytes");
+                               return false;
+                       }
+                       if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder.flac) && !d->aborting_due_to_until) {
+                               flac__utils_printf(stderr, 2, "\n");
+                               print_error_with_state(d, "ERROR while decoding frames");
+                               return false;
+                       }
+                       if(FLAC__stream_decoder_get_state(d->decoder.flac) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until) {
+                               flac__utils_printf(stderr, 2, "\n");
+                               print_error_with_state(d, "ERROR during decoding");
+                               return false;
+                       }
                }
        }
        else {
-#ifdef FLaC__HAS_OGG
-               if(stream_info.is_ogg) {
-                       if(!FLAC__stream_decoder_process_whole_stream(stream_info.decoder.stream)) {
-                               if(stream_info.verbose) fprintf(stderr, "\n");
-                               fprintf(stderr, "%s: ERROR while decoding data, state=%d:%s\n", stream_info.inbasefilename, FLAC__stream_decoder_get_state(stream_info.decoder.stream), FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(stream_info.decoder.stream)]);
-                               goto raw_abort_;
+#ifdef FLAC__HAS_OGG
+               if(d->is_ogg) {
+                       if(!OggFLAC__stream_decoder_process_until_end_of_stream(d->decoder.ogg) && !d->aborting_due_to_until) {
+                               flac__utils_printf(stderr, 2, "\n");
+                               print_error_with_state(d, "ERROR while decoding data");
+                               return false;
                        }
-                       if(FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA && FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_END_OF_STREAM) {
-                               if(stream_info.verbose) fprintf(stderr, "\n");
-                               fprintf(stderr, "%s: ERROR during decoding, state=%d:%s\n", stream_info.inbasefilename, FLAC__stream_decoder_get_state(stream_info.decoder.stream), FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(stream_info.decoder.stream)]);
-                               goto raw_abort_;
+                       if(OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_OK && OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until) {
+                               flac__utils_printf(stderr, 2, "\n");
+                               print_error_with_state(d, "ERROR during decoding");
+                               return false;
                        }
                }
                else
 #endif
                {
-                       if(!FLAC__file_decoder_process_whole_file(stream_info.decoder.file)) {
-                               if(stream_info.verbose) fprintf(stderr, "\n");
-                               fprintf(stderr, "%s: ERROR while decoding data, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                               goto raw_abort_;
+                       if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder.flac) && !d->aborting_due_to_until) {
+                               flac__utils_printf(stderr, 2, "\n");
+                               print_error_with_state(d, "ERROR while decoding data");
+                               return false;
                        }
-                       if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_END_OF_FILE) {
-                               if(stream_info.verbose) fprintf(stderr, "\n");
-                               fprintf(stderr, "%s: ERROR during decoding, state=%d:%s\n", stream_info.inbasefilename, FLAC__file_decoder_get_state(stream_info.decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info.decoder.file)]);
-                               goto raw_abort_;
+                       if(FLAC__stream_decoder_get_state(d->decoder.flac) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until) {
+                               flac__utils_printf(stderr, 2, "\n");
+                               print_error_with_state(d, "ERROR during decoding");
+                               return false;
                        }
                }
        }
 
-#ifdef FLaC__HAS_OGG
-       if(stream_info.is_ogg) {
-               if(stream_info.decoder.stream) {
-                       if(FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_UNINITIALIZED)
-                               FLAC__stream_decoder_finish(stream_info.decoder.stream);
-                       md5_failure = false;
-                       print_stats(&stream_info);
-                       FLAC__stream_decoder_delete(stream_info.decoder.stream);
+       if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out) && ((d->total_samples * d->channels * ((d->bps+7)/8)) & 1)) {
+               if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
+                       print_error_with_state(d, d->is_wave_out?
+                               "ERROR writing pad byte to WAVE data chunk" :
+                               "ERROR writing pad byte to AIFF SSND chunk"
+                       );
+                       return false;
+               }
+       }
+
+       return true;
+}
+
+int DecoderSession_finish_ok(DecoderSession *d)
+{
+       FLAC__bool ok = true, md5_failure = false;
+
+#ifdef FLAC__HAS_OGG
+       if(d->is_ogg) {
+               if(d->decoder.ogg) {
+                       md5_failure = !OggFLAC__stream_decoder_finish(d->decoder.ogg) && !d->aborting_due_to_until;
+                       print_stats(d);
+                       OggFLAC__stream_decoder_delete(d->decoder.ogg);
                }
        }
        else
 #endif
        {
-               if(stream_info.decoder.file) {
-                       if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_UNINITIALIZED)
-                               md5_failure = !FLAC__file_decoder_finish(stream_info.decoder.file);
-                       print_stats(&stream_info);
-                       FLAC__file_decoder_delete(stream_info.decoder.file);
+               if(d->decoder.flac) {
+                       md5_failure = !FLAC__stream_decoder_finish(d->decoder.flac) && !d->aborting_due_to_until;
+                       print_stats(d);
+                       FLAC__stream_decoder_delete(d->decoder.flac);
                }
        }
-       if(0 != stream_info.fout && stream_info.fout != stdout)
-               fclose(stream_info.fout);
-#ifdef FLaC__HAS_OGG
-       if(stream_info.is_ogg) {
-               if(0 != stream_info.fin && stream_info.fin != stdin)
-                       fclose(stream_info.fin);
-       }
-#endif
-       if(analysis_mode)
-               flac__analyze_finish(aopts);
+       if(d->analysis_mode)
+               flac__analyze_finish(d->aopts);
        if(md5_failure) {
-               fprintf(stderr, "\r%s: WARNING, MD5 signature mismatch\n", stream_info.inbasefilename);
+               flac__utils_printf(stderr, 1, "\r%s: ERROR, MD5 signature mismatch\n", d->inbasefilename);
+               ok = d->continue_through_decode_errors;
+       }
+       else if(!d->got_stream_info) {
+               flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since there was no STREAMINFO\n", d->inbasefilename);
        }
        else {
-               if(stream_info.verbose)
-                       fprintf(stderr, "\r%s: %s         \n", stream_info.inbasefilename, stream_info.test_only? "ok           ":analysis_mode?"done           ":"done");
+               flac__utils_printf(stderr, 2, "\r%s: %s         \n", d->inbasefilename, d->test_only? "ok           ":d->analysis_mode?"done           ":"done");
        }
-       return 0;
-raw_abort_:
-#ifdef FLaC__HAS_OGG
-       if(stream_info.is_ogg) {
-               if(stream_info.decoder.stream) {
-                       if(FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_UNINITIALIZED)
-                               FLAC__stream_decoder_finish(stream_info.decoder.stream);
-                       FLAC__stream_decoder_delete(stream_info.decoder.stream);
+       DecoderSession_destroy(d, /*error_occurred=*/!ok);
+       if((d->is_wave_out || d->is_aiff_out) && (d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))))
+               if(!fixup_iff_headers(d))
+                       return 1;
+       return ok? 0 : 1;
+}
+
+int DecoderSession_finish_error(DecoderSession *d)
+{
+#ifdef FLAC__HAS_OGG
+       if(d->is_ogg) {
+               if(d->decoder.ogg) {
+                       OggFLAC__stream_decoder_finish(d->decoder.ogg);
+                       OggFLAC__stream_decoder_delete(d->decoder.ogg);
                }
        }
        else
 #endif
        {
-               if(stream_info.decoder.file) {
-                       if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_UNINITIALIZED)
-                               FLAC__file_decoder_finish(stream_info.decoder.file);
-                       FLAC__file_decoder_delete(stream_info.decoder.file);
+               if(d->decoder.flac) {
+                       FLAC__stream_decoder_finish(d->decoder.flac);
+                       FLAC__stream_decoder_delete(d->decoder.flac);
                }
        }
-       if(0 != stream_info.fout && stream_info.fout != stdout) {
-               fclose(stream_info.fout);
-               unlink(outfilename);
+       if(d->analysis_mode)
+               flac__analyze_finish(d->aopts);
+       DecoderSession_destroy(d, /*error_occurred=*/true);
+       return 1;
+}
+
+FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
+{
+       /* convert from mm:ss.sss to sample number if necessary */
+       flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
+
+       /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
+       if(spec->is_relative && spec->value.samples == 0) {
+               spec->is_relative = false;
+               return true;
        }
-#ifdef FLaC__HAS_OGG
-       if(stream_info.is_ogg) {
-               if(0 != stream_info.fin && stream_info.fin != stdin)
-                       fclose(stream_info.fin);
+
+       /* in any other case the total samples in the input must be known */
+       if(total_samples_in_input == 0) {
+               flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
+               return false;
        }
-#endif
-       if(analysis_mode)
-               flac__analyze_finish(aopts);
-       return 1;
+
+       FLAC__ASSERT(spec->value_is_samples);
+
+       /* convert relative specifications to absolute */
+       if(spec->is_relative) {
+               if(spec->value.samples <= 0)
+                       spec->value.samples += (FLAC__int64)total_samples_in_input;
+               else
+                       spec->value.samples += skip;
+               spec->is_relative = false;
+       }
+
+       /* error check */
+       if(spec->value.samples < 0) {
+               flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
+               return false;
+       }
+       if((FLAC__uint64)spec->value.samples <= skip) {
+               flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
+               return false;
+       }
+       if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
+               flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
+               return false;
+       }
+
+       return true;
 }
 
-FLAC__bool init(const char *infilename, stream_info_struct *stream_info)
+FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
 {
-       FLAC__uint32 test = 1;
+       const char *fmt_desc = decoder_session->is_wave_out? "WAVE" : "AIFF";
+       FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
+       const FLAC__uint32 aligned_data_size = (FLAC__uint32)((data_size+1) & (~1U)); /* we'll check for overflow later */
+       if(samples == 0) {
+               if(f == stdout) {
+                       flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
+                       flac__utils_printf(stderr, 1, "             Generated %s file will have a data chunk size of 0.  Try\n", fmt_desc);
+                       flac__utils_printf(stderr, 1, "             decoding directly to a file instead.\n");
+               }
+               else {
+                       decoder_session->iff_headers_need_fixup = true;
+               }
+       }
+       if(data_size >= 0xFFFFFFDC) {
+               flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file chunk\n", decoder_session->inbasefilename, fmt_desc);
+               return false;
+       }
+       if(decoder_session->is_wave_out) {
+               if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
+                       return false;
+
+               if(!write_little_endian_uint32(f, aligned_data_size+36)) /* filesize-8 */
+                       return false;
 
-       is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
+               if(flac__utils_fwrite("WAVEfmt ", 1, 8, f) != 8)
+                       return false;
 
-#ifdef FLaC__HAS_OGG
-       if(stream_info->is_ogg) {
-               stream_info->decoder.stream = FLAC__stream_decoder_new();
+               if(flac__utils_fwrite("\020\000\000\000", 1, 4, f) != 4) /* chunk size = 16 */
+                       return false;
 
-               if(0 == stream_info->decoder.stream) {
-                       fprintf(stderr, "%s: ERROR creating the decoder instance\n", stream_info->inbasefilename);
+               if(flac__utils_fwrite("\001\000", 1, 2, f) != 2) /* compression code == 1 */
                        return false;
-               }
 
-               FLAC__stream_decoder_set_read_callback(stream_info->decoder.stream, read_callback);
-               /*
-                * The three ugly casts here are to 'downcast' the 'void *' argument of
-                * the callback down to 'FLAC__StreamDecoder *'.  In C++ this would be
-                * unnecessary but here the cast makes the C compiler happy.
-                */
-               FLAC__stream_decoder_set_write_callback(stream_info->decoder.stream, (FLAC__StreamDecoderWriteStatus (*)(const FLAC__StreamDecoder *, const FLAC__Frame *, const FLAC__int32 *[], void *))write_callback);
-               FLAC__stream_decoder_set_metadata_callback(stream_info->decoder.stream, (void (*)(const FLAC__StreamDecoder *, const FLAC__StreamMetaData *, void *))metadata_callback);
-               FLAC__stream_decoder_set_error_callback(stream_info->decoder.stream, (void (*)(const FLAC__StreamDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
-               FLAC__stream_decoder_set_client_data(stream_info->decoder.stream, stream_info);
+               if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
+                       return false;
 
-               if(FLAC__stream_decoder_init(stream_info->decoder.stream) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
-                       fprintf(stderr, "%s: ERROR initializing decoder, state=%d:%s\n", stream_info->inbasefilename, FLAC__stream_decoder_get_state(stream_info->decoder.stream), FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(stream_info->decoder.stream)]);
+               if(!write_little_endian_uint32(f, decoder_session->sample_rate))
+                       return false;
+
+               if(!write_little_endian_uint32(f, decoder_session->sample_rate * decoder_session->channels * ((decoder_session->bps+7) / 8))) /* @@@ or is it (sample_rate*channels*bps) / 8 ??? */
+                       return false;
+
+               if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels * ((decoder_session->bps+7) / 8)))) /* block align */
+                       return false;
+
+               if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->bps))) /* bits per sample */
                        return false;
-               }
 
-               ogg_stream_init(&stream_info->ogg.os, 0);
-               ogg_sync_init(&stream_info->ogg.oy);
+               if(flac__utils_fwrite("data", 1, 4, f) != 4)
+                       return false;
+
+               if(!write_little_endian_uint32(f, (FLAC__uint32)data_size)) /* data size */
+                       return false;
        }
-       else
-#endif
-       {
-               stream_info->decoder.file = FLAC__file_decoder_new();
+       else {
+               if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
+                       return false;
 
-               if(0 == stream_info->decoder.file) {
-                       fprintf(stderr, "%s: ERROR creating the decoder instance\n", stream_info->inbasefilename);
+               if(!write_big_endian_uint32(f, aligned_data_size+46)) /* filesize-8 */
                        return false;
-               }
 
-               FLAC__file_decoder_set_md5_checking(stream_info->decoder.file, true);
-               FLAC__file_decoder_set_filename(stream_info->decoder.file, infilename);
-               /*
-                * The three ugly casts here are to 'downcast' the 'void *' argument of
-                * the callback down to 'FLAC__FileDecoder *'.  In C++ this would be
-                * unnecessary but here the cast makes the C compiler happy.
-                */
-               FLAC__file_decoder_set_write_callback(stream_info->decoder.file, (FLAC__StreamDecoderWriteStatus (*)(const FLAC__FileDecoder *, const FLAC__Frame *, const FLAC__int32 *[], void *))write_callback);
-               FLAC__file_decoder_set_metadata_callback(stream_info->decoder.file, (void (*)(const FLAC__FileDecoder *, const FLAC__StreamMetaData *, void *))metadata_callback);
-               FLAC__file_decoder_set_error_callback(stream_info->decoder.file, (void (*)(const FLAC__FileDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
-               FLAC__file_decoder_set_client_data(stream_info->decoder.file, stream_info);
+               if(flac__utils_fwrite("AIFFCOMM", 1, 8, f) != 8)
+                       return false;
 
-               if(FLAC__file_decoder_init(stream_info->decoder.file) != FLAC__FILE_DECODER_OK) {
-                       fprintf(stderr, "%s: ERROR initializing decoder, state=%d:%s\n", stream_info->inbasefilename, FLAC__file_decoder_get_state(stream_info->decoder.file), FLAC__FileDecoderStateString[FLAC__file_decoder_get_state(stream_info->decoder.file)]);
+               if(flac__utils_fwrite("\000\000\000\022", 1, 4, f) != 4) /* chunk size = 18 */
+                       return false;
+
+               if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
+                       return false;
+
+               if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
+                       return false;
+
+               if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->bps)))
+                       return false;
+
+               if(!write_sane_extended(f, decoder_session->sample_rate))
+                       return false;
+
+               if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
+                       return false;
+
+               if(!write_big_endian_uint32(f, (FLAC__uint32)data_size+8)) /* data size */
+                       return false;
+
+               if(!write_big_endian_uint32(f, 0/*offset*/))
+                       return false;
+
+               if(!write_big_endian_uint32(f, 0/*block_size*/))
                        return false;
-               }
        }
 
        return true;
@@ -539,269 +706,506 @@ FLAC__bool init(const char *infilename, stream_info_struct *stream_info)
 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
 {
        FLAC__byte *b = (FLAC__byte*)(&val);
-       if(is_big_endian_host) {
+       if(is_big_endian_host_) {
                FLAC__byte tmp;
                tmp = b[1]; b[1] = b[0]; b[0] = tmp;
        }
-       return fwrite(b, 1, 2, f) == 2;
+       return flac__utils_fwrite(b, 1, 2, f) == 2;
 }
 
 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
 {
        FLAC__byte *b = (FLAC__byte*)(&val);
-       if(is_big_endian_host) {
+       if(is_big_endian_host_) {
                FLAC__byte tmp;
                tmp = b[3]; b[3] = b[0]; b[0] = tmp;
                tmp = b[2]; b[2] = b[1]; b[1] = tmp;
        }
-       return fwrite(b, 1, 4, f) == 4;
+       return flac__utils_fwrite(b, 1, 4, f) == 4;
 }
 
-#ifdef FLaC__HAS_OGG
-#define OGG_READ_BUFFER_SIZE 4096
-FLAC__StreamDecoderReadStatus read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
+FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
 {
-       stream_info_struct *stream_info = (stream_info_struct *)client_data;
-       FILE *fin = stream_info->fin;
-       size_t bytes_read;
-       ogg_page og;
-       char *oggbuf;
-       unsigned int offset = 0;
-
-       *bytes = 0;
+       FLAC__byte *b = (FLAC__byte*)(&val);
+       if(!is_big_endian_host_) {
+               FLAC__byte tmp;
+               tmp = b[1]; b[1] = b[0]; b[0] = tmp;
+       }
+       return flac__utils_fwrite(b, 1, 2, f) == 2;
+}
 
-       if (stream_info->abort_flag)
-               return FLAC__STREAM_DECODER_READ_ABORT;
+FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
+{
+       FLAC__byte *b = (FLAC__byte*)(&val);
+       if(!is_big_endian_host_) {
+               FLAC__byte tmp;
+               tmp = b[3]; b[3] = b[0]; b[0] = tmp;
+               tmp = b[2]; b[2] = b[1]; b[1] = tmp;
+       }
+       return flac__utils_fwrite(b, 1, 4, f) == 4;
+}
 
-       oggbuf = ogg_sync_buffer(&stream_info->ogg.oy, OGG_READ_BUFFER_SIZE);
+FLAC__bool write_sane_extended(FILE *f, unsigned val)
+       /* Write to 'f' a SANE extended representation of 'val'.  Return false if
+       * the write succeeds; return true otherwise.
+       *
+       * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
+       * of exponent, and 64 bits of significand (mantissa).  Unlike most IEEE-754
+       * representations, it does not imply a 1 above the MSB of the significand.
+       *
+       * Preconditions:
+       *  val!=0U
+       */
+{
+       unsigned int shift, exponent;
 
-       (void)decoder; /* avoid compiler warning */
+       FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
 
-       if(feof(fin))
-               return FLAC__STREAM_DECODER_READ_END_OF_STREAM;
+       for(shift= 0U; (val>>(31-shift))==0U; ++shift)
+               ;
+       val<<= shift;
+       exponent= 63U-(shift+32U); /* add 32 for unused second word */
 
-       bytes_read = fread(oggbuf, 1, OGG_READ_BUFFER_SIZE, fin);
+       if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
+               return false;
+       if(!write_big_endian_uint32(f, val))
+               return false;
+       if(!write_big_endian_uint32(f, 0)) /* unused second word */
+               return false;
 
-       if(ferror(fin))
-               return FLAC__STREAM_DECODER_READ_ABORT;
+       return true;
+}
 
-       if(ogg_sync_wrote(&stream_info->ogg.oy, bytes_read) < 0)
-               return FLAC__STREAM_DECODER_READ_ABORT;
+FLAC__bool fixup_iff_headers(DecoderSession *d)
+{
+       const char *fmt_desc = (d->is_wave_out? "WAVE" : "AIFF");
+       FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
 
-       while(ogg_sync_pageout(&stream_info->ogg.oy, &og) == 1) {
-               if(ogg_stream_pagein(&stream_info->ogg.os, &og) == 0) {
-                       ogg_packet op;
+       if(0 == f) {
+               flac__utils_printf(stderr, 1, "ERROR, couldn't open file %s while fixing up %s chunk size: %s\n", d->outfilename, fmt_desc, strerror(errno));
+               return false;
+       }
 
-                       while(ogg_stream_packetout(&stream_info->ogg.os, &op) == 1) {
-                               memcpy(buffer + offset, op.packet, op.bytes);
-                               *bytes += op.bytes;
-                               offset += op.bytes;
-                       }
-               } else {
-                       return FLAC__STREAM_DECODER_READ_ABORT;
-               }
+       if(!write_iff_headers(f, d, d->samples_processed)) {
+               fclose(f);
+               return false;
        }
 
-       return FLAC__STREAM_DECODER_READ_CONTINUE;
+       fclose(f);
+       return true;
 }
-#endif
 
-FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
+FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
 {
-       stream_info_struct *stream_info = (stream_info_struct *)client_data;
-       FILE *fout = stream_info->fout;
-       unsigned bps = stream_info->bps, channels = stream_info->channels;
-       FLAC__bool is_big_endian = (stream_info->is_wave_out? false : stream_info->is_big_endian);
-       FLAC__bool is_unsigned_samples = (stream_info->is_wave_out? bps<=8 : stream_info->is_unsigned_samples);
+       DecoderSession *decoder_session = (DecoderSession*)client_data;
+       FILE *fout = decoder_session->fout;
+       const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
+       FLAC__bool is_big_endian = (decoder_session->is_aiff_out? true : (decoder_session->is_wave_out? false : decoder_session->is_big_endian));
+       FLAC__bool is_unsigned_samples = (decoder_session->is_aiff_out? false : (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples));
        unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
        static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
-       /* WATCHOUT: we say 'sizeof(FLAC__int32)' above instead of '(FLAC__MAX_BITS_PER_SAMPLE+7)/8' because we have to use an array FLAC__int32 even for 24 bps */
        FLAC__uint8  *u8buffer  = (FLAC__uint8  *)s8buffer;
        FLAC__int16  *s16buffer = (FLAC__int16  *)s8buffer;
        FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
        FLAC__int32  *s32buffer = (FLAC__int32  *)s8buffer;
        FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
+       size_t bytes_to_write = 0;
 
        (void)decoder;
 
-       if(stream_info->abort_flag)
-               return FLAC__STREAM_DECODER_WRITE_ABORT;
+       if(decoder_session->abort_flag)
+               return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
 
-       stream_info->samples_processed += wide_samples;
-       stream_info->frame_counter++;
+       /* sanity-check the bits-per-sample */
+       if(decoder_session->bps) {
+               if(bps != decoder_session->bps) {
+                       if(decoder_session->got_stream_info)
+                               flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, bps, decoder_session->bps);
+                       else
+                               flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, bps, decoder_session->bps);
+                       if(!decoder_session->continue_through_decode_errors)
+                               return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
+               }
+       }
+       else {
+               /* must not have gotten STREAMINFO, save the bps from the frame header */
+               FLAC__ASSERT(!decoder_session->got_stream_info);
+               decoder_session->bps = bps;
+       }
 
-       if(stream_info->verbose && !(stream_info->frame_counter & 0x7f))
-               print_stats(stream_info);
+       /* sanity-check the #channels */
+       if(decoder_session->channels) {
+               if(channels != decoder_session->channels) {
+                       if(decoder_session->got_stream_info)
+                               flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
+                       else
+                               flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, channels, decoder_session->channels);
+                       if(!decoder_session->continue_through_decode_errors)
+                               return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
+               }
+       }
+       else {
+               /* must not have gotten STREAMINFO, save the #channels from the frame header */
+               FLAC__ASSERT(!decoder_session->got_stream_info);
+               decoder_session->channels = channels;
+       }
 
-       if(stream_info->analysis_mode) {
-               flac__analyze_frame(frame, stream_info->frame_counter-1, stream_info->aopts, fout);
+       /* sanity-check the sample rate */
+       if(decoder_session->sample_rate) {
+               if(frame->header.sample_rate != decoder_session->sample_rate) {
+                       if(decoder_session->got_stream_info)
+                               flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
+                       else
+                               flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
+                       if(!decoder_session->continue_through_decode_errors)
+                               return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
+               }
        }
-       else if(!stream_info->test_only) {
-               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++)
-                                               u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
-                       }
-                       else {
-                               for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
-                                       for(channel = 0; channel < channels; channel++, sample++)
-                                               s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
-                       }
-                       if(fwrite(u8buffer, 1, sample, fout) != sample)
-                               return FLAC__STREAM_DECODER_WRITE_ABORT;
-               }
-               else if(bps == 16) {
-                       if(is_unsigned_samples) {
-                               for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
-                                       for(channel = 0; channel < channels; channel++, sample++)
-                                               u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
-                       }
-                       else {
-                               for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
-                                       for(channel = 0; channel < channels; channel++, sample++)
-                                               s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
+       else {
+               /* must not have gotten STREAMINFO, save the sample rate from the frame header */
+               FLAC__ASSERT(!decoder_session->got_stream_info);
+               decoder_session->sample_rate = frame->header.sample_rate;
+       }
+
+       /*
+        * limit the number of samples to accept based on --until
+        */
+       FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
+       /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
+       if(decoder_session->skip_specification->is_relative) {
+               if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
+                       decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
+               else {
+                       flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --skip because the total sample count was not found in the metadata\n", decoder_session->inbasefilename);
+                       return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
+               }
+       }
+       if(decoder_session->until_specification->is_relative) {
+               if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
+                       decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
+               else {
+                       flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until because the total sample count was not found in the metadata\n", decoder_session->inbasefilename);
+                       return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
+               }
+       }
+       FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
+       FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
+       if(decoder_session->until_specification->value.samples > 0) {
+               const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
+               const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
+               const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
+               FLAC__ASSERT(until >= input_samples_passed);
+               if(input_samples_passed + wide_samples > until)
+                       wide_samples = (unsigned)(until - input_samples_passed);
+               if (wide_samples == 0) {
+                       decoder_session->abort_flag = true;
+                       decoder_session->aborting_due_to_until = true;
+                       return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
+               }
+       }
+
+       if(wide_samples > 0) {
+               decoder_session->samples_processed += wide_samples;
+               decoder_session->frame_counter++;
+
+               if(!(decoder_session->frame_counter & 0x3f))
+                       print_stats(decoder_session);
+
+               if(decoder_session->analysis_mode) {
+                       flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->aopts, fout);
+               }
+               else if(!decoder_session->test_only) {
+                       if (decoder_session->replaygain.apply) {
+                               bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
+                                       u8buffer,
+                                       !is_big_endian,
+                                       is_unsigned_samples,
+                                       buffer,
+                                       wide_samples,
+                                       channels,
+                                       bps, /* source_bps */
+                                       bps, /* target_bps */
+                                       decoder_session->replaygain.scale,
+                                       decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
+                                       decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
+                                       &decoder_session->replaygain.dither_context
+                               );
                        }
-                       if(is_big_endian != is_big_endian_host) {
-                               unsigned char tmp;
-                               const unsigned bytes = sample * 2;
-                               for(byte = 0; byte < bytes; byte += 2) {
-                                       tmp = u8buffer[byte];
-                                       u8buffer[byte] = u8buffer[byte+1];
-                                       u8buffer[byte+1] = tmp;
+                       else 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++)
+                                                       u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
                                }
+                               else {
+                                       for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
+                                               for(channel = 0; channel < channels; channel++, sample++)
+                                                       s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
+                               }
+                               bytes_to_write = sample;
                        }
-                       if(fwrite(u16buffer, 2, sample, fout) != sample)
-                               return FLAC__STREAM_DECODER_WRITE_ABORT;
-               }
-               else if(bps == 24) {
-                       if(is_unsigned_samples) {
-                               for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
-                                       for(channel = 0; channel < channels; channel++, sample++)
-                                               u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
-                       }
-                       else {
-                               for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
-                                       for(channel = 0; channel < channels; channel++, sample++)
-                                               s32buffer[sample] = buffer[channel][wide_sample];
-                       }
-                       if(is_big_endian != is_big_endian_host) {
-                               unsigned char tmp;
-                               const unsigned bytes = sample * 4;
-                               for(byte = 0; byte < bytes; byte += 4) {
-                                       tmp = u8buffer[byte];
-                                       u8buffer[byte] = u8buffer[byte+3];
-                                       u8buffer[byte+3] = tmp;
-                                       tmp = u8buffer[byte+1];
-                                       u8buffer[byte+1] = u8buffer[byte+2];
-                                       u8buffer[byte+2] = tmp;
+                       else if(bps == 16) {
+                               if(is_unsigned_samples) {
+                                       for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
+                                               for(channel = 0; channel < channels; channel++, sample++)
+                                                       u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
                                }
+                               else {
+                                       for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
+                                               for(channel = 0; channel < channels; channel++, sample++)
+                                                       s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
+                               }
+                               if(is_big_endian != is_big_endian_host_) {
+                                       unsigned char tmp;
+                                       const unsigned bytes = sample * 2;
+                                       for(byte = 0; byte < bytes; byte += 2) {
+                                               tmp = u8buffer[byte];
+                                               u8buffer[byte] = u8buffer[byte+1];
+                                               u8buffer[byte+1] = tmp;
+                                       }
+                               }
+                               bytes_to_write = 2 * sample;
                        }
-                       if(is_big_endian) {
-                               unsigned lbyte;
-                               const unsigned bytes = sample * 4;
-                               for(lbyte = byte = 0; byte < bytes; ) {
-                                       byte++;
-                                       u8buffer[lbyte++] = u8buffer[byte++];
-                                       u8buffer[lbyte++] = u8buffer[byte++];
-                                       u8buffer[lbyte++] = u8buffer[byte++];
+                       else if(bps == 24) {
+                               if(is_unsigned_samples) {
+                                       for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
+                                               for(channel = 0; channel < channels; channel++, sample++)
+                                                       u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
+                               }
+                               else {
+                                       for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
+                                               for(channel = 0; channel < channels; channel++, sample++)
+                                                       s32buffer[sample] = buffer[channel][wide_sample];
                                }
+                               if(is_big_endian != is_big_endian_host_) {
+                                       unsigned char tmp;
+                                       const unsigned bytes = sample * 4;
+                                       for(byte = 0; byte < bytes; byte += 4) {
+                                               tmp = u8buffer[byte];
+                                               u8buffer[byte] = u8buffer[byte+3];
+                                               u8buffer[byte+3] = tmp;
+                                               tmp = u8buffer[byte+1];
+                                               u8buffer[byte+1] = u8buffer[byte+2];
+                                               u8buffer[byte+2] = tmp;
+                                       }
+                               }
+                               if(is_big_endian) {
+                                       unsigned lbyte;
+                                       const unsigned bytes = sample * 4;
+                                       for(lbyte = byte = 0; byte < bytes; ) {
+                                               byte++;
+                                               u8buffer[lbyte++] = u8buffer[byte++];
+                                               u8buffer[lbyte++] = u8buffer[byte++];
+                                               u8buffer[lbyte++] = u8buffer[byte++];
+                                       }
+                               }
+                               else {
+                                       unsigned lbyte;
+                                       const unsigned bytes = sample * 4;
+                                       for(lbyte = byte = 0; byte < bytes; ) {
+                                               u8buffer[lbyte++] = u8buffer[byte++];
+                                               u8buffer[lbyte++] = u8buffer[byte++];
+                                               u8buffer[lbyte++] = u8buffer[byte++];
+                                               byte++;
+                                       }
+                               }
+                               bytes_to_write = 3 * sample;
                        }
                        else {
-                               unsigned lbyte;
-                               const unsigned bytes = sample * 4;
-                               for(lbyte = byte = 0; byte < bytes; ) {
-                                       u8buffer[lbyte++] = u8buffer[byte++];
-                                       u8buffer[lbyte++] = u8buffer[byte++];
-                                       u8buffer[lbyte++] = u8buffer[byte++];
-                                       byte++;
-                               }
+                               FLAC__ASSERT(0);
                        }
-                       if(fwrite(u8buffer, 3, sample, fout) != sample)
-                               return FLAC__STREAM_DECODER_WRITE_ABORT;
                }
-               else {
-                       FLAC__ASSERT(0);
+       }
+       if(bytes_to_write > 0) {
+               if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
+                       /* if a pipe closed when writing to stdout, we let it go without an error message */
+                       if(errno == EPIPE && decoder_session->fout == stdout)
+                               decoder_session->aborting_due_to_until = true;
+                       decoder_session->abort_flag = true;
+                       return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
                }
        }
-       return FLAC__STREAM_DECODER_WRITE_CONTINUE;
+       return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
 }
 
-void metadata_callback(const void *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
+void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
 {
-       stream_info_struct *stream_info = (stream_info_struct *)client_data;
+       DecoderSession *decoder_session = (DecoderSession*)client_data;
        (void)decoder;
        if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
+               FLAC__uint64 skip, until;
+               decoder_session->got_stream_info = true;
+               decoder_session->bps = metadata->data.stream_info.bits_per_sample;
+               decoder_session->channels = metadata->data.stream_info.channels;
+               decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
+
+               flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
+               FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
+               skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
+
                /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
-               if(metadata->data.stream_info.total_samples > 0 && stream_info->skip >= metadata->data.stream_info.total_samples) {
-                       stream_info->total_samples = 0;
-                       stream_info->skip_count_too_high = true;
+               if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
+                       flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
+                       decoder_session->abort_flag = true;
+                       return;
                }
-               else
-                       stream_info->total_samples = metadata->data.stream_info.total_samples - stream_info->skip;
-               stream_info->bps = metadata->data.stream_info.bits_per_sample;
-               stream_info->channels = metadata->data.stream_info.channels;
-               stream_info->sample_rate = metadata->data.stream_info.sample_rate;
-
-               if(stream_info->bps != 8 && stream_info->bps != 16 && stream_info->bps != 24) {
-                       fprintf(stderr, "%s: ERROR: bits per sample is not 8/16/24\n", stream_info->inbasefilename);
-                       stream_info->abort_flag = true;
+               else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
+                       flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
+                       decoder_session->abort_flag = true;
+                       return;
+               }
+               FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
+               decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
+
+               /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
+               if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
+                       decoder_session->abort_flag = true;
+                       return;
+               }
+               FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
+               until = (FLAC__uint64)decoder_session->until_specification->value.samples;
+
+               if(until > 0) {
+                       FLAC__ASSERT(decoder_session->total_samples != 0);
+                       FLAC__ASSERT(0 == decoder_session->cue_specification);
+                       decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
+               }
+
+               if(decoder_session->bps != 8 && decoder_session->bps != 16 && decoder_session->bps != 24) {
+                       flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is not 8/16/24\n", decoder_session->inbasefilename);
+                       decoder_session->abort_flag = true;
+                       return;
+               }
+       }
+       else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
+               /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
+               if(decoder_session->total_samples == 0) {
+                       flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
+                       decoder_session->abort_flag = true;
                        return;
                }
 
-               /* write the WAVE headers if necessary */
-               if(!stream_info->analysis_mode && !stream_info->test_only && stream_info->is_wave_out) {
-                       FLAC__uint64 data_size = stream_info->total_samples * stream_info->channels * ((stream_info->bps+7)/8);
-                       if(data_size >= 0xFFFFFFDC) {
-                               fprintf(stderr, "%s: ERROR: stream is too big to fit in a single WAVE file chunk\n", stream_info->inbasefilename);
-                               stream_info->abort_flag = true;
-                               return;
+               flac__utils_canonicalize_cue_specification(decoder_session->cue_specification, &metadata->data.cue_sheet, decoder_session->total_samples, decoder_session->skip_specification, decoder_session->until_specification);
+
+               FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
+               FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
+
+               FLAC__ASSERT(!decoder_session->until_specification->is_relative);
+               FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
+
+               FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
+               FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
+               FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
+               FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
+
+               decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
+       }
+       else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
+               if (decoder_session->replaygain.spec.apply) {
+                       double reference, gain, peak;
+                       if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
+                               flac__utils_printf(stderr, 1, "%s: WARNING: can't get %s (or even %s) ReplayGain tags\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", decoder_session->replaygain.spec.use_album_gain? "track":"album");
+                       }
+                       else {
+                               const char *ls[] = { "no", "peak", "hard" };
+                               const char *ns[] = { "no", "low", "medium", "high" };
+                               decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
+                               FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
+                               FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
+                               flac__utils_printf(stderr, 1, "%s: INFO: applying %s ReplayGain (gain=%0.2fdB+preamp=%0.1fdB, %s noise shaping, %s limiting) to output\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", gain, decoder_session->replaygain.spec.preamp, ns[decoder_session->replaygain.spec.noise_shaping], ls[decoder_session->replaygain.spec.limiter]);
+                               flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
                        }
-                       if(fwrite("RIFF", 1, 4, stream_info->fout) != 4) stream_info->abort_flag = true;
-                       if(!write_little_endian_uint32(stream_info->fout, (FLAC__uint32)(data_size+36))) stream_info->abort_flag = true; /* filesize-8 */
-                       if(fwrite("WAVEfmt ", 1, 8, stream_info->fout) != 8) stream_info->abort_flag = true;
-                       if(fwrite("\020\000\000\000", 1, 4, stream_info->fout) != 4) stream_info->abort_flag = true; /* chunk size = 16 */
-                       if(fwrite("\001\000", 1, 2, stream_info->fout) != 2) stream_info->abort_flag = true; /* compression code == 1 */
-                       if(!write_little_endian_uint16(stream_info->fout, (FLAC__uint16)(stream_info->channels))) stream_info->abort_flag = true;
-                       if(!write_little_endian_uint32(stream_info->fout, stream_info->sample_rate)) stream_info->abort_flag = true;
-                       if(!write_little_endian_uint32(stream_info->fout, stream_info->sample_rate * stream_info->channels * ((stream_info->bps+7) / 8))) stream_info->abort_flag = true; /* @@@ or is it (sample_rate*channels*bps) / 8 ??? */
-                       if(!write_little_endian_uint16(stream_info->fout, (FLAC__uint16)(stream_info->channels * ((stream_info->bps+7) / 8)))) stream_info->abort_flag = true; /* block align */
-                       if(!write_little_endian_uint16(stream_info->fout, (FLAC__uint16)(stream_info->bps))) stream_info->abort_flag = true; /* bits per sample */
-                       if(fwrite("data", 1, 4, stream_info->fout) != 4) stream_info->abort_flag = true;
-                       if(!write_little_endian_uint32(stream_info->fout, (FLAC__uint32)data_size)) stream_info->abort_flag = true; /* data size */
                }
        }
 }
 
-void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
+void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
 {
-       stream_info_struct *stream_info = (stream_info_struct *)client_data;
+       DecoderSession *decoder_session = (DecoderSession*)client_data;
        (void)decoder;
-       fprintf(stderr, "%s: *** Got error code %d:%s\n", stream_info->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
-       stream_info->abort_flag = true;
+       flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
+       if(!decoder_session->continue_through_decode_errors) {
+               decoder_session->abort_flag = true;
+               if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
+                       decoder_session->aborting_due_to_unparseable = true;
+       }
+}
+
+void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
+{
+       const int ilen = strlen(d->inbasefilename) + 1;
+
+       flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
+
+       flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
+
+       /* print out some more info for some errors: */
+       if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
+               flac__utils_printf(stderr, 1,
+                       "\n"
+                       "An error occurred opening the input file; it is likely that it does not exist\n"
+                       "or is not readable.\n"
+               );
+       }
+}
+
+void print_error_with_state(const DecoderSession *d, const char *message)
+{
+       const int ilen = strlen(d->inbasefilename) + 1;
+       const char *state_string;
+
+       flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
+
+#ifdef FLAC__HAS_OGG
+       if(d->is_ogg) {
+               state_string = OggFLAC__stream_decoder_get_resolved_state_string(d->decoder.ogg);
+       }
+       else
+#endif
+       {
+               state_string = FLAC__stream_decoder_get_resolved_state_string(d->decoder.flac);
+       }
+
+       flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
+
+       /* print out some more info for some errors: */
+       if (d->aborting_due_to_unparseable) {
+               flac__utils_printf(stderr, 1,
+                       "\n"
+                       "The FLAC stream may have been created by a more advanced encoder.  Try\n"
+                       "  metaflac --show-vendor-tag %s\n"
+                       "If the version number is greater than %s, this decoder is probably\n"
+                       "not able to decode the file.  If the version number is not, the file\n"
+                       "may be corrupted, or you may have found a bug.  In this case please\n"
+                       "submit a bug report to\n"
+                       "    http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
+                       "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
+                       d->inbasefilename, FLAC__VERSION_STRING
+               );
+       }
 }
 
-void print_stats(const stream_info_struct *stream_info)
+void print_stats(const DecoderSession *decoder_session)
 {
-       if(stream_info->verbose) {
-#ifdef _MSC_VER
-               /* with VC++ you have to spoon feed it the casting */
-               const double progress = (double)(FLAC__int64)stream_info->samples_processed / (double)(FLAC__int64)stream_info->total_samples * 100.0;
+       if(flac__utils_verbosity_ >= 2) {
+#if defined _MSC_VER || defined __MINGW32__
+               /* with MSVC you have to spoon feed it the casting */
+               const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
 #else
-               const double progress = (double)stream_info->samples_processed / (double)stream_info->total_samples * 100.0;
+               const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
 #endif
-               if(stream_info->total_samples > 0) {
+               if(decoder_session->total_samples > 0) {
                        fprintf(stderr, "\r%s: %s%u%% complete",
-                               stream_info->inbasefilename,
-                               stream_info->test_only? "testing, " : stream_info->analysis_mode? "analyzing, " : "",
+                               decoder_session->inbasefilename,
+                               decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
                                (unsigned)floor(progress + 0.5)
                        );
                }
                else {
                        fprintf(stderr, "\r%s: %s %u samples",
-                               stream_info->inbasefilename,
-                               stream_info->test_only? "tested" : stream_info->analysis_mode? "analyzed" : "wrote",
-                               (unsigned)stream_info->samples_processed
+                               decoder_session->inbasefilename,
+                               decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
+                               (unsigned)decoder_session->samples_processed
                        );
                }
        }