dc7cbe09091e7450f26875fa155c7ecfe1a5c2e6
[flac.git] / src / flac / encode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000-2009  Josh Coalson
3  * Copyright (C) 2011-2013  Xiph.Org Foundation
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include <config.h>
22 #endif
23
24 #include <errno.h>
25 #include <limits.h> /* for LONG_MAX */
26 #include <math.h> /* for floor() */
27 #include <stdio.h> /* for FILE etc. */
28 #include <stdlib.h> /* for malloc */
29 #include <string.h> /* for strcmp(), strerror() */
30 #include <sys/stat.h>
31 #include "FLAC/all.h"
32 #include "share/alloc.h"
33 #include "share/grabbag.h"
34 #include "share/compat.h"
35 #include "share/private.h"
36 #include "share/safe_str.h"
37 #include "encode.h"
38
39 #ifdef min
40 #undef min
41 #endif
42 #define min(x,y) ((x)<(y)?(x):(y))
43 #ifdef max
44 #undef max
45 #endif
46 #define max(x,y) ((x)>(y)?(x):(y))
47
48 /* this MUST be >= 588 so that sector aligning can take place with one read */
49 /* this MUST be < 2^sizeof(size_t) / ( FLAC__MAX_CHANNELS * (FLAC__MAX_BITS_PER_SAMPLE/8) ) */
50 #define CHUNK_OF_SAMPLES 2048
51
52 typedef struct {
53         unsigned sample_rate;
54         unsigned channels;
55         unsigned bits_per_sample; /* width of sample point, including 'shift' bits, valid bps is bits_per_sample-shift */
56         unsigned shift; /* # of LSBs samples have been shifted left by */
57         unsigned bytes_per_wide_sample; /* for convenience, always == channels*((bps+7)/8), or 0 if N/A to input format (like FLAC) */
58         FLAC__bool is_unsigned_samples;
59         FLAC__bool is_big_endian;
60         FLAC__uint32 channel_mask;
61 } SampleInfo;
62
63 /* this is the client_data attached to the FLAC decoder when encoding from a FLAC file */
64 typedef struct {
65         FLAC__off_t filesize;
66         const FLAC__byte *lookahead;
67         unsigned lookahead_length;
68         size_t num_metadata_blocks;
69         FLAC__StreamMetadata *metadata_blocks[1024]; /*@@@ BAD MAGIC number */
70         FLAC__uint64 samples_left_to_process;
71         FLAC__bool fatal_error;
72 } FLACDecoderData;
73
74 typedef struct {
75 #if FLAC__HAS_OGG
76         FLAC__bool use_ogg;
77 #endif
78         FLAC__bool verify;
79         FLAC__bool is_stdout;
80         FLAC__bool outputfile_opened; /* true if we successfully opened the output file and we want it to be deleted if there is an error */
81         const char *inbasefilename;
82         const char *infilename;
83         const char *outfilename;
84
85         FLAC__bool treat_warnings_as_errors;
86         FLAC__bool continue_through_decode_errors;
87         FLAC__bool replay_gain;
88         FLAC__uint64 total_samples_to_encode; /* (i.e. "wide samples" aka "sample frames") WATCHOUT: may be 0 to mean 'unknown' */
89         FLAC__uint64 unencoded_size; /* an estimate of the input size, only used in the progress indicator */
90         FLAC__uint64 bytes_written;
91         FLAC__uint64 samples_written;
92         unsigned stats_mask;
93
94         SampleInfo info;
95
96         FileFormat format;
97         union {
98                 struct {
99                         FLAC__uint64 data_bytes;
100                 } iff;
101                 struct {
102                         FLAC__StreamDecoder *decoder;
103                         FLACDecoderData client_data;
104                 } flac;
105         } fmt;
106
107         FLAC__StreamEncoder *encoder;
108
109         FILE *fin;
110         FLAC__StreamMetadata *seek_table_template;
111         double progress, compression_ratio;
112 } EncoderSession;
113
114 const int FLAC_ENCODE__DEFAULT_PADDING = 8192;
115
116 static FLAC__bool is_big_endian_host_;
117
118 static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
119 static signed char *scbuffer_ = (signed char *)ucbuffer_;
120 static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_;
121 static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_;
122
123 static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
124 static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
125
126
127 /*
128  * local routines
129  */
130 static FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, FLAC__off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length);
131 static void EncoderSession_destroy(EncoderSession *e);
132 static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero, foreign_metadata_t *foreign_metadata, FLAC__bool error_on_compression_fail);
133 static int EncoderSession_finish_error(EncoderSession *e);
134 static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options);
135 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
136 static FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e);
137 static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
138 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
139 static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata);
140 static FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift, size_t *channel_map);
141 static void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
142 static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
143 static FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
144 static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
145 static FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
146 static FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data);
147 static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
148 static void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
149 static void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
150 static FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, unsigned sample_rate, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors);
151 static void print_stats(const EncoderSession *encoder_session);
152 static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
153 static void print_error_with_state(const EncoderSession *e, const char *message);
154 static void print_verify_error(EncoderSession *e);
155 static FLAC__bool read_bytes(FILE *f, FLAC__byte *buf, size_t n, FLAC__bool eof_ok, const char *fn);
156 static FLAC__bool read_uint16(FILE *f, FLAC__bool big_endian, FLAC__uint16 *val, const char *fn);
157 static FLAC__bool read_uint32(FILE *f, FLAC__bool big_endian, FLAC__uint32 *val, const char *fn);
158 static FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn);
159 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn);
160 static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
161 static unsigned count_channel_mask_bits(FLAC__uint32 mask);
162 #if 0
163 static FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels);
164 #endif
165
166 static FLAC__bool get_sample_info_raw(EncoderSession *e, encode_options_t options)
167 {
168         e->info.sample_rate = options.format_options.raw.sample_rate;
169         e->info.channels = options.format_options.raw.channels;
170         e->info.bits_per_sample = options.format_options.raw.bps;
171         e->info.shift = 0;
172         e->info.bytes_per_wide_sample = options.format_options.raw.channels * ((options.format_options.raw.bps+7)/8);
173         e->info.is_unsigned_samples = options.format_options.raw.is_unsigned_samples;
174         e->info.is_big_endian = options.format_options.raw.is_big_endian;
175         e->info.channel_mask = 0;
176
177         return true;
178 }
179
180 static FLAC__bool get_sample_info_wave(EncoderSession *e, encode_options_t options)
181 {
182         FLAC__bool got_fmt_chunk = false, got_data_chunk = false, got_ds64_chunk = false;
183         unsigned sample_rate = 0, channels = 0, bps = 0, shift = 0;
184         FLAC__uint32 channel_mask = 0;
185         FLAC__uint64 ds64_data_size = 0;
186
187         e->info.is_unsigned_samples = false;
188         e->info.is_big_endian = false;
189
190         if(e->format == FORMAT_WAVE64) {
191                 /*
192                  * lookahead[] already has "riff\x2E\x91\xCF\x11\xA5\xD6\x28\xDB", skip over remaining header
193                  */
194                 if(!fskip_ahead(e->fin, 16+8+16-12)) { /* riff GUID + riff size + WAVE GUID - lookahead */
195                         flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over remaining \"riff\" header\n", e->inbasefilename);
196                         return false;
197                 }
198         }
199         /* else lookahead[] already has "RIFFxxxxWAVE" or "RF64xxxxWAVE" */
200
201         while(!feof(e->fin) && !got_data_chunk) {
202                 /* chunk IDs are 4 bytes for WAVE/RF64, 16 for Wave64 */
203                 /* for WAVE/RF64 we want the 5th char zeroed so we can treat it like a C string */
204                 char chunk_id[16] = { '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' };
205
206                 if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, e->format==FORMAT_WAVE64?16:4, /*eof_ok=*/true, e->inbasefilename)) {
207                         flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename);
208                         return false;
209                 }
210                 if(feof(e->fin))
211                         break;
212
213                 if(e->format == FORMAT_RF64 && !memcmp(chunk_id, "ds64", 4)) { /* RF64 64-bit sizes chunk */
214                         FLAC__uint32 xx, data_bytes;
215
216                         if(got_ds64_chunk) {
217                                 flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'ds64' chunks\n", e->inbasefilename);
218                                 return false;
219                         }
220                         if(got_fmt_chunk || got_data_chunk) {
221                                 flac__utils_printf(stderr, 1, "%s: ERROR: 'ds64' chunk appears after 'fmt ' or 'data' chunk\n", e->inbasefilename);
222                                 return false;
223                         }
224
225                         /* ds64 chunk size */
226                         if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
227                                 return false;
228                         data_bytes = xx;
229                         if(data_bytes < 28) {
230                                 flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'ds64' chunk has length = %u\n", e->inbasefilename, (unsigned)data_bytes);
231                                 return false;
232                         }
233                         if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */
234                                 data_bytes++;
235
236                         /* RIFF 64-bit size, lo/hi */
237                         if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
238                                 return false;
239                         if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
240                                 return false;
241
242                         /* 'data' 64-bit size */
243                         if(!read_uint64(e->fin, /*big_endian=*/false, &ds64_data_size, e->inbasefilename))
244                                 return false;
245
246                         data_bytes -= 16;
247
248                         /* skip any extra data in the ds64 chunk */
249                         if(!fskip_ahead(e->fin, data_bytes)) {
250                                 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'ds64' data\n", e->inbasefilename);
251                                 return false;
252                         }
253
254                         got_ds64_chunk = true;
255                 }
256                 else if(
257                         !memcmp(chunk_id, "fmt ", 4) &&
258                         (e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "fmt \xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 16))
259                 ) { /* format chunk */
260                         FLAC__uint16 x;
261                         FLAC__uint32 xx, data_bytes;
262                         FLAC__uint16 wFormatTag; /* wFormatTag word from the 'fmt ' chunk */
263
264                         if(got_fmt_chunk) {
265                                 flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'fmt ' chunks\n", e->inbasefilename);
266                                 return false;
267                         }
268
269                         /* see
270                          *   http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
271                          *   http://windowssdk.msdn.microsoft.com/en-us/library/ms713497.aspx
272                          *   http://msdn.microsoft.com/library/default.asp?url=/library/en-us/audio_r/hh/Audio_r/aud-prop_d40f094e-44f9-4baa-8a15-03e4fb369501.xml.asp
273                          *
274                          * WAVEFORMAT is
275                          * 4 byte: chunk size
276                          * 2 byte: format type: 1 for WAVE_FORMAT_PCM, 65534 for WAVE_FORMAT_EXTENSIBLE
277                          * 2 byte: # channels
278                          * 4 byte: sample rate (Hz)
279                          * 4 byte: avg bytes per sec
280                          * 2 byte: block align
281                          * 2 byte: bits per sample (not necessarily all significant)
282                          * WAVEFORMATEX adds
283                          * 2 byte: extension size in bytes (usually 0 for WAVEFORMATEX and 22 for WAVEFORMATEXTENSIBLE with PCM)
284                          * WAVEFORMATEXTENSIBLE adds
285                          * 2 byte: valid bits per sample
286                          * 4 byte: channel mask
287                          * 16 byte: subformat GUID, first 2 bytes have format type, 1 being PCM
288                          *
289                          * Current spec says WAVEFORMATEX with PCM must have bps == 8 or 16, or any multiple of 8 for WAVEFORMATEXTENSIBLE.
290                          * Lots of old broken WAVEs/apps have don't follow it, e.g. 20 bps but a block align of 3/6 for mono/stereo.
291                          *
292                          * Block align for WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE is also supposed to be channels*bps/8
293                          *
294                          * If the channel mask has more set bits than # of channels, the extra MSBs are ignored.
295                          * If the channel mask has less set bits than # of channels, the extra channels are unassigned to any speaker.
296                          *
297                          * Data is supposed to be unsigned for bps <= 8 else signed.
298                          */
299
300                         /* fmt chunk size */
301                         if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
302                                 return false;
303                         data_bytes = xx;
304                         if(e->format == FORMAT_WAVE64) {
305                                 /* other half of the size field should be 0 */
306                                 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
307                                         return false;
308                                 if(xx) {
309                                         flac__utils_printf(stderr, 1, "%s: ERROR: freakishly large Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (unsigned)xx, (unsigned)data_bytes);
310                                         return false;
311                                 }
312                                 /* subtract size of header */
313                                 if (data_bytes < 16+8) {
314                                         flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (unsigned)xx, (unsigned)data_bytes);
315                                         return false;
316                                 }
317                                 data_bytes -= (16+8);
318                         }
319                         if(data_bytes < 16) {
320                                 flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'fmt ' chunk has length = %u\n", e->inbasefilename, (unsigned)data_bytes);
321                                 return false;
322                         }
323                         if(e->format != FORMAT_WAVE64) {
324                                 if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */
325                                         data_bytes++;
326                         }
327                         else { /* Wave64 */
328                                 data_bytes = (data_bytes+7) & (~7u); /* should never happen, but enforce Wave64 alignment rules */
329                         }
330
331                         /* format code */
332                         if(!read_uint16(e->fin, /*big_endian=*/false, &wFormatTag, e->inbasefilename))
333                                 return false;
334                         if(wFormatTag != 1 /*WAVE_FORMAT_PCM*/ && wFormatTag != 65534 /*WAVE_FORMAT_EXTENSIBLE*/) {
335                                 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", e->inbasefilename, (unsigned)wFormatTag);
336                                 return false;
337                         }
338
339                         /* number of channels */
340                         if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
341                                 return false;
342                         channels = (unsigned)x;
343
344                         /* sample rate */
345                         if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
346                                 return false;
347                         sample_rate = xx;
348
349                         /* avg bytes per second (ignored) */
350                         if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
351                                 return false;
352                         /* block align */
353                         if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
354                                 return false;
355
356                         /* bits per sample */
357                         if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
358                                 return false;
359                         bps = (unsigned)x;
360
361                         e->info.is_unsigned_samples = (bps <= 8);
362
363                         if(wFormatTag == 1) {
364                                 if(bps != 8 && bps != 16) {
365                                         if(bps == 24 || bps == 32) {
366                                                 /* let these slide with a warning since they're unambiguous */
367                                                 flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (unsigned)wFormatTag, bps);
368                                                 if(e->treat_warnings_as_errors)
369                                                         return false;
370                                         }
371                                         else {
372                                                 /* @@@ we could add an option to specify left- or right-justified blocks so we knew how to set 'shift' */
373                                                 flac__utils_printf(stderr, 1, "%s: ERROR: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (unsigned)wFormatTag, bps);
374                                                 return false;
375                                         }
376                                 }
377 #if 0 /* @@@ reinstate once we can get an answer about whether the samples are left- or right-justified */
378                                 if((bps+7)/8 * channels == block_align) {
379                                         if(bps % 8) {
380                                                 /* assume legacy file is byte aligned with some LSBs zero; this is double-checked in format_input() */
381                                                 flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", e->inbasefilename, (unsigned)wFormatTag, block_align, bps, channels);
382                                                 if(e->treat_warnings_as_errors)
383                                                         return false;
384                                                 shift = 8 - (bps % 8);
385                                                 bps += shift;
386                                         }
387                                         else
388                                                 shift = 0;
389                                 }
390                                 else {
391                                         flac__utils_printf(stderr, 1, "%s: ERROR: illegal WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", e->inbasefilename, (unsigned)wFormatTag, block_align, bps, channels);
392                                         return false;
393                                 }
394 #else
395                                 shift = 0;
396 #endif
397                                 if(channels > 2 && !options.channel_map_none) {
398                                         flac__utils_printf(stderr, 1, "%s: ERROR: WAVE has >2 channels but is not WAVE_FORMAT_EXTENSIBLE; cannot assign channels\n", e->inbasefilename);
399                                         return false;
400                                 }
401                                 FLAC__ASSERT(data_bytes >= 16);
402                                 data_bytes -= 16;
403                         }
404                         else {
405                                 if(data_bytes < 40) {
406                                         flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with size %u\n", e->inbasefilename, (unsigned)data_bytes);
407                                         return false;
408                                 }
409                                 /* cbSize */
410                                 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
411                                         return false;
412                                 if(x < 22) {
413                                         flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with cbSize %u\n", e->inbasefilename, (unsigned)x);
414                                         return false;
415                                 }
416                                 /* valid bps */
417                                 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
418                                         return false;
419                                 if((unsigned)x > bps) {
420                                         flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", e->inbasefilename, (unsigned)x, bps);
421                                         return false;
422                                 }
423                                 shift = bps - (unsigned)x;
424                                 /* channel mask */
425                                 if(!read_uint32(e->fin, /*big_endian=*/false, &channel_mask, e->inbasefilename))
426                                         return false;
427                                 /* for mono/stereo and unassigned channels, we fake the mask */
428                                 if(channel_mask == 0) {
429                                         if(channels == 1)
430                                                 channel_mask = 0x0001;
431                                         else if(channels == 2)
432                                                 channel_mask = 0x0003;
433                                 }
434                                 /* set channel mapping */
435                                 /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
436                                 /* front left, front right, center, LFE, back left, back right, surround left, surround right */
437                                 /* the default mapping is sufficient for 1-6 channels and 7-8 are currently unspecified anyway */
438 #if 0
439                                 /* @@@ example for dolby/vorbis order, for reference later in case it becomes important */
440                                 if(
441                                         options.channel_map_none ||
442                                         channel_mask == 0x0001 || /* 1 channel: (mono) */
443                                         channel_mask == 0x0003 || /* 2 channels: front left, front right */
444                                         channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
445                                         channel_mask == 0x0603    /* 4 channels: front left, front right, side left, side right */
446                                 ) {
447                                         /* keep default channel order */
448                                 }
449                                 else if(
450                                         channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
451                                         channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
452                                         channel_mask == 0x0607    /* 5 channels: front left, front right, front center, side left, side right */
453                                 ) {
454                                         /* to dolby order: front left, center, front right [, surround left, surround right ] */
455                                         channel_map[1] = 2;
456                                         channel_map[2] = 1;
457                                 }
458                                 else if(
459                                         channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
460                                         channel_mask == 0x060f || /* 6 channels: front left, front right, front center, LFE, side left, side right */
461                                         channel_mask == 0x070f || /* 7 channels: front left, front right, front center, LFE, back center, side left, side right */
462                                         channel_mask == 0x063f    /* 8 channels: front left, front right, front center, LFE, back left, back right, side left, side right */
463                                 ) {
464                                         /* to dolby order: front left, center, front right, surround left, surround right, LFE */
465                                         channel_map[1] = 2;
466                                         channel_map[2] = 1;
467                                         channel_map[3] = 5;
468                                         channel_map[4] = 3;
469                                         channel_map[5] = 4;
470                                 }
471 #else
472                                 if(
473                                         options.channel_map_none ||
474                                         channel_mask == 0x0001 || /* 1 channel: (mono) */
475                                         channel_mask == 0x0003 || /* 2 channels: front left, front right */
476                                         channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
477                                         channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
478                                         channel_mask == 0x0603 || /* 4 channels: front left, front right, side left, side right */
479                                         channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
480                                         channel_mask == 0x0607 || /* 5 channels: front left, front right, front center, side left, side right */
481                                         channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
482                                         channel_mask == 0x060f || /* 6 channels: front left, front right, front center, LFE, side left, side right */
483                                         channel_mask == 0x070f || /* 7 channels: front left, front right, front center, LFE, back center, side left, side right */
484                                         channel_mask == 0x063f    /* 8 channels: front left, front right, front center, LFE, back left, back right, side left, side right */
485                                 ) {
486                                         /* keep default channel order */
487                                 }
488 #endif
489                                 else {
490                                         flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk with unsupported channel mask=0x%04X\n\nUse --channel-map=none option to store channels in current order; FLAC files\nmust also be decoded with --channel-map=none to restore correct order.\n", e->inbasefilename, (unsigned)channel_mask);
491                                         return false;
492                                 }
493                                 if(!options.channel_map_none) {
494                                         if(count_channel_mask_bits(channel_mask) < channels) {
495                                                 flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has unassigned channels (#channels=%u)\n", e->inbasefilename, (unsigned)channel_mask, channels);
496                                                 return false;
497                                         }
498 #if 0
499                                         /* supporting this is too difficult with channel mapping; e.g. what if mask is 0x003f but #channels=4?
500                                          * there would be holes in the order that would have to be filled in, or the mask would have to be
501                                          * limited and the logic above rerun to see if it still fits into the FLAC mapping.
502                                          */
503                                         else if(count_channel_mask_bits(channel_mask) > channels)
504                                                 channel_mask = limit_channel_mask(channel_mask, channels);
505 #else
506                                         else if(count_channel_mask_bits(channel_mask) > channels) {
507                                                 flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has extra bits for non-existant channels (#channels=%u)\n", e->inbasefilename, (unsigned)channel_mask, channels);
508                                                 return false;
509                                         }
510 #endif
511                                 }
512                                 /* first part of GUID */
513                                 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
514                                         return false;
515                                 if(x != 1) {
516                                         flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE chunk with non-PCM format %u\n", e->inbasefilename, (unsigned)x);
517                                         return false;
518                                 }
519                                 data_bytes -= 26;
520                         }
521
522                         e->info.bytes_per_wide_sample = channels * (bps / 8);
523
524                         /* skip any extra data in the fmt chunk */
525                         if(!fskip_ahead(e->fin, data_bytes)) {
526                                 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'fmt' data\n", e->inbasefilename);
527                                 return false;
528                         }
529
530                         got_fmt_chunk = true;
531                 }
532                 else if(
533                         !memcmp(chunk_id, "data", 4) &&
534                         (e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "data\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 16))
535                 ) { /* data chunk */
536                         FLAC__uint32 xx;
537                         FLAC__uint64 data_bytes;
538
539                         if(!got_fmt_chunk) {
540                                 flac__utils_printf(stderr, 1, "%s: ERROR: got 'data' chunk before 'fmt' chunk\n", e->inbasefilename);
541                                 return false;
542                         }
543
544                         /* data size */
545                         if(e->format != FORMAT_WAVE64) {
546                                 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
547                                         return false;
548                                 data_bytes = xx;
549                         }
550                         else { /* Wave64 */
551                                 if(!read_uint64(e->fin, /*big_endian=*/false, &data_bytes, e->inbasefilename))
552                                         return false;
553                                 /* subtract size of header */
554                                 if (data_bytes < 16+8) {
555                                         flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'data' chunk has length = 0x00000000%08X\n", e->inbasefilename, (unsigned)data_bytes);
556                                         return false;
557                                 }
558                                 data_bytes -= (16+8);
559                         }
560                         if(e->format == FORMAT_RF64) {
561                                 if(!got_ds64_chunk) {
562                                         flac__utils_printf(stderr, 1, "%s: ERROR: RF64 file has no 'ds64' chunk before 'data' chunk\n", e->inbasefilename);
563                                         return false;
564                                 }
565                                 if(data_bytes == 0xffffffff)
566                                         data_bytes = ds64_data_size;
567                         }
568                         if(options.ignore_chunk_sizes) {
569                                 FLAC__ASSERT(!options.sector_align);
570                                 if(data_bytes) {
571                                         flac__utils_printf(stderr, 1, "%s: WARNING: 'data' chunk has non-zero size, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id);
572                                         if(e->treat_warnings_as_errors)
573                                                 return false;
574                                 }
575                                 data_bytes = (FLAC__uint64)0 - (FLAC__uint64)e->info.bytes_per_wide_sample; /* max out data_bytes; we'll use EOF as signal to stop reading */
576                         }
577                         else if(0 == data_bytes) {
578                                 flac__utils_printf(stderr, 1, "%s: ERROR: 'data' chunk has size of 0\n", e->inbasefilename);
579                                 return false;
580                         }
581
582                         e->fmt.iff.data_bytes = data_bytes;
583
584                         got_data_chunk = true;
585                         break;
586                 }
587                 else {
588                         FLAC__uint32 xx;
589                         FLAC__uint64 skip;
590                         if(!options.format_options.iff.foreign_metadata) {
591                                 if(e->format != FORMAT_WAVE64)
592                                         flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id);
593                                 else
594                                         flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk %02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X (use --keep-foreign-metadata to keep)\n",
595                                                 e->inbasefilename,
596                                                 (unsigned)((const unsigned char *)chunk_id)[3],
597                                                 (unsigned)((const unsigned char *)chunk_id)[2],
598                                                 (unsigned)((const unsigned char *)chunk_id)[1],
599                                                 (unsigned)((const unsigned char *)chunk_id)[0],
600                                                 (unsigned)((const unsigned char *)chunk_id)[5],
601                                                 (unsigned)((const unsigned char *)chunk_id)[4],
602                                                 (unsigned)((const unsigned char *)chunk_id)[7],
603                                                 (unsigned)((const unsigned char *)chunk_id)[6],
604                                                 (unsigned)((const unsigned char *)chunk_id)[9],
605                                                 (unsigned)((const unsigned char *)chunk_id)[8],
606                                                 (unsigned)((const unsigned char *)chunk_id)[10],
607                                                 (unsigned)((const unsigned char *)chunk_id)[11],
608                                                 (unsigned)((const unsigned char *)chunk_id)[12],
609                                                 (unsigned)((const unsigned char *)chunk_id)[13],
610                                                 (unsigned)((const unsigned char *)chunk_id)[14],
611                                                 (unsigned)((const unsigned char *)chunk_id)[15]
612                                         );
613                                 if(e->treat_warnings_as_errors)
614                                         return false;
615                         }
616
617                         /* chunk size */
618                         if(e->format != FORMAT_WAVE64) {
619                                 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
620                                         return false;
621                                 skip = xx;
622                                 skip += skip & 1;
623                         }
624                         else { /* Wave64 */
625                                 if(!read_uint64(e->fin, /*big_endian=*/false, &skip, e->inbasefilename))
626                                         return false;
627                                 skip = (skip+7) & (~(FLAC__uint64)7);
628                                 /* subtract size of header */
629                                 if (skip < 16+8) {
630                                         flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 chunk has length = 0x00000000%08X\n", e->inbasefilename, (unsigned)skip);
631                                         return false;
632                                 }
633                                 skip -= (16+8);
634                         }
635                         if(skip) {
636                                 if(!fskip_ahead(e->fin, skip)) {
637                                         flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename);
638                                         return false;
639                                 }
640                         }
641                 }
642         }
643
644         if(!got_fmt_chunk) {
645                 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find fmt chunk\n", e->inbasefilename);
646                 return false;
647         }
648         if(!got_data_chunk) {
649                 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find data chunk\n", e->inbasefilename);
650                 return false;
651         }
652
653         e->info.sample_rate = sample_rate;
654         e->info.channels = channels;
655         e->info.bits_per_sample = bps;
656         e->info.shift = shift;
657         e->info.channel_mask = channel_mask;
658
659         return true;
660 }
661
662 static FLAC__bool get_sample_info_aiff(EncoderSession *e, encode_options_t options)
663 {
664         FLAC__bool got_comm_chunk = false, got_ssnd_chunk = false;
665         unsigned sample_rate = 0, channels = 0, bps = 0, shift = 0;
666         FLAC__uint64 sample_frames = 0;
667         FLAC__uint32 channel_mask = 0;
668
669         e->info.is_unsigned_samples = false;
670         e->info.is_big_endian = true;
671
672         /*
673          * lookahead[] already has "FORMxxxxAIFF", do chunks
674          */
675         while(!feof(e->fin) && !got_ssnd_chunk) {
676                 char chunk_id[5] = { '\0', '\0', '\0', '\0', '\0' }; /* one extra byte for terminating NUL so we can also treat it like a C string */
677                 if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, 4, /*eof_ok=*/true, e->inbasefilename)) {
678                         flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename);
679                         return false;
680                 }
681                 if(feof(e->fin))
682                         break;
683
684                 if(!memcmp(chunk_id, "COMM", 4)) { /* common chunk */
685                         FLAC__uint16 x;
686                         FLAC__uint32 xx;
687                         unsigned long skip;
688                         const FLAC__bool is_aifc = e->format == FORMAT_AIFF_C;
689                         const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18);
690
691                         if(got_comm_chunk) {
692                                 flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'COMM' chunks\n", e->inbasefilename);
693                                 return false;
694                         }
695
696                         /* COMM chunk size */
697                         if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
698                                 return false;
699                         else if(xx < minimum_comm_size) {
700                                 flac__utils_printf(stderr, 1, "%s: ERROR: non-standard %s 'COMM' chunk has length = %u\n", e->inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx);
701                                 return false;
702                         }
703                         else if(!is_aifc && xx != minimum_comm_size) {
704                                 flac__utils_printf(stderr, 1, "%s: WARNING: non-standard %s 'COMM' chunk has length = %u, expected %u\n", e->inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx, minimum_comm_size);
705                                 if(e->treat_warnings_as_errors)
706                                         return false;
707                         }
708                         skip = (xx-minimum_comm_size)+(xx & 1);
709
710                         /* number of channels */
711                         if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
712                                 return false;
713                         channels = (unsigned)x;
714                         if(channels > 2 && !options.channel_map_none) {
715                                 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
716                                 return false;
717                         }
718
719                         /* number of sample frames */
720                         if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
721                                 return false;
722                         sample_frames = xx;
723
724                         /* bits per sample */
725                         if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
726                                 return false;
727                         bps = (unsigned)x;
728                         shift = (bps%8)? 8-(bps%8) : 0; /* SSND data is always byte-aligned, left-justified but format_input() will double-check */
729                         bps += shift;
730
731                         /* sample rate */
732                         if(!read_sane_extended(e->fin, &xx, e->inbasefilename))
733                                 return false;
734                         sample_rate = xx;
735
736                         /* check compression type for AIFF-C */
737                         if(is_aifc) {
738                                 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
739                                         return false;
740                                 if(xx == 0x736F7774) /* "sowt" */
741                                         e->info.is_big_endian = false;
742                                 else if(xx == 0x4E4F4E45) /* "NONE" */
743                                         ; /* nothing to do, we already default to big-endian */
744                                 else {
745                                         flac__utils_printf(stderr, 1, "%s: ERROR: can't handle AIFF-C compression type \"%c%c%c%c\"\n", e->inbasefilename, (char)(xx>>24), (char)((xx>>16)&8), (char)((xx>>8)&8), (char)(xx&8));
746                                         return false;
747                                 }
748                         }
749
750                         /* set channel mapping */
751                         /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
752                         /* front left, front right, center, LFE, back left, back right, surround left, surround right */
753                         /* specs say the channel ordering is:
754                          *                             1     2   3   4   5   6
755                          * ___________________________________________________
756                          * 2         stereo            l     r
757                          * 3                           l     r   c
758                          * 4                           l     c   r   S
759                          * quad (ambiguous with 4ch)  Fl    Fr   Bl  Br
760                          * 5                          Fl     Fr  Fc  Sl  Sr
761                          * 6                           l     lc  c   r   rc  S
762                          * l:left r:right c:center Fl:front-left Fr:front-right Bl:back-left Br:back-right Lc:left-center Rc:right-center S:surround
763                          * so we only have unambiguous mappings for 2, 3, and 5 channels
764                          */
765                         if(
766                                 options.channel_map_none ||
767                                 channels == 1 || /* 1 channel: (mono) */
768                                 channels == 2 || /* 2 channels: left, right */
769                                 channels == 3 || /* 3 channels: left, right, center */
770                                 channels == 5    /* 5 channels: front left, front right, center, surround left, surround right */
771                         ) {
772                                 /* keep default channel order */
773                         }
774                         else {
775                                 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
776                                 return false;
777                         }
778
779                         e->info.bytes_per_wide_sample = channels * (bps / 8);
780
781                         /* skip any extra data in the COMM chunk */
782                         if(!fskip_ahead(e->fin, skip)) {
783                                 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra COMM data\n", e->inbasefilename);
784                                 return false;
785                         }
786
787                         got_comm_chunk = true;
788                 }
789                 else if(!memcmp(chunk_id, "SSND", 4) && !got_ssnd_chunk) { /* sound data chunk */
790                         FLAC__uint32 xx;
791                         FLAC__uint64 data_bytes;
792                         unsigned offset = 0;
793
794                         if(!got_comm_chunk) {
795                                 flac__utils_printf(stderr, 1, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", e->inbasefilename);
796                                 return false;
797                         }
798
799                         /* SSND chunk size */
800                         if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
801                                 return false;
802                         data_bytes = xx;
803                         if(options.ignore_chunk_sizes) {
804                                 FLAC__ASSERT(!options.sector_align);
805                                 if(data_bytes) {
806                                         flac__utils_printf(stderr, 1, "%s: WARNING: 'SSND' chunk has non-zero size, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id);
807                                         if(e->treat_warnings_as_errors)
808                                                 return false;
809                                 }
810                                 data_bytes = (FLAC__uint64)0 - (FLAC__uint64)e->info.bytes_per_wide_sample; /* max out data_bytes; we'll use EOF as signal to stop reading */
811                         }
812                         else if(data_bytes <= 8) {
813                                 flac__utils_printf(stderr, 1, "%s: ERROR: 'SSND' chunk has size <= 8\n", e->inbasefilename);
814                                 return false;
815                         }
816                         else {
817                                 data_bytes -= 8; /* discount the offset and block size fields */
818                         }
819
820                         /* offset */
821                         if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
822                                 return false;
823                         offset = xx;
824                         data_bytes -= offset;
825
826                         /* block size */
827                         if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
828                                 return false;
829                         if(xx && !options.ignore_chunk_sizes)
830                                 data_bytes -= (xx - (data_bytes % xx));
831                         if(options.ignore_chunk_sizes) {
832                                 if(xx) {
833                                         flac__utils_printf(stderr, 1, "%s: WARNING: 'SSND' chunk has non-zero blocksize, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id);
834                                         if(e->treat_warnings_as_errors)
835                                                 return false;
836                                 }
837                         }
838
839                         /* skip any SSND offset bytes */
840                         if(!fskip_ahead(e->fin, offset)) {
841                                 flac__utils_printf(stderr, 1, "%s: ERROR: skipping offset in SSND chunk\n", e->inbasefilename);
842                                 return false;
843                         }
844
845                         e->fmt.iff.data_bytes = data_bytes;
846
847                         got_ssnd_chunk = true;
848                 }
849                 else {
850                         FLAC__uint32 xx;
851                         if(!options.format_options.iff.foreign_metadata) {
852                                 flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id);
853                                 if(e->treat_warnings_as_errors)
854                                         return false;
855                         }
856
857                         /* chunk size */
858                         if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
859                                 return false;
860                         else {
861                                 unsigned long skip = xx + (xx & 1);
862
863                                 FLAC__ASSERT(skip <= LONG_MAX);
864                                 if(!fskip_ahead(e->fin, skip)) {
865                                         flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename);
866                                         return false;
867                                 }
868                         }
869                 }
870         }
871
872         if(!got_comm_chunk) {
873                 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find COMM chunk\n", e->inbasefilename);
874                 return false;
875         }
876         if(!got_ssnd_chunk && sample_frames) {
877                 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find SSND chunk\n", e->inbasefilename);
878                 return false;
879         }
880
881         e->info.sample_rate = sample_rate;
882         e->info.channels = channels;
883         e->info.bits_per_sample = bps;
884         e->info.shift = shift;
885         e->info.channel_mask = channel_mask;
886
887         return true;
888 }
889
890 static FLAC__bool get_sample_info_flac(EncoderSession *e)
891 {
892         if (!(
893                 FLAC__stream_decoder_set_md5_checking(e->fmt.flac.decoder, false) &&
894                 FLAC__stream_decoder_set_metadata_respond_all(e->fmt.flac.decoder)
895         )) {
896                 flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", e->inbasefilename);
897                 return false;
898         }
899
900         if (e->format == FORMAT_OGGFLAC) {
901                 if (FLAC__stream_decoder_init_ogg_stream(e->fmt.flac.decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/e) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
902                         flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for Ogg FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder));
903                         return false;
904                 }
905         }
906         else if (FLAC__stream_decoder_init_stream(e->fmt.flac.decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/e) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
907                 flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder));
908                 return false;
909         }
910
911         if (!FLAC__stream_decoder_process_until_end_of_metadata(e->fmt.flac.decoder) || e->fmt.flac.client_data.fatal_error) {
912                 if (e->fmt.flac.client_data.fatal_error)
913                         flac__utils_printf(stderr, 1, "%s: ERROR: out of memory or too many metadata blocks while reading metadata in FLAC input\n", e->inbasefilename);
914                 else
915                         flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder));
916                 return false;
917         }
918
919         if (e->fmt.flac.client_data.num_metadata_blocks == 0) {
920                 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, got no metadata blocks\n", e->inbasefilename);
921                 return false;
922         }
923         else if (e->fmt.flac.client_data.metadata_blocks[0]->type != FLAC__METADATA_TYPE_STREAMINFO) {
924                 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, first metadata block is not STREAMINFO\n", e->inbasefilename);
925                 return false;
926         }
927         else if (e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples == 0) {
928                 flac__utils_printf(stderr, 1, "%s: ERROR: FLAC input has STREAMINFO with unknown total samples which is not supported\n", e->inbasefilename);
929                 return false;
930         }
931
932         e->info.sample_rate = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.sample_rate;
933         e->info.channels = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.channels;
934         e->info.bits_per_sample = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.bits_per_sample;
935         e->info.shift = 0;
936         e->info.bytes_per_wide_sample = 0;
937         e->info.is_unsigned_samples = false; /* not applicable for FLAC input */
938         e->info.is_big_endian = false; /* not applicable for FLAC input */
939         e->info.channel_mask = 0;
940
941         return true;
942 }
943
944 /*
945  * public routines
946  */
947 int flac__encode_file(FILE *infile, FLAC__off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, encode_options_t options)
948 {
949         EncoderSession encoder_session;
950         size_t channel_map[FLAC__MAX_CHANNELS];
951         int info_align_carry = -1, info_align_zero = -1;
952
953         if(!EncoderSession_construct(&encoder_session, options, infilesize, infile, infilename, outfilename, lookahead, lookahead_length))
954                 return 1;
955
956         /* initialize default channel map that preserves channel order */
957         {
958                 size_t i;
959                 for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++)
960                         channel_map[i] = i;
961         }
962
963         /* read foreign metadata if requested */
964         if(EncoderSession_format_is_iff(&encoder_session) && options.format_options.iff.foreign_metadata) {
965                 const char *error;
966                 if(!(
967                         options.format == FORMAT_WAVE || options.format == FORMAT_RF64?
968                                 flac__foreign_metadata_read_from_wave(options.format_options.iff.foreign_metadata, infilename, &error) :
969                         options.format == FORMAT_WAVE64?
970                                 flac__foreign_metadata_read_from_wave64(options.format_options.iff.foreign_metadata, infilename, &error) :
971                                 flac__foreign_metadata_read_from_aiff(options.format_options.iff.foreign_metadata, infilename, &error)
972                 )) {
973                         flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", encoder_session.inbasefilename, error);
974                         return EncoderSession_finish_error(&encoder_session);
975                 }
976         }
977
978         /* initialize encoder session with info about the audio (channels/bps/resolution/endianness/etc) */
979         switch(options.format) {
980                 case FORMAT_RAW:
981                         if(!get_sample_info_raw(&encoder_session, options))
982                                 return EncoderSession_finish_error(&encoder_session);
983                         break;
984                 case FORMAT_WAVE:
985                 case FORMAT_WAVE64:
986                 case FORMAT_RF64:
987                         if(!get_sample_info_wave(&encoder_session, options))
988                                 return EncoderSession_finish_error(&encoder_session);
989                         break;
990                 case FORMAT_AIFF:
991                 case FORMAT_AIFF_C:
992                         if(!get_sample_info_aiff(&encoder_session, options))
993                                 return EncoderSession_finish_error(&encoder_session);
994                         break;
995                 case FORMAT_FLAC:
996                 case FORMAT_OGGFLAC:
997                         /*
998                          * set up FLAC decoder for the input
999                          */
1000                         if (0 == (encoder_session.fmt.flac.decoder = FLAC__stream_decoder_new())) {
1001                                 flac__utils_printf(stderr, 1, "%s: ERROR: creating decoder for FLAC input\n", encoder_session.inbasefilename);
1002                                 return EncoderSession_finish_error(&encoder_session);
1003                         }
1004                         if(!get_sample_info_flac(&encoder_session))
1005                                 return EncoderSession_finish_error(&encoder_session);
1006                         break;
1007                 default:
1008                         FLAC__ASSERT(0);
1009                         /* double protection */
1010                         return EncoderSession_finish_error(&encoder_session);
1011         }
1012
1013         /* some more checks */
1014         if(encoder_session.info.channels == 0 || encoder_session.info.channels > FLAC__MAX_CHANNELS) {
1015                 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u\n", encoder_session.inbasefilename, encoder_session.info.channels);
1016                 return EncoderSession_finish_error(&encoder_session);
1017         }
1018         if(!FLAC__format_sample_rate_is_valid(encoder_session.info.sample_rate)) {
1019                 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, encoder_session.info.sample_rate);
1020                 return EncoderSession_finish_error(&encoder_session);
1021         }
1022         if(encoder_session.info.bits_per_sample-encoder_session.info.shift < 4 || encoder_session.info.bits_per_sample-encoder_session.info.shift > 24) {
1023                 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, encoder_session.info.bits_per_sample-encoder_session.info.shift);
1024                 return EncoderSession_finish_error(&encoder_session);
1025         }
1026         if(options.sector_align) {
1027                 if(encoder_session.info.channels != 2) {
1028                         flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.channels);
1029                         return EncoderSession_finish_error(&encoder_session);
1030                 }
1031                 if(encoder_session.info.sample_rate != 44100) {
1032                         flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.sample_rate);
1033                         return EncoderSession_finish_error(&encoder_session);
1034                 }
1035                 if(encoder_session.info.bits_per_sample-encoder_session.info.shift != 16) {
1036                         flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits-per-sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.bits_per_sample-encoder_session.info.shift);
1037                         return EncoderSession_finish_error(&encoder_session);
1038                 }
1039         }
1040
1041         {
1042                 FLAC__uint64 total_samples_in_input; /* WATCHOUT: may be 0 to mean "unknown" */
1043                 FLAC__uint64 skip;
1044                 FLAC__uint64 until; /* a value of 0 mean end-of-stream (i.e. --until=-0) */
1045                 unsigned align_remainder = 0;
1046
1047                 switch(options.format) {
1048                         case FORMAT_RAW:
1049                                 if(infilesize < 0)
1050                                         total_samples_in_input = 0;
1051                                 else
1052                                         total_samples_in_input = (FLAC__uint64)infilesize / encoder_session.info.bytes_per_wide_sample + *options.align_reservoir_samples;
1053                                 break;
1054                         case FORMAT_WAVE:
1055                         case FORMAT_WAVE64:
1056                         case FORMAT_RF64:
1057                         case FORMAT_AIFF:
1058                         case FORMAT_AIFF_C:
1059                                 /* truncation in the division removes any padding byte that was counted in encoder_session.fmt.iff.data_bytes */
1060                                 total_samples_in_input = encoder_session.fmt.iff.data_bytes / encoder_session.info.bytes_per_wide_sample + *options.align_reservoir_samples;
1061                                 break;
1062                         case FORMAT_FLAC:
1063                         case FORMAT_OGGFLAC:
1064                                 total_samples_in_input = encoder_session.fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples + *options.align_reservoir_samples;
1065                                 break;
1066                         default:
1067                                 FLAC__ASSERT(0);
1068                                 /* double protection */
1069                                 return EncoderSession_finish_error(&encoder_session);
1070                 }
1071
1072                 /*
1073                  * now that we know the sample rate, canonicalize the
1074                  * --skip string to an absolute sample number:
1075                  */
1076                 flac__utils_canonicalize_skip_until_specification(&options.skip_specification, encoder_session.info.sample_rate);
1077                 FLAC__ASSERT(options.skip_specification.value.samples >= 0);
1078                 skip = (FLAC__uint64)options.skip_specification.value.samples;
1079                 FLAC__ASSERT(!options.sector_align || (options.format != FORMAT_FLAC && options.format != FORMAT_OGGFLAC && skip == 0));
1080                 /* *options.align_reservoir_samples will be 0 unless --sector-align is used */
1081                 FLAC__ASSERT(options.sector_align || *options.align_reservoir_samples == 0);
1082
1083                 /*
1084                  * now that we possibly know the input size, canonicalize the
1085                  * --until string to an absolute sample number:
1086                  */
1087                 if(!canonicalize_until_specification(&options.until_specification, encoder_session.inbasefilename, encoder_session.info.sample_rate, skip, total_samples_in_input))
1088                         return EncoderSession_finish_error(&encoder_session);
1089                 until = (FLAC__uint64)options.until_specification.value.samples;
1090                 FLAC__ASSERT(!options.sector_align || until == 0);
1091
1092                 /* adjust encoding parameters based on skip and until values */
1093                 switch(options.format) {
1094                         case FORMAT_RAW:
1095                                 infilesize -= (FLAC__off_t)skip * encoder_session.info.bytes_per_wide_sample;
1096                                 encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1097                                 break;
1098                         case FORMAT_WAVE:
1099                         case FORMAT_WAVE64:
1100                         case FORMAT_RF64:
1101                         case FORMAT_AIFF:
1102                         case FORMAT_AIFF_C:
1103                                 encoder_session.fmt.iff.data_bytes -= skip * encoder_session.info.bytes_per_wide_sample;
1104                                 if(options.ignore_chunk_sizes) {
1105                                         encoder_session.total_samples_to_encode = 0;
1106                                         flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n");
1107                                         FLAC__ASSERT(0 == until);
1108                                 }
1109                                 else {
1110                                         encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1111                                 }
1112                                 break;
1113                         case FORMAT_FLAC:
1114                         case FORMAT_OGGFLAC:
1115                                 encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1116                                 break;
1117                         default:
1118                                 FLAC__ASSERT(0);
1119                                 /* double protection */
1120                                 return EncoderSession_finish_error(&encoder_session);
1121                 }
1122                 if(until > 0) {
1123                         const FLAC__uint64 trim = total_samples_in_input - until;
1124                         FLAC__ASSERT(total_samples_in_input > 0);
1125                         FLAC__ASSERT(!options.sector_align);
1126                         if(options.format == FORMAT_RAW)
1127                                 infilesize -= (FLAC__off_t)trim * encoder_session.info.bytes_per_wide_sample;
1128                         else if(EncoderSession_format_is_iff(&encoder_session))
1129                                 encoder_session.fmt.iff.data_bytes -= trim * encoder_session.info.bytes_per_wide_sample;
1130                         encoder_session.total_samples_to_encode -= trim;
1131                 }
1132                 if(options.sector_align && (options.format != FORMAT_RAW || infilesize >=0)) { /* for RAW, need to know the filesize */
1133                         FLAC__ASSERT(skip == 0); /* asserted above too, but lest we forget */
1134                         align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
1135                         if(options.is_last_file)
1136                                 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
1137                         else
1138                                 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
1139                 }
1140                 switch(options.format) {
1141                         case FORMAT_RAW:
1142                                 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample;
1143                                 break;
1144                         case FORMAT_WAVE:
1145                                 /* +44 for the size of the WAVE headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1146                                 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 44;
1147                                 break;
1148                         case FORMAT_WAVE64:
1149                                 /* +44 for the size of the WAVE headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1150                                 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 104;
1151                                 break;
1152                         case FORMAT_RF64:
1153                                 /* +72 for the size of the RF64 headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1154                                 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 80;
1155                                 break;
1156                         case FORMAT_AIFF:
1157                         case FORMAT_AIFF_C:
1158                                 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1159                                 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 54;
1160                                 break;
1161                         case FORMAT_FLAC:
1162                         case FORMAT_OGGFLAC:
1163                                 if(infilesize < 0)
1164                                         /* if we don't know, use 0 as hint to progress indicator (which is the only place this is used): */
1165                                         encoder_session.unencoded_size = 0;
1166                                 else if(skip == 0 && until == 0)
1167                                         encoder_session.unencoded_size = (FLAC__uint64)infilesize;
1168                                 else if(total_samples_in_input)
1169                                         encoder_session.unencoded_size = (FLAC__uint64)infilesize * encoder_session.total_samples_to_encode / total_samples_in_input;
1170                                 else
1171                                         encoder_session.unencoded_size = (FLAC__uint64)infilesize;
1172                                 break;
1173                         default:
1174                                 FLAC__ASSERT(0);
1175                                 /* double protection */
1176                                 return EncoderSession_finish_error(&encoder_session);
1177                 }
1178
1179                 if(encoder_session.total_samples_to_encode == 0)
1180                         flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n");
1181
1182                 if(options.format == FORMAT_FLAC || options.format == FORMAT_OGGFLAC)
1183                         encoder_session.fmt.flac.client_data.samples_left_to_process = encoder_session.total_samples_to_encode;
1184
1185                 stats_new_file();
1186                 /* init the encoder */
1187                 if(!EncoderSession_init_encoder(&encoder_session, options))
1188                         return EncoderSession_finish_error(&encoder_session);
1189
1190                 /* skip over any samples as requested */
1191                 if(skip > 0) {
1192                         switch(options.format) {
1193                                 case FORMAT_RAW:
1194                                         {
1195                                                 unsigned skip_bytes = encoder_session.info.bytes_per_wide_sample * (unsigned)skip;
1196                                                 if(skip_bytes > lookahead_length) {
1197                                                         skip_bytes -= lookahead_length;
1198                                                         lookahead_length = 0;
1199                                                         if(!fskip_ahead(encoder_session.fin, skip_bytes)) {
1200                                                                 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1201                                                                 return EncoderSession_finish_error(&encoder_session);
1202                                                         }
1203                                                 }
1204                                                 else {
1205                                                         lookahead += skip_bytes;
1206                                                         lookahead_length -= skip_bytes;
1207                                                 }
1208                                         }
1209                                         break;
1210                                 case FORMAT_WAVE:
1211                                 case FORMAT_WAVE64:
1212                                 case FORMAT_RF64:
1213                                 case FORMAT_AIFF:
1214                                 case FORMAT_AIFF_C:
1215                                         if(!fskip_ahead(encoder_session.fin, skip * encoder_session.info.bytes_per_wide_sample)) {
1216                                                 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1217                                                 return EncoderSession_finish_error(&encoder_session);
1218                                         }
1219                                         break;
1220                                 case FORMAT_FLAC:
1221                                 case FORMAT_OGGFLAC:
1222                                         /*
1223                                          * have to wait until the FLAC encoder is set up for writing
1224                                          * before any seeking in the input FLAC file, because the seek
1225                                          * itself will usually call the decoder's write callback, and
1226                                          * our decoder's write callback passes samples to our FLAC
1227                                          * encoder
1228                                          */
1229                                         if(!FLAC__stream_decoder_seek_absolute(encoder_session.fmt.flac.decoder, skip)) {
1230                                                 flac__utils_printf(stderr, 1, "%s: ERROR while skipping samples, FLAC decoder state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(encoder_session.fmt.flac.decoder));
1231                                                 return EncoderSession_finish_error(&encoder_session);
1232                                         }
1233                                         break;
1234                                 default:
1235                                         FLAC__ASSERT(0);
1236                                         /* double protection */
1237                                         return EncoderSession_finish_error(&encoder_session);
1238                         }
1239                 }
1240
1241                 /*
1242                  * first do any samples in the reservoir
1243                  */
1244                 if(options.sector_align && *options.align_reservoir_samples > 0) {
1245                         FLAC__ASSERT(options.format != FORMAT_FLAC && options.format != FORMAT_OGGFLAC); /* check again */
1246                         if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.align_reservoir, *options.align_reservoir_samples)) {
1247                                 print_error_with_state(&encoder_session, "ERROR during encoding");
1248                                 return EncoderSession_finish_error(&encoder_session);
1249                         }
1250                 }
1251
1252                 /*
1253                  * decrement infilesize or the data_bytes counter if we need to align the file
1254                  */
1255                 if(options.sector_align) {
1256                         if(options.is_last_file) {
1257                                 *options.align_reservoir_samples = 0;
1258                         }
1259                         else {
1260                                 *options.align_reservoir_samples = align_remainder;
1261                                 if(options.format == FORMAT_RAW) {
1262                                         FLAC__ASSERT(infilesize >= 0);
1263                                         infilesize -= (FLAC__off_t)((*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample);
1264                                         FLAC__ASSERT(infilesize >= 0);
1265                                 }
1266                                 else if(EncoderSession_format_is_iff(&encoder_session))
1267                                         encoder_session.fmt.iff.data_bytes -= (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample;
1268                         }
1269                 }
1270
1271                 /*
1272                  * now do samples from the file
1273                  */
1274                 switch(options.format) {
1275                         case FORMAT_RAW:
1276                                 if(infilesize < 0) {
1277                                         size_t bytes_read;
1278                                         while(!feof(infile)) {
1279                                                 if(lookahead_length > 0) {
1280                                                         FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample);
1281                                                         memcpy(ucbuffer_, lookahead, lookahead_length);
1282                                                         bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
1283                                                         if(ferror(infile)) {
1284                                                                 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1285                                                                 return EncoderSession_finish_error(&encoder_session);
1286                                                         }
1287                                                         lookahead_length = 0;
1288                                                 }
1289                                                 else
1290                                                         bytes_read = fread(ucbuffer_, sizeof(unsigned char), CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample, infile);
1291
1292                                                 if(bytes_read == 0) {
1293                                                         if(ferror(infile)) {
1294                                                                 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1295                                                                 return EncoderSession_finish_error(&encoder_session);
1296                                                         }
1297                                                 }
1298                                                 else if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1299                                                         flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1300                                                         return EncoderSession_finish_error(&encoder_session);
1301                                                 }
1302                                                 else {
1303                                                         unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1304                                                         if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map))
1305                                                                 return EncoderSession_finish_error(&encoder_session);
1306
1307                                                         if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1308                                                                 print_error_with_state(&encoder_session, "ERROR during encoding");
1309                                                                 return EncoderSession_finish_error(&encoder_session);
1310                                                         }
1311                                                 }
1312                                         }
1313                                 }
1314                                 else {
1315                                         size_t bytes_read;
1316                                         const FLAC__uint64 max_input_bytes = infilesize;
1317                                         FLAC__uint64 total_input_bytes_read = 0;
1318                                         while(total_input_bytes_read < max_input_bytes) {
1319                                                 {
1320                                                         size_t wanted = (CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample);
1321                                                         wanted = (size_t) min((FLAC__uint64)wanted, max_input_bytes - total_input_bytes_read);
1322
1323                                                         if(lookahead_length > 0) {
1324                                                                 FLAC__ASSERT(lookahead_length <= wanted);
1325                                                                 memcpy(ucbuffer_, lookahead, lookahead_length);
1326                                                                 wanted -= lookahead_length;
1327                                                                 bytes_read = lookahead_length;
1328                                                                 if(wanted > 0) {
1329                                                                         bytes_read += fread(ucbuffer_+lookahead_length, sizeof(unsigned char), wanted, infile);
1330                                                                         if(ferror(infile)) {
1331                                                                                 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1332                                                                                 return EncoderSession_finish_error(&encoder_session);
1333                                                                         }
1334                                                                 }
1335                                                                 lookahead_length = 0;
1336                                                         }
1337                                                         else
1338                                                                 bytes_read = fread(ucbuffer_, sizeof(unsigned char), wanted, infile);
1339                                                 }
1340
1341                                                 if(bytes_read == 0) {
1342                                                         if(ferror(infile)) {
1343                                                                 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1344                                                                 return EncoderSession_finish_error(&encoder_session);
1345                                                         }
1346                                                         else if(feof(infile)) {
1347                                                                 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %" PRIu64 " samples, got %" PRIu64 " samples\n", encoder_session.inbasefilename, encoder_session.total_samples_to_encode, encoder_session.samples_written);
1348                                                                 if(encoder_session.treat_warnings_as_errors)
1349                                                                         return EncoderSession_finish_error(&encoder_session);
1350                                                                 total_input_bytes_read = max_input_bytes;
1351                                                         }
1352                                                 }
1353                                                 else {
1354                                                         if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1355                                                                 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1356                                                                 return EncoderSession_finish_error(&encoder_session);
1357                                                         }
1358                                                         else {
1359                                                                 unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1360                                                                 if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map))
1361                                                                         return EncoderSession_finish_error(&encoder_session);
1362
1363                                                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1364                                                                         print_error_with_state(&encoder_session, "ERROR during encoding");
1365                                                                         return EncoderSession_finish_error(&encoder_session);
1366                                                                 }
1367                                                                 total_input_bytes_read += bytes_read;
1368                                                         }
1369                                                 }
1370                                         }
1371                                 }
1372                                 break;
1373                         case FORMAT_WAVE:
1374                         case FORMAT_WAVE64:
1375                         case FORMAT_RF64:
1376                         case FORMAT_AIFF:
1377                         case FORMAT_AIFF_C:
1378                                 while(encoder_session.fmt.iff.data_bytes > 0) {
1379                                         const size_t bytes_to_read = (size_t)min(
1380                                                 encoder_session.fmt.iff.data_bytes,
1381                                                 (FLAC__uint64)CHUNK_OF_SAMPLES * (FLAC__uint64)encoder_session.info.bytes_per_wide_sample
1382                                         );
1383                                         size_t bytes_read = fread(ucbuffer_, sizeof(unsigned char), bytes_to_read, infile);
1384                                         if(bytes_read == 0) {
1385                                                 if(ferror(infile)) {
1386                                                         flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1387                                                         return EncoderSession_finish_error(&encoder_session);
1388                                                 }
1389                                                 else if(feof(infile)) {
1390                                                         if(options.ignore_chunk_sizes) {
1391                                                                 flac__utils_printf(stderr, 1, "%s: INFO: hit EOF with --ignore-chunk-sizes, got %" PRIu64 " samples\n", encoder_session.inbasefilename, encoder_session.samples_written);
1392                                                         }
1393                                                         else {
1394                                                                 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %" PRIu64 " samples, got %" PRIu64 " samples\n", encoder_session.inbasefilename, encoder_session.total_samples_to_encode, encoder_session.samples_written);
1395                                                                 if(encoder_session.treat_warnings_as_errors)
1396                                                                         return EncoderSession_finish_error(&encoder_session);
1397                                                         }
1398                                                         encoder_session.fmt.iff.data_bytes = 0;
1399                                                 }
1400                                         }
1401                                         else {
1402                                                 if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1403                                                         flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1404                                                         return EncoderSession_finish_error(&encoder_session);
1405                                                 }
1406                                                 else {
1407                                                         unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1408                                                         if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map))
1409                                                                 return EncoderSession_finish_error(&encoder_session);
1410
1411                                                         if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1412                                                                 print_error_with_state(&encoder_session, "ERROR during encoding");
1413                                                                 return EncoderSession_finish_error(&encoder_session);
1414                                                         }
1415                                                         encoder_session.fmt.iff.data_bytes -= bytes_read;
1416                                                 }
1417                                         }
1418                                 }
1419                                 break;
1420                         case FORMAT_FLAC:
1421                         case FORMAT_OGGFLAC:
1422                                 while(!encoder_session.fmt.flac.client_data.fatal_error && encoder_session.fmt.flac.client_data.samples_left_to_process > 0) {
1423                                         /* We can also hit the end of stream without samples_left_to_process
1424                                          * going to 0 if there are errors and continue_through_decode_errors
1425                                          * is on, so we want to break in that case too:
1426                                          */
1427                                         if(encoder_session.continue_through_decode_errors && FLAC__stream_decoder_get_state(encoder_session.fmt.flac.decoder) == FLAC__STREAM_DECODER_END_OF_STREAM)
1428                                                 break;
1429                                         if(!FLAC__stream_decoder_process_single(encoder_session.fmt.flac.decoder)) {
1430                                                 flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(encoder_session.fmt.flac.decoder));
1431                                                 return EncoderSession_finish_error(&encoder_session);
1432                                         }
1433                                 }
1434                                 if(encoder_session.fmt.flac.client_data.fatal_error) {
1435                                         flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(encoder_session.fmt.flac.decoder));
1436                                         return EncoderSession_finish_error(&encoder_session);
1437                                 }
1438                                 break;
1439                         default:
1440                                 FLAC__ASSERT(0);
1441                                 /* double protection */
1442                                 return EncoderSession_finish_error(&encoder_session);
1443                 }
1444
1445                 /*
1446                  * now read unaligned samples into reservoir or pad with zeroes if necessary
1447                  */
1448                 if(options.sector_align) {
1449                         if(options.is_last_file) {
1450                                 unsigned wide_samples = 588 - align_remainder;
1451                                 if(wide_samples < 588) {
1452                                         unsigned channel;
1453
1454                                         info_align_zero = wide_samples;
1455                                         for(channel = 0; channel < encoder_session.info.channels; channel++)
1456                                                 memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
1457
1458                                         if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1459                                                 print_error_with_state(&encoder_session, "ERROR during encoding");
1460                                                 return EncoderSession_finish_error(&encoder_session);
1461                                         }
1462                                 }
1463                         }
1464                         else {
1465                                 if(*options.align_reservoir_samples > 0) {
1466                                         size_t bytes_read;
1467                                         FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1468                                         bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample, infile);
1469                                         if(bytes_read == 0 && ferror(infile)) {
1470                                                 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1471                                                 return EncoderSession_finish_error(&encoder_session);
1472                                         }
1473                                         else if(bytes_read != (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample) {
1474                                                 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %" PRIu64 " bytes; expected %" PRIu64 " samples, got %" PRIu64 " samples\n", encoder_session.inbasefilename, bytes_read, encoder_session.total_samples_to_encode, encoder_session.samples_written);
1475                                                 if(encoder_session.treat_warnings_as_errors)
1476                                                         return EncoderSession_finish_error(&encoder_session);
1477                                         }
1478                                         else {
1479                                                 info_align_carry = *options.align_reservoir_samples;
1480                                                 if(!format_input(options.align_reservoir, *options.align_reservoir_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map))
1481                                                         return EncoderSession_finish_error(&encoder_session);
1482                                         }
1483                                 }
1484                         }
1485                 }
1486         }
1487
1488         return EncoderSession_finish_ok(
1489                 &encoder_session,
1490                 info_align_carry,
1491                 info_align_zero,
1492                 EncoderSession_format_is_iff(&encoder_session)? options.format_options.iff.foreign_metadata : 0,
1493                 options.error_on_compression_fail
1494         );
1495 }
1496
1497 FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, FLAC__off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length)
1498 {
1499         unsigned i;
1500         FLAC__uint32 test = 1;
1501
1502         /*
1503          * initialize globals
1504          */
1505
1506         is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
1507
1508         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1509                 input_[i] = &(in_[i][0]);
1510
1511
1512         /*
1513          * initialize instance
1514          */
1515
1516 #if FLAC__HAS_OGG
1517         e->use_ogg = options.use_ogg;
1518 #endif
1519         e->verify = options.verify;
1520         e->treat_warnings_as_errors = options.treat_warnings_as_errors;
1521         e->continue_through_decode_errors = options.continue_through_decode_errors;
1522
1523         e->is_stdout = (0 == strcmp(outfilename, "-"));
1524         e->outputfile_opened = false;
1525
1526         e->inbasefilename = grabbag__file_get_basename(infilename);
1527         e->infilename = infilename;
1528         e->outfilename = outfilename;
1529
1530         e->total_samples_to_encode = 0;
1531         e->unencoded_size = 0;
1532         e->bytes_written = 0;
1533         e->samples_written = 0;
1534         e->stats_mask = 0;
1535
1536         memset(&e->info, 0, sizeof(e->info));
1537
1538         e->format = options.format;
1539
1540         switch(options.format) {
1541                 case FORMAT_RAW:
1542                         break;
1543                 case FORMAT_WAVE:
1544                 case FORMAT_WAVE64:
1545                 case FORMAT_RF64:
1546                 case FORMAT_AIFF:
1547                 case FORMAT_AIFF_C:
1548                         e->fmt.iff.data_bytes = 0;
1549                         break;
1550                 case FORMAT_FLAC:
1551                 case FORMAT_OGGFLAC:
1552                         e->fmt.flac.decoder = 0;
1553                         e->fmt.flac.client_data.filesize = infilesize;
1554                         e->fmt.flac.client_data.lookahead = lookahead;
1555                         e->fmt.flac.client_data.lookahead_length = lookahead_length;
1556                         e->fmt.flac.client_data.num_metadata_blocks = 0;
1557                         e->fmt.flac.client_data.samples_left_to_process = 0;
1558                         e->fmt.flac.client_data.fatal_error = false;
1559                         break;
1560                 default:
1561                         FLAC__ASSERT(0);
1562                         /* double protection */
1563                         return false;
1564         }
1565
1566         e->encoder = 0;
1567
1568         e->fin = infile;
1569         e->seek_table_template = 0;
1570
1571         if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1572                 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1573                 return false;
1574         }
1575
1576         e->encoder = FLAC__stream_encoder_new();
1577         if(0 == e->encoder) {
1578                 flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1579                 EncoderSession_destroy(e);
1580                 return false;
1581         }
1582
1583         return true;
1584 }
1585
1586 void EncoderSession_destroy(EncoderSession *e)
1587 {
1588         if(e->format == FORMAT_FLAC || e->format == FORMAT_OGGFLAC) {
1589                 size_t i;
1590                 if(e->fmt.flac.decoder)
1591                         FLAC__stream_decoder_delete(e->fmt.flac.decoder);
1592                 e->fmt.flac.decoder = 0;
1593                 for(i = 0; i < e->fmt.flac.client_data.num_metadata_blocks; i++)
1594                         FLAC__metadata_object_delete(e->fmt.flac.client_data.metadata_blocks[i]);
1595                 e->fmt.flac.client_data.num_metadata_blocks = 0;
1596         }
1597
1598         if(e->fin != stdin)
1599                 fclose(e->fin);
1600
1601         if(0 != e->encoder) {
1602                 FLAC__stream_encoder_delete(e->encoder);
1603                 e->encoder = 0;
1604         }
1605
1606         if(0 != e->seek_table_template) {
1607                 FLAC__metadata_object_delete(e->seek_table_template);
1608                 e->seek_table_template = 0;
1609         }
1610 }
1611
1612 int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero, foreign_metadata_t *foreign_metadata, FLAC__bool error_on_compression_fail)
1613 {
1614         FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1615         int ret = 0;
1616         FLAC__bool verify_error = false;
1617
1618         if(e->encoder) {
1619                 fse_state = FLAC__stream_encoder_get_state(e->encoder);
1620                 ret = FLAC__stream_encoder_finish(e->encoder)? 0 : 1;
1621                 verify_error =
1622                         fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA ||
1623                         FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA
1624                 ;
1625         }
1626         /* all errors except verify errors should interrupt the stats */
1627         if(ret && !verify_error)
1628                 print_error_with_state(e, "ERROR during encoding");
1629         else if(e->total_samples_to_encode > 0) {
1630                 print_stats(e);
1631                 flac__utils_printf(stderr, 2, "\n");
1632         }
1633
1634         if(verify_error) {
1635                 print_verify_error(e);
1636                 ret = 1;
1637         }
1638         else {
1639                 if(info_align_carry >= 0) {
1640                         flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d samples to be carried over\n", e->inbasefilename, info_align_carry);
1641                 }
1642                 if(info_align_zero >= 0) {
1643                         flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d zero samples to be appended\n", e->inbasefilename, info_align_zero);
1644                 }
1645         }
1646
1647         /*@@@@@@ should this go here or somewhere else? */
1648         if(ret == 0 && foreign_metadata) {
1649                 const char *error;
1650                 if(!flac__foreign_metadata_write_to_flac(foreign_metadata, e->infilename, e->outfilename, &error)) {
1651                         flac__utils_printf(stderr, 1, "%s: ERROR: updating foreign metadata in FLAC file: %s\n", e->inbasefilename, error);
1652                         ret = 1;
1653                 }
1654         }
1655
1656         if (e->compression_ratio >= 1.0) {
1657                 flac__utils_printf(stderr, 1,
1658                         "FAILURE: Compression failed (ratio %0.3f, should be < 1.0).\n"
1659                         "This happens for some files for one or more of the following reasons:\n"
1660                         " * Recompressing an existing FLAC from a higher to a lower compression setting.\n"
1661                         " * Insufficient input data  (eg, very short files, < 10000 frames).\n"
1662                         " * The audio data is not compressable (eg a full range white noise signal).\n"
1663                         , e->compression_ratio);
1664                 if (error_on_compression_fail)
1665                         ret = 1;
1666         }
1667
1668         EncoderSession_destroy(e);
1669
1670         return ret;
1671 }
1672
1673 int EncoderSession_finish_error(EncoderSession *e)
1674 {
1675         FLAC__ASSERT(e->encoder);
1676
1677         if(e->total_samples_to_encode > 0)
1678                 flac__utils_printf(stderr, 2, "\n");
1679
1680         if(FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1681                 print_verify_error(e);
1682         else if(e->outputfile_opened)
1683                 /* only want to delete the file if we opened it; otherwise it could be an existing file and our overwrite failed */
1684                 flac_unlink(e->outfilename);
1685
1686         EncoderSession_destroy(e);
1687
1688         return 1;
1689 }
1690
1691 typedef struct {
1692         unsigned num_metadata;
1693         FLAC__bool *needs_delete;
1694         FLAC__StreamMetadata **metadata;
1695         FLAC__StreamMetadata *cuesheet; /* always needs to be deleted */
1696 } static_metadata_t;
1697
1698 static void static_metadata_init(static_metadata_t *m)
1699 {
1700         m->num_metadata = 0;
1701         m->needs_delete = 0;
1702         m->metadata = 0;
1703         m->cuesheet = 0;
1704 }
1705
1706 static void static_metadata_clear(static_metadata_t *m)
1707 {
1708         unsigned i;
1709         for(i = 0; i < m->num_metadata; i++)
1710                 if(m->needs_delete[i])
1711                         FLAC__metadata_object_delete(m->metadata[i]);
1712         if(m->metadata)
1713                 free(m->metadata);
1714         if(m->needs_delete)
1715                 free(m->needs_delete);
1716         if(m->cuesheet)
1717                 FLAC__metadata_object_delete(m->cuesheet);
1718         static_metadata_init(m);
1719 }
1720
1721 static FLAC__bool static_metadata_append(static_metadata_t *m, FLAC__StreamMetadata *d, FLAC__bool needs_delete)
1722 {
1723         void *x;
1724         if(0 == (x = safe_realloc_muladd2_(m->metadata, sizeof(*m->metadata), /*times (*/m->num_metadata, /*+*/1/*)*/)))
1725                 return false;
1726         m->metadata = (FLAC__StreamMetadata**)x;
1727         if(0 == (x = safe_realloc_muladd2_(m->needs_delete, sizeof(*m->needs_delete), /*times (*/m->num_metadata, /*+*/1/*)*/)))
1728                 return false;
1729         m->needs_delete = (FLAC__bool*)x;
1730         m->metadata[m->num_metadata] = d;
1731         m->needs_delete[m->num_metadata] = needs_delete;
1732         m->num_metadata++;
1733         return true;
1734 }
1735
1736 FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options)
1737 {
1738         const unsigned channels = e->info.channels;
1739         const unsigned bps = e->info.bits_per_sample - e->info.shift;
1740         const unsigned sample_rate = e->info.sample_rate;
1741         FLACDecoderData *flac_decoder_data = (e->format == FORMAT_FLAC || e->format == FORMAT_OGGFLAC)? &e->fmt.flac.client_data : 0;
1742         FLAC__StreamMetadata padding;
1743         FLAC__StreamMetadata **metadata = 0;
1744         static_metadata_t static_metadata;
1745         unsigned num_metadata = 0, ic;
1746         FLAC__StreamEncoderInitStatus init_status;
1747         const FLAC__bool is_cdda = (channels == 1 || channels == 2) && (bps == 16) && (sample_rate == 44100);
1748         char apodizations[2000];
1749
1750         FLAC__ASSERT(sizeof(options.pictures)/sizeof(options.pictures[0]) <= 64);
1751
1752         static_metadata_init(&static_metadata);
1753
1754         e->replay_gain = options.replay_gain;
1755
1756         apodizations[0] = '\0';
1757
1758         if(e->replay_gain) {
1759                 if(channels != 1 && channels != 2) {
1760                         flac__utils_printf(stderr, 1, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
1761                         return false;
1762                 }
1763                 if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) {
1764                         flac__utils_printf(stderr, 1, "%s: ERROR, invalid sample rate (%u) for --replay-gain\n", e->inbasefilename, sample_rate);
1765                         return false;
1766                 }
1767                 if(options.is_first_file) {
1768                         if(!grabbag__replaygain_init(sample_rate)) {
1769                                 flac__utils_printf(stderr, 1, "%s: ERROR initializing ReplayGain stage\n", e->inbasefilename);
1770                                 return false;
1771                         }
1772                 }
1773         }
1774
1775         if(!parse_cuesheet(&static_metadata.cuesheet, options.cuesheet_filename, e->inbasefilename, sample_rate, is_cdda, e->total_samples_to_encode, e->treat_warnings_as_errors))
1776                 return false;
1777
1778         if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? static_metadata.cuesheet : 0, e)) {
1779                 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1780                 static_metadata_clear(&static_metadata);
1781                 return false;
1782         }
1783
1784         /* build metadata */
1785         if(flac_decoder_data) {
1786                 /*
1787                  * we're encoding from FLAC so we will use the FLAC file's
1788                  * metadata as the basis for the encoded file
1789                  */
1790                 {
1791                         unsigned i;
1792                         /*
1793                          * first handle pictures: simple append any --pictures
1794                          * specified.
1795                          */
1796                         for(i = 0; i < options.num_pictures; i++) {
1797                                 FLAC__StreamMetadata *pic = FLAC__metadata_object_clone(options.pictures[i]);
1798                                 if(0 == pic) {
1799                                         flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PICTURE block\n", e->inbasefilename);
1800                                         static_metadata_clear(&static_metadata);
1801                                         return false;
1802                                 }
1803                                 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks++] = pic;
1804                         }
1805                 }
1806                 {
1807                         /*
1808                          * next handle vorbis comment: if any tags were specified
1809                          * or there is no existing vorbis comment, we create a
1810                          * new vorbis comment (discarding any existing one); else
1811                          * we keep the existing one.  also need to make sure to
1812                          * propagate any channel mask tag.
1813                          */
1814                         /* @@@ change to append -T values from options.vorbis_comment if input has VC already? */
1815                         size_t i, j;
1816                         FLAC__bool vc_found = false;
1817                         for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1818                                 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
1819                                         vc_found = true;
1820                                 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT && options.vorbis_comment->data.vorbis_comment.num_comments > 0) {
1821                                         (void) flac__utils_get_channel_mask_tag(flac_decoder_data->metadata_blocks[i], &e->info.channel_mask);
1822                                         flac__utils_printf(stderr, 1, "%s: WARNING, replacing tags from input FLAC file with those given on the command-line\n", e->inbasefilename);
1823                                         if(e->treat_warnings_as_errors) {
1824                                                 static_metadata_clear(&static_metadata);
1825                                                 return false;
1826                                         }
1827                                         FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1828                                         flac_decoder_data->metadata_blocks[i] = 0;
1829                                 }
1830                                 else
1831                                         flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1832                         }
1833                         flac_decoder_data->num_metadata_blocks = j;
1834                         if((!vc_found || options.vorbis_comment->data.vorbis_comment.num_comments > 0) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1835                                 /* prepend ours */
1836                                 FLAC__StreamMetadata *vc = FLAC__metadata_object_clone(options.vorbis_comment);
1837                                 if(0 == vc || (e->info.channel_mask && !flac__utils_set_channel_mask_tag(vc, e->info.channel_mask))) {
1838                                         flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for VORBIS_COMMENT block\n", e->inbasefilename);
1839                                         static_metadata_clear(&static_metadata);
1840                                         return false;
1841                                 }
1842                                 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1843                                         flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1844                                 flac_decoder_data->metadata_blocks[1] = vc;
1845                                 flac_decoder_data->num_metadata_blocks++;
1846                         }
1847                 }
1848                 {
1849                         /*
1850                          * next handle cuesheet: if --cuesheet was specified, use
1851                          * it; else if file has existing CUESHEET and cuesheet's
1852                          * lead-out offset is correct, keep it; else no CUESHEET
1853                          */
1854                         size_t i, j;
1855                         for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1856                                 FLAC__bool existing_cuesheet_is_bad = false;
1857                                 /* check if existing cuesheet matches the input audio */
1858                                 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && 0 == static_metadata.cuesheet) {
1859                                         const FLAC__StreamMetadata_CueSheet *cs = &flac_decoder_data->metadata_blocks[i]->data.cue_sheet;
1860                                         if(e->total_samples_to_encode == 0) {
1861                                                 flac__utils_printf(stderr, 1, "%s: WARNING, cuesheet in input FLAC file cannot be kept if input size is not known, dropping it...\n", e->inbasefilename);
1862                                                 if(e->treat_warnings_as_errors) {
1863                                                         static_metadata_clear(&static_metadata);
1864                                                         return false;
1865                                                 }
1866                                                 existing_cuesheet_is_bad = true;
1867                                         }
1868                                         else if(e->total_samples_to_encode != cs->tracks[cs->num_tracks-1].offset) {
1869                                                 flac__utils_printf(stderr, 1, "%s: WARNING, lead-out offset of cuesheet in input FLAC file does not match input length, dropping existing cuesheet...\n", e->inbasefilename);
1870                                                 if(e->treat_warnings_as_errors) {
1871                                                         static_metadata_clear(&static_metadata);
1872                                                         return false;
1873                                                 }
1874                                                 existing_cuesheet_is_bad = true;
1875                                         }
1876                                 }
1877                                 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && (existing_cuesheet_is_bad || 0 != static_metadata.cuesheet)) {
1878                                         if(0 != static_metadata.cuesheet) {
1879                                                 flac__utils_printf(stderr, 1, "%s: WARNING, replacing cuesheet in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1880                                                 if(e->treat_warnings_as_errors) {
1881                                                         static_metadata_clear(&static_metadata);
1882                                                         return false;
1883                                                 }
1884                                         }
1885                                         FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1886                                         flac_decoder_data->metadata_blocks[i] = 0;
1887                                 }
1888                                 else
1889                                         flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1890                         }
1891                         flac_decoder_data->num_metadata_blocks = j;
1892                         if(0 != static_metadata.cuesheet && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1893                                 /* prepend ours */
1894                                 FLAC__StreamMetadata *cs = FLAC__metadata_object_clone(static_metadata.cuesheet);
1895                                 if(0 == cs) {
1896                                         flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for CUESHEET block\n", e->inbasefilename);
1897                                         static_metadata_clear(&static_metadata);
1898                                         return false;
1899                                 }
1900                                 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1901                                         flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1902                                 flac_decoder_data->metadata_blocks[1] = cs;
1903                                 flac_decoder_data->num_metadata_blocks++;
1904                         }
1905                 }
1906                 {
1907                         /*
1908                          * next handle seektable: if -S- was specified, no
1909                          * SEEKTABLE; else if -S was specified, use it/them;
1910                          * else if file has existing SEEKTABLE and input size is
1911                          * preserved (no --skip/--until/etc specified), keep it;
1912                          * else use default seektable options
1913                          *
1914                          * note: meanings of num_requested_seek_points:
1915                          *  -1 : no -S option given, default to some value
1916                          *   0 : -S- given (no seektable)
1917                          *  >0 : one or more -S options given
1918                          */
1919                         size_t i, j;
1920                         FLAC__bool existing_seektable = false;
1921                         for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1922                                 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE)
1923                                         existing_seektable = true;
1924                                 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE && (e->total_samples_to_encode != flac_decoder_data->metadata_blocks[0]->data.stream_info.total_samples || options.num_requested_seek_points >= 0)) {
1925                                         if(options.num_requested_seek_points > 0) {
1926                                                 flac__utils_printf(stderr, 1, "%s: WARNING, replacing seektable in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1927                                                 if(e->treat_warnings_as_errors) {
1928                                                         static_metadata_clear(&static_metadata);
1929                                                         return false;
1930                                                 }
1931                                         }
1932                                         else if(options.num_requested_seek_points == 0)
1933                                                 ; /* no warning, silently delete existing SEEKTABLE since user specified --no-seektable (-S-) */
1934                                         else {
1935                                                 flac__utils_printf(stderr, 1, "%s: WARNING, can't use existing seektable in input FLAC since the input size is changing or unknown, dropping existing SEEKTABLE block...\n", e->inbasefilename);
1936                                                 if(e->treat_warnings_as_errors) {
1937                                                         static_metadata_clear(&static_metadata);
1938                                                         return false;
1939                                                 }
1940                                         }
1941                                         FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1942                                         flac_decoder_data->metadata_blocks[i] = 0;
1943                                         existing_seektable = false;
1944                                 }
1945                                 else
1946                                         flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1947                         }
1948                         flac_decoder_data->num_metadata_blocks = j;
1949                         if((options.num_requested_seek_points > 0 || (options.num_requested_seek_points < 0 && !existing_seektable)) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1950                                 /* prepend ours */
1951                                 FLAC__StreamMetadata *st = FLAC__metadata_object_clone(e->seek_table_template);
1952                                 if(0 == st) {
1953                                         flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for SEEKTABLE block\n", e->inbasefilename);
1954                                         static_metadata_clear(&static_metadata);
1955                                         return false;
1956                                 }
1957                                 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1958                                         flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1959                                 flac_decoder_data->metadata_blocks[1] = st;
1960                                 flac_decoder_data->num_metadata_blocks++;
1961                         }
1962                 }
1963                 {
1964                         /*
1965                          * finally handle padding: if --no-padding was specified,
1966                          * then delete all padding; else if -P was specified,
1967                          * use that instead of existing padding (if any); else
1968                          * if existing file has padding, move all existing
1969                          * padding blocks to one padding block at the end; else
1970                          * use default padding.
1971                          */
1972                         int p = -1;
1973                         size_t i, j;
1974                         for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1975                                 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_PADDING) {
1976                                         if(p < 0)
1977                                                 p = 0;
1978                                         p += flac_decoder_data->metadata_blocks[i]->length;
1979                                         FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1980                                         flac_decoder_data->metadata_blocks[i] = 0;
1981                                 }
1982                                 else
1983                                         flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1984                         }
1985                         flac_decoder_data->num_metadata_blocks = j;
1986                         if(options.padding > 0)
1987                                 p = options.padding;
1988                         if(p < 0)
1989                                 p = e->total_samples_to_encode / sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8;
1990                         if(p > 0)
1991                                 p += (e->replay_gain ? GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED : 0);
1992                         if(options.padding != 0) {
1993                                 if(p > 0 && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1994                                         flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
1995                                         if(0 == flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]) {
1996                                                 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PADDING block\n", e->inbasefilename);
1997                                                 static_metadata_clear(&static_metadata);
1998                                                 return false;
1999                                         }
2000                                         flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->is_last = false; /* the encoder will set this for us */
2001                                         flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->length = p;
2002                                         flac_decoder_data->num_metadata_blocks++;
2003                                 }
2004                         }
2005                 }
2006                 metadata = &flac_decoder_data->metadata_blocks[1]; /* don't include STREAMINFO */
2007                 num_metadata = flac_decoder_data->num_metadata_blocks - 1;
2008         }
2009         else {
2010                 /*
2011                  * we're not encoding from FLAC so we will build the metadata
2012                  * from scratch
2013                  */
2014                 const foreign_metadata_t *foreign_metadata = EncoderSession_format_is_iff(e)? options.format_options.iff.foreign_metadata : 0;
2015                 unsigned i;
2016
2017                 if(e->seek_table_template->data.seek_table.num_points > 0) {
2018                         e->seek_table_template->is_last = false; /* the encoder will set this for us */
2019                         static_metadata_append(&static_metadata, e->seek_table_template, /*needs_delete=*/false);
2020                 }
2021                 if(0 != static_metadata.cuesheet)
2022                         static_metadata_append(&static_metadata, static_metadata.cuesheet, /*needs_delete=*/false);
2023                 if(e->info.channel_mask) {
2024                         if(!flac__utils_set_channel_mask_tag(options.vorbis_comment, e->info.channel_mask)) {
2025                                 flac__utils_printf(stderr, 1, "%s: ERROR adding channel mask tag\n", e->inbasefilename);
2026                                 static_metadata_clear(&static_metadata);
2027                                 return false;
2028                         }
2029                 }
2030                 static_metadata_append(&static_metadata, options.vorbis_comment, /*needs_delete=*/false);
2031                 for(i = 0; i < options.num_pictures; i++)
2032                         static_metadata_append(&static_metadata, options.pictures[i], /*needs_delete=*/false);
2033                 if(foreign_metadata) {
2034                         for(i = 0; i < foreign_metadata->num_blocks; i++) {
2035                                 FLAC__StreamMetadata *p = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
2036                                 if(!p) {
2037                                         flac__utils_printf(stderr, 1, "%s: ERROR: out of memory\n", e->inbasefilename);
2038                                         static_metadata_clear(&static_metadata);
2039                                         return false;
2040                                 }
2041                                 static_metadata_append(&static_metadata, p, /*needs_delete=*/true);
2042                                 static_metadata.metadata[static_metadata.num_metadata-1]->length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8 + foreign_metadata->blocks[i].size;
2043                         }
2044                 }
2045                 if(options.padding != 0) {
2046                         padding.is_last = false; /* the encoder will set this for us */
2047                         padding.type = FLAC__METADATA_TYPE_PADDING;
2048                         padding.length = (unsigned)(options.padding>0? options.padding : (e->total_samples_to_encode / sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8)) + (e->replay_gain ? GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED : 0);
2049                         static_metadata_append(&static_metadata, &padding, /*needs_delete=*/false);
2050                 }
2051                 metadata = static_metadata.metadata;
2052                 num_metadata = static_metadata.num_metadata;
2053         }
2054
2055         /* check for a few things that have not already been checked.  the
2056          * FLAC__stream_encoder_init*() will check it but only return
2057          * FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA so we check some
2058          * up front to give a better error message.
2059          */
2060         if(!verify_metadata(e, metadata, num_metadata)) {
2061                 static_metadata_clear(&static_metadata);
2062                 return false;
2063         }
2064
2065         FLAC__stream_encoder_set_verify(e->encoder, options.verify);
2066         FLAC__stream_encoder_set_streamable_subset(e->encoder, !options.lax);
2067         FLAC__stream_encoder_set_channels(e->encoder, channels);
2068         FLAC__stream_encoder_set_bits_per_sample(e->encoder, bps);
2069         FLAC__stream_encoder_set_sample_rate(e->encoder, sample_rate);
2070         for(ic = 0; ic < options.num_compression_settings; ic++) {
2071                 switch(options.compression_settings[ic].type) {
2072                         case CST_BLOCKSIZE:
2073                                 FLAC__stream_encoder_set_blocksize(e->encoder, options.compression_settings[ic].value.t_unsigned);
2074                                 break;
2075                         case CST_COMPRESSION_LEVEL:
2076                                 FLAC__stream_encoder_set_compression_level(e->encoder, options.compression_settings[ic].value.t_unsigned);
2077                                 apodizations[0] = '\0';
2078                                 break;
2079                         case CST_DO_MID_SIDE:
2080                                 FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder, options.compression_settings[ic].value.t_bool);
2081                                 break;
2082                         case CST_LOOSE_MID_SIDE:
2083                                 FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder, options.compression_settings[ic].value.t_bool);
2084                                 break;
2085                         case CST_APODIZATION:
2086                                 if(strlen(apodizations)+strlen(options.compression_settings[ic].value.t_string)+2 >= sizeof(apodizations)) {
2087                                         flac__utils_printf(stderr, 1, "%s: ERROR: too many apodization functions requested\n", e->inbasefilename);
2088                                         static_metadata_clear(&static_metadata);
2089                                         return false;
2090                                 }
2091                                 else {
2092                                         safe_strncat(apodizations, options.compression_settings[ic].value.t_string, sizeof(apodizations));
2093                                         safe_strncat(apodizations, ";", sizeof(apodizations));
2094                                 }
2095                                 break;
2096                         case CST_MAX_LPC_ORDER:
2097                                 FLAC__stream_encoder_set_max_lpc_order(e->encoder, options.compression_settings[ic].value.t_unsigned);
2098                                 break;
2099                         case CST_QLP_COEFF_PRECISION:
2100                                 FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder, options.compression_settings[ic].value.t_unsigned);
2101                                 break;
2102                         case CST_DO_QLP_COEFF_PREC_SEARCH:
2103                                 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder, options.compression_settings[ic].value.t_bool);
2104                                 break;
2105                         case CST_DO_ESCAPE_CODING:
2106                                 FLAC__stream_encoder_set_do_escape_coding(e->encoder, options.compression_settings[ic].value.t_bool);
2107                                 break;
2108                         case CST_DO_EXHAUSTIVE_MODEL_SEARCH:
2109                                 FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder, options.compression_settings[ic].value.t_bool);
2110                                 break;
2111                         case CST_MIN_RESIDUAL_PARTITION_ORDER:
2112                                 FLAC__stream_encoder_set_min_residual_partition_order(e->encoder, options.compression_settings[ic].value.t_unsigned);
2113                                 break;
2114                         case CST_MAX_RESIDUAL_PARTITION_ORDER:
2115                                 FLAC__stream_encoder_set_max_residual_partition_order(e->encoder, options.compression_settings[ic].value.t_unsigned);
2116                                 break;
2117                         case CST_RICE_PARAMETER_SEARCH_DIST:
2118                                 FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder, options.compression_settings[ic].value.t_unsigned);
2119                                 break;
2120                 }
2121         }
2122         if(*apodizations)
2123                 FLAC__stream_encoder_set_apodization(e->encoder, apodizations);
2124         FLAC__stream_encoder_set_total_samples_estimate(e->encoder, e->total_samples_to_encode);
2125         FLAC__stream_encoder_set_metadata(e->encoder, (num_metadata > 0)? metadata : 0, num_metadata);
2126
2127         FLAC__stream_encoder_disable_constant_subframes(e->encoder, options.debug.disable_constant_subframes);
2128         FLAC__stream_encoder_disable_fixed_subframes(e->encoder, options.debug.disable_fixed_subframes);
2129         FLAC__stream_encoder_disable_verbatim_subframes(e->encoder, options.debug.disable_verbatim_subframes);
2130         if(!options.debug.do_md5) {
2131                 flac__utils_printf(stderr, 1, "%s: WARNING, MD5 computation disabled, resulting file will not have MD5 sum\n", e->inbasefilename);
2132                 if(e->treat_warnings_as_errors) {
2133                         static_metadata_clear(&static_metadata);
2134                         return false;
2135                 }
2136                 FLAC__stream_encoder_set_do_md5(e->encoder, false);
2137         }
2138
2139 #if FLAC__HAS_OGG
2140         if(e->use_ogg) {
2141                 FLAC__stream_encoder_set_ogg_serial_number(e->encoder, options.serial_number);
2142
2143                 init_status = FLAC__stream_encoder_init_ogg_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
2144         }
2145         else
2146 #endif
2147         {
2148                 init_status = FLAC__stream_encoder_init_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
2149         }
2150
2151         if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
2152                 print_error_with_init_status(e, "ERROR initializing encoder", init_status);
2153                 if(FLAC__stream_encoder_get_state(e->encoder) != FLAC__STREAM_ENCODER_IO_ERROR)
2154                         e->outputfile_opened = true;
2155                 static_metadata_clear(&static_metadata);
2156                 return false;
2157         }
2158         else
2159                 e->outputfile_opened = true;
2160
2161         e->stats_mask =
2162                 (FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) && FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x07 :
2163                 (FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x0f :
2164                 0x3f;
2165
2166         static_metadata_clear(&static_metadata);
2167
2168         return true;
2169 }
2170
2171 FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples)
2172 {
2173         if(e->replay_gain) {
2174                 if(!grabbag__replaygain_analyze(buffer, e->info.channels==2, e->info.bits_per_sample, samples)) {
2175                         flac__utils_printf(stderr, 1, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename);
2176                         if(e->treat_warnings_as_errors)
2177                                 return false;
2178                 }
2179         }
2180
2181         return FLAC__stream_encoder_process(e->encoder, buffer, samples);
2182 }
2183
2184 FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e)
2185 {
2186         return
2187                 e->format == FORMAT_WAVE ||
2188                 e->format == FORMAT_WAVE64 ||
2189                 e->format == FORMAT_RF64 ||
2190                 e->format == FORMAT_AIFF ||
2191                 e->format == FORMAT_AIFF_C;
2192 }
2193
2194 FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e)
2195 {
2196         const FLAC__bool only_placeholders = e->is_stdout;
2197         FLAC__bool has_real_points;
2198
2199         if(num_requested_seek_points == 0 && 0 == cuesheet)
2200                 return true;
2201
2202         if(num_requested_seek_points < 0) {
2203 #if FLAC__HAS_OGG
2204                 /*@@@@@@ workaround ogg bug: too many seekpoints makes table not fit in one page */
2205                 if(e->use_ogg && e->total_samples_to_encode > 0 && e->total_samples_to_encode / e->info.sample_rate / 10 > 230)
2206                         requested_seek_points = "230x;";
2207                 else
2208 #endif
2209                         requested_seek_points = "10s;";
2210                 num_requested_seek_points = 1;
2211         }
2212
2213         if(num_requested_seek_points > 0) {
2214                 if(!grabbag__seektable_convert_specification_to_template(requested_seek_points, only_placeholders, e->total_samples_to_encode, e->info.sample_rate, e->seek_table_template, &has_real_points))
2215                         return false;
2216         }
2217
2218         if(0 != cuesheet) {
2219                 unsigned i, j;
2220                 const FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet;
2221                 for(i = 0; i < cs->num_tracks; i++) {
2222                         const FLAC__StreamMetadata_CueSheet_Track *tr = cs->tracks+i;
2223                         for(j = 0; j < tr->num_indices; j++) {
2224                                 if(!FLAC__metadata_object_seektable_template_append_point(e->seek_table_template, tr->offset + tr->indices[j].offset))
2225                                         return false;
2226                                 has_real_points = true;
2227                         }
2228                 }
2229                 if(has_real_points)
2230                         if(!FLAC__metadata_object_seektable_template_sort(e->seek_table_template, /*compact=*/true))
2231                                 return false;
2232         }
2233
2234         if(has_real_points) {
2235                 if(e->is_stdout) {
2236                         flac__utils_printf(stderr, 1, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename);
2237                         if(e->treat_warnings_as_errors)
2238                                 return false;
2239                 }
2240         }
2241
2242         return true;
2243 }
2244
2245 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
2246 {
2247         /* convert from mm:ss.sss to sample number if necessary */
2248         flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
2249
2250         /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
2251         if(spec->is_relative && spec->value.samples == 0) {
2252                 spec->is_relative = false;
2253                 return true;
2254         }
2255
2256         /* in any other case the total samples in the input must be known */
2257         if(total_samples_in_input == 0) {
2258                 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when input length is unknown\n", inbasefilename);
2259                 return false;
2260         }
2261
2262         FLAC__ASSERT(spec->value_is_samples);
2263
2264         /* convert relative specifications to absolute */
2265         if(spec->is_relative) {
2266                 if(spec->value.samples <= 0)
2267                         spec->value.samples += (FLAC__int64)total_samples_in_input;
2268                 else
2269                         spec->value.samples += skip;
2270                 spec->is_relative = false;
2271         }
2272
2273         /* error check */
2274         if(spec->value.samples < 0) {
2275                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
2276                 return false;
2277         }
2278         if((FLAC__uint64)spec->value.samples <= skip) {
2279                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
2280                 return false;
2281         }
2282         if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
2283                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
2284                 return false;
2285         }
2286
2287         return true;
2288 }
2289
2290 FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata)
2291 {
2292         FLAC__bool metadata_picture_has_type1 = false;
2293         FLAC__bool metadata_picture_has_type2 = false;
2294         unsigned i;
2295
2296         FLAC__ASSERT(0 != metadata);
2297         for(i = 0; i < num_metadata; i++) {
2298                 const FLAC__StreamMetadata *m = metadata[i];
2299                 if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
2300                         if(!FLAC__format_seektable_is_legal(&m->data.seek_table)) {
2301                                 flac__utils_printf(stderr, 1, "%s: ERROR: SEEKTABLE metadata block is invalid\n", e->inbasefilename);
2302                                 return false;
2303                         }
2304                 }
2305                 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
2306                         if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0)) {
2307                                 flac__utils_printf(stderr, 1, "%s: ERROR: CUESHEET metadata block is invalid\n", e->inbasefilename);
2308                                 return false;
2309                         }
2310                 }
2311                 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
2312                         const char *error = 0;
2313                         if(!FLAC__format_picture_is_legal(&m->data.picture, &error)) {
2314                                 flac__utils_printf(stderr, 1, "%s: ERROR: PICTURE metadata block is invalid: %s\n", e->inbasefilename, error);
2315                                 return false;
2316                         }
2317                         if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
2318                                 if(metadata_picture_has_type1) {
2319                                         flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 1 (32x32 icon) in the file\n", e->inbasefilename);
2320                                         return false;
2321                                 }
2322                                 metadata_picture_has_type1 = true;
2323                         }
2324                         else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
2325                                 if(metadata_picture_has_type2) {
2326                                         flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 2 (icon) in the file\n", e->inbasefilename);
2327                                         return false;
2328                                 }
2329                                 metadata_picture_has_type2 = true;
2330                         }
2331                 }
2332         }
2333
2334         return true;
2335 }
2336
2337 FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift, size_t *channel_map)
2338 {
2339         unsigned wide_sample, sample, channel;
2340         FLAC__int32 *out[FLAC__MAX_CHANNELS];
2341
2342         if(0 == channel_map) {
2343                 for(channel = 0; channel < channels; channel++)
2344                         out[channel] = dest[channel];
2345         }
2346         else {
2347                 for(channel = 0; channel < channels; channel++)
2348                         out[channel] = dest[channel_map[channel]];
2349         }
2350
2351         if(bps == 8) {
2352                 if(is_unsigned_samples) {
2353                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2354                                 for(channel = 0; channel < channels; channel++, sample++)
2355                                         out[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
2356                 }
2357                 else {
2358                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2359                                 for(channel = 0; channel < channels; channel++, sample++)
2360                                         out[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
2361                 }
2362         }
2363         else if(bps == 16) {
2364                 if(is_big_endian != is_big_endian_host_) {
2365                         unsigned char tmp;
2366                         const unsigned bytes = wide_samples * channels * (bps >> 3);
2367                         unsigned b;
2368                         for(b = 0; b < bytes; b += 2) {
2369                                 tmp = ucbuffer_[b];
2370                                 ucbuffer_[b] = ucbuffer_[b+1];
2371                                 ucbuffer_[b+1] = tmp;
2372                         }
2373                 }
2374                 if(is_unsigned_samples) {
2375                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2376                                 for(channel = 0; channel < channels; channel++, sample++)
2377                                         out[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
2378                 }
2379                 else {
2380                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2381                                 for(channel = 0; channel < channels; channel++, sample++)
2382                                         out[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
2383                 }
2384         }
2385         else if(bps == 24) {
2386                 if(!is_big_endian) {
2387                         unsigned char tmp;
2388                         const unsigned bytes = wide_samples * channels * (bps >> 3);
2389                         unsigned b;
2390                         for(b = 0; b < bytes; b += 3) {
2391                                 tmp = ucbuffer_[b];
2392                                 ucbuffer_[b] = ucbuffer_[b+2];
2393                                 ucbuffer_[b+2] = tmp;
2394                         }
2395                 }
2396                 if(is_unsigned_samples) {
2397                         unsigned b;
2398                         for(b = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2399                                 for(channel = 0; channel < channels; channel++, sample++) {
2400                                         FLAC__int32 t;
2401                                         t  = ucbuffer_[b++]; t <<= 8;
2402                                         t |= ucbuffer_[b++]; t <<= 8;
2403                                         t |= ucbuffer_[b++];
2404                                         t -= 0x800000;
2405                                         out[channel][wide_sample] = t;
2406                                 }
2407                 }
2408                 else {
2409                         unsigned b;
2410                         for(b = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2411                                 for(channel = 0; channel < channels; channel++, sample++) {
2412                                         FLAC__int32 t;
2413                                         t  = scbuffer_[b++]; t <<= 8;
2414                                         t |= ucbuffer_[b++]; t <<= 8;
2415                                         t |= ucbuffer_[b++];
2416                                         out[channel][wide_sample] = t;
2417                                 }
2418                 }
2419         }
2420         else {
2421                 FLAC__ASSERT(0);
2422         }
2423         if(shift > 0) {
2424                 FLAC__int32 mask = (1<<shift)-1;
2425                 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2426                         for(channel = 0; channel < channels; channel++) {
2427                                 if(out[channel][wide_sample] & mask) {
2428                                         flac__utils_printf(stderr, 1, "ERROR during read, sample data (channel#%u sample#%u = %d) has non-zero least-significant bits\n  WAVE/AIFF header said the last %u bits are not significant and should be zero.\n", channel, wide_sample, out[channel][wide_sample], shift);
2429                                         return false;
2430                                 }
2431                                 out[channel][wide_sample] >>= shift;
2432                         }
2433         }
2434         return true;
2435 }
2436
2437 void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
2438 {
2439         EncoderSession *e = (EncoderSession*)client_data;
2440
2441         const FLAC__uint64 uesize = e->unencoded_size;
2442
2443 #if defined _MSC_VER || defined __MINGW32__
2444         /* with MSVC you have to spoon feed it the casting */
2445         e->progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)e->total_samples_to_encode;
2446         e->compression_ratio = (double)(FLAC__int64)e->bytes_written / ((double)(FLAC__int64)(uesize? uesize:1) * min(1.0, e->progress));
2447 #else
2448         e->progress = (double)samples_written / (double)e->total_samples_to_encode;
2449         e->compression_ratio = (double)e->bytes_written / ((double)(uesize? uesize:1) * min(1.0, e->progress));
2450 #endif
2451
2452         (void)encoder, (void)total_frames_estimate;
2453
2454         e->bytes_written = bytes_written;
2455         e->samples_written = samples_written;
2456
2457         if(e->total_samples_to_encode > 0 && !((frames_written-1) & e->stats_mask))
2458                 print_stats(e);
2459 }
2460
2461 FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
2462 {
2463         size_t n = 0;
2464         EncoderSession *e = (EncoderSession*)client_data;
2465     FLACDecoderData *data = &e->fmt.flac.client_data;
2466
2467         (void)decoder;
2468
2469         if (data->fatal_error)
2470                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2471
2472         /* use up lookahead first */
2473         if (data->lookahead_length) {
2474                 n = min(data->lookahead_length, *bytes);
2475                 memcpy(buffer, data->lookahead, n);
2476                 buffer += n;
2477                 data->lookahead += n;
2478                 data->lookahead_length -= n;
2479         }
2480
2481         /* get the rest from file */
2482         if (*bytes > n) {
2483                 *bytes = n + fread(buffer, 1, *bytes-n, e->fin);
2484                 if(ferror(e->fin))
2485                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2486                 else if(0 == *bytes)
2487                         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2488                 else
2489                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2490         }
2491         else
2492                 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2493 }
2494
2495 FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2496 {
2497         EncoderSession *e = (EncoderSession*)client_data;
2498         (void)decoder;
2499
2500         if(fseeko(e->fin, (FLAC__off_t)absolute_byte_offset, SEEK_SET) < 0)
2501                 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
2502         else
2503                 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2504 }
2505
2506 FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2507 {
2508         EncoderSession *e = (EncoderSession*)client_data;
2509         FLAC__off_t pos;
2510         (void)decoder;
2511
2512         if((pos = ftello(e->fin)) < 0)
2513                 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
2514         else {
2515                 *absolute_byte_offset = (FLAC__uint64)pos;
2516                 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2517         }
2518 }
2519
2520 FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2521 {
2522         const EncoderSession *e = (EncoderSession*)client_data;
2523     const FLACDecoderData *data = &e->fmt.flac.client_data;
2524         (void)decoder;
2525
2526         if(data->filesize < 0)
2527                 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
2528         else {
2529                 *stream_length = (FLAC__uint64)data->filesize;
2530                 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2531         }
2532 }
2533
2534 FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data)
2535 {
2536         EncoderSession *e = (EncoderSession*)client_data;
2537         (void)decoder;
2538
2539         return feof(e->fin)? true : false;
2540 }
2541
2542 FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
2543 {
2544         EncoderSession *e = (EncoderSession*)client_data;
2545     FLACDecoderData *data = &e->fmt.flac.client_data;
2546         FLAC__uint64 n = min(data->samples_left_to_process, frame->header.blocksize);
2547         (void)decoder;
2548
2549         if(!EncoderSession_process(e, buffer, (unsigned)n)) {
2550                 print_error_with_state(e, "ERROR during encoding");
2551                 data->fatal_error = true;
2552                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2553         }
2554
2555         data->samples_left_to_process -= n;
2556         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2557 }
2558
2559 void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
2560 {
2561         EncoderSession *e = (EncoderSession*)client_data;
2562     FLACDecoderData *data = &e->fmt.flac.client_data;
2563         (void)decoder;
2564
2565         if (data->fatal_error)
2566                 return;
2567
2568         if (
2569                 data->num_metadata_blocks == sizeof(data->metadata_blocks)/sizeof(data->metadata_blocks[0]) ||
2570                 0 == (data->metadata_blocks[data->num_metadata_blocks] = FLAC__metadata_object_clone(metadata))
2571         )
2572                 data->fatal_error = true;
2573         else
2574                 data->num_metadata_blocks++;
2575 }
2576
2577 void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
2578 {
2579         EncoderSession *e = (EncoderSession*)client_data;
2580     FLACDecoderData *data = &e->fmt.flac.client_data;
2581         (void)decoder;
2582
2583         stats_print_name(1, e->inbasefilename);
2584         flac__utils_printf(stderr, 1, "ERROR got %s while decoding FLAC input\n", FLAC__StreamDecoderErrorStatusString[status]);
2585         if(!e->continue_through_decode_errors)
2586                 data->fatal_error = true;
2587 }
2588
2589 FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, unsigned sample_rate, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors)
2590 {
2591         FILE *f;
2592         unsigned last_line_read;
2593         const char *error_message;
2594
2595         if(0 == cuesheet_filename)
2596                 return true;
2597
2598         if(lead_out_offset == 0) {
2599                 flac__utils_printf(stderr, 1, "%s: ERROR cannot import cuesheet when the number of input samples to encode is unknown\n", inbasefilename);
2600                 return false;
2601         }
2602
2603         if(0 == (f = flac_fopen(cuesheet_filename, "r"))) {
2604                 flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading: %s\n", inbasefilename, cuesheet_filename, strerror(errno));
2605                 return false;
2606         }
2607
2608         *cuesheet = grabbag__cuesheet_parse(f, &error_message, &last_line_read, sample_rate, is_cdda, lead_out_offset);
2609
2610         fclose(f);
2611
2612         if(0 == *cuesheet) {
2613                 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\" on line %u: %s\n", inbasefilename, cuesheet_filename, last_line_read, error_message);
2614                 return false;
2615         }
2616
2617         if(!FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/false, &error_message)) {
2618                 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\": %s\n", inbasefilename, cuesheet_filename, error_message);
2619                 return false;
2620         }
2621
2622         /* if we're expecting CDDA, warn about non-compliance */
2623         if(is_cdda && !FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/true, &error_message)) {
2624                 flac__utils_printf(stderr, 1, "%s: WARNING cuesheet \"%s\" is not audio CD compliant: %s\n", inbasefilename, cuesheet_filename, error_message);
2625                 if(treat_warnings_as_errors)
2626                         return false;
2627                 (*cuesheet)->data.cue_sheet.is_cd = false;
2628         }
2629
2630         return true;
2631 }
2632
2633 static void print_stats(const EncoderSession *encoder_session)
2634 {
2635         if(flac__utils_verbosity_ >= 2) {
2636                 char ratiostr[16];
2637
2638                 FLAC__ASSERT(encoder_session->total_samples_to_encode > 0);
2639
2640                 if (encoder_session->compression_ratio > 0.0)
2641                         flac_snprintf(ratiostr, sizeof(ratiostr), "%0.3f", encoder_session->compression_ratio);
2642                 else
2643                         flac_snprintf(ratiostr, sizeof(ratiostr), "N/A");
2644
2645                 if(encoder_session->samples_written == encoder_session->total_samples_to_encode) {
2646                         stats_print_name(2, encoder_session->inbasefilename);
2647                         stats_print_info(2, "%swrote %" PRIu64 " bytes, ratio=%s",
2648                                 encoder_session->verify? "Verify OK, " : "",
2649                                 encoder_session->bytes_written,
2650                                 ratiostr
2651                         );
2652                 }
2653                 else {
2654                         stats_print_name(2, encoder_session->inbasefilename);
2655                         stats_print_info(2, "%u%% complete, ratio=%s", (unsigned)floor(encoder_session->progress * 100.0 + 0.5), ratiostr);
2656                 }
2657         }
2658 }
2659
2660 void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status)
2661 {
2662         const int ilen = strlen(e->inbasefilename) + 1;
2663         const char *state_string = "";
2664
2665         flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2666
2667         flac__utils_printf(stderr, 1, "%*s init_status = %s\n", ilen, "", FLAC__StreamEncoderInitStatusString[init_status]);
2668
2669         if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR) {
2670                 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
2671
2672                 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2673
2674                 /* print out some more info for some errors: */
2675                 if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
2676                         flac__utils_printf(stderr, 1,
2677                                 "\n"
2678                                 "An error occurred while writing; the most common cause is that the disk is full.\n"
2679                         );
2680                 }
2681                 else if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_IO_ERROR])) {
2682                         flac__utils_printf(stderr, 1,
2683                                 "\n"
2684                                 "An error occurred opening the output file; it is likely that the output\n"
2685                                 "directory does not exist or is not writable, the output file already exists and\n"
2686                                 "is not writable, or the disk is full.\n"
2687                         );
2688                 }
2689         }
2690         else if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE) {
2691                 flac__utils_printf(stderr, 1,
2692                         "\n"
2693                         "The encoding parameters specified do not conform to the FLAC Subset and may not\n"
2694                         "be streamable or playable in hardware devices.  If you really understand the\n"
2695                         "consequences, you can add --lax to the command-line options to encode with\n"
2696                         "these parameters anyway.  See http://xiph.org/flac/format.html#subset\n"
2697                 );
2698         }
2699 }
2700
2701 void print_error_with_state(const EncoderSession *e, const char *message)
2702 {
2703         const int ilen = strlen(e->inbasefilename) + 1;
2704         const char *state_string;
2705
2706         flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2707
2708         state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
2709
2710         flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2711
2712         /* print out some more info for some errors: */
2713         if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
2714                 flac__utils_printf(stderr, 1,
2715                         "\n"
2716                         "An error occurred while writing; the most common cause is that the disk is full.\n"
2717                 );
2718         }
2719 }
2720
2721 void print_verify_error(EncoderSession *e)
2722 {
2723         FLAC__uint64 absolute_sample;
2724         unsigned frame_number;
2725         unsigned channel;
2726         unsigned sample;
2727         FLAC__int32 expected;
2728         FLAC__int32 got;
2729
2730         FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2731
2732         flac__utils_printf(stderr, 1, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
2733         flac__utils_printf(stderr, 1, "       Absolute sample=%" PRIu64 ", frame=%u, channel=%u, sample=%u, expected %d, got %d\n", absolute_sample, frame_number, channel, sample, expected, got);
2734         flac__utils_printf(stderr, 1, "       In all known cases, verify errors are caused by hardware problems,\n");
2735         flac__utils_printf(stderr, 1, "       usually overclocking or bad RAM.  Delete %s\n", e->outfilename);
2736         flac__utils_printf(stderr, 1, "       and repeat the flac command exactly as before.  If it does not give a\n");
2737         flac__utils_printf(stderr, 1, "       verify error in the exact same place each time you try it, then there is\n");
2738         flac__utils_printf(stderr, 1, "       a problem with your hardware; please see the FAQ:\n");
2739         flac__utils_printf(stderr, 1, "           http://xiph.org/flac/faq.html#tools__hardware_prob\n");
2740         flac__utils_printf(stderr, 1, "       If it does fail in the exact same place every time, keep\n");
2741         flac__utils_printf(stderr, 1, "       %s and submit a bug report to:\n", e->outfilename);
2742         flac__utils_printf(stderr, 1, "           https://sourceforge.net/p/flac/bugs/\n");
2743         flac__utils_printf(stderr, 1, "       Make sure to upload the FLAC file and use the \"Monitor\" feature to\n");
2744         flac__utils_printf(stderr, 1, "       monitor the bug status.\n");
2745         flac__utils_printf(stderr, 1, "Verify FAILED!  Do not trust %s\n", e->outfilename);
2746 }
2747
2748 FLAC__bool read_bytes(FILE *f, FLAC__byte *buf, size_t n, FLAC__bool eof_ok, const char *fn)
2749 {
2750         size_t bytes_read = fread(buf, 1, n, f);
2751
2752         if(bytes_read == 0) {
2753                 if(!eof_ok) {
2754                         flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2755                         return false;
2756                 }
2757                 else
2758                         return true;
2759         }
2760         if(bytes_read < n) {
2761                 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2762                 return false;
2763         }
2764         return true;
2765 }
2766
2767 FLAC__bool read_uint16(FILE *f, FLAC__bool big_endian, FLAC__uint16 *val, const char *fn)
2768 {
2769         if(!read_bytes(f, (FLAC__byte*)val, 2, /*eof_ok=*/false, fn))
2770                 return false;
2771         if(is_big_endian_host_ != big_endian) {
2772                 FLAC__byte tmp, *b = (FLAC__byte*)val;
2773                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
2774         }
2775         return true;
2776 }
2777
2778 FLAC__bool read_uint32(FILE *f, FLAC__bool big_endian, FLAC__uint32 *val, const char *fn)
2779 {
2780         if(!read_bytes(f, (FLAC__byte*)val, 4, /*eof_ok=*/false, fn))
2781                 return false;
2782         if(is_big_endian_host_ != big_endian) {
2783                 FLAC__byte tmp, *b = (FLAC__byte*)val;
2784                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
2785                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
2786         }
2787         return true;
2788 }
2789
2790 FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn)
2791 {
2792         if(!read_bytes(f, (FLAC__byte*)val, 8, /*eof_ok=*/false, fn))
2793                 return false;
2794         if(is_big_endian_host_ != big_endian) {
2795                 FLAC__byte tmp, *b = (FLAC__byte*)val;
2796                 tmp = b[7]; b[7] = b[0]; b[0] = tmp;
2797                 tmp = b[6]; b[6] = b[1]; b[1] = tmp;
2798                 tmp = b[5]; b[5] = b[2]; b[2] = tmp;
2799                 tmp = b[4]; b[4] = b[3]; b[3] = tmp;
2800         }
2801         return true;
2802 }
2803
2804 FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn)
2805         /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
2806          * convert it into an integral value and store in 'val'.  Return false if only
2807          * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f', or if the
2808          * value is negative, between zero and one, or too large to be represented by
2809          * 'val'; return true otherwise.
2810          */
2811 {
2812         unsigned int i;
2813         FLAC__byte buf[10];
2814         FLAC__uint64 p = 0;
2815         FLAC__int16 e;
2816         FLAC__int16 shift;
2817
2818         if(!read_bytes(f, buf, sizeof(buf), /*eof_ok=*/false, fn))
2819                 return false;
2820         e = ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
2821         shift = 63-e;
2822         if((buf[0]>>7)==1U || e<0 || e>63) {
2823                 flac__utils_printf(stderr, 1, "%s: ERROR: invalid floating-point value\n", fn);
2824                 return false;
2825         }
2826
2827         for(i = 0; i < 8; ++i)
2828                 p |= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
2829         *val = (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1));
2830
2831         return true;
2832 }
2833
2834 FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset)
2835 {
2836         static unsigned char dump[8192];
2837         struct flac_stat_s stb;
2838
2839         if(flac_fstat(fileno(f), &stb) == 0 && (stb.st_mode & S_IFMT) == S_IFREG)
2840         {
2841                 if(fseeko(f, offset, SEEK_CUR) == 0)
2842                         return true;
2843         }
2844         while(offset > 0) {
2845                 const long need = (long)min(offset, sizeof(dump));
2846                 if((long)fread(dump, 1, need, f) < need)
2847                         return false;
2848                 offset -= need;
2849         }
2850         return true;
2851 }
2852
2853 unsigned count_channel_mask_bits(FLAC__uint32 mask)
2854 {
2855         unsigned count = 0;
2856         while(mask) {
2857                 if(mask & 1)
2858                         count++;
2859                 mask >>= 1;
2860         }
2861         return count;
2862 }
2863
2864 #if 0
2865 FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels)
2866 {
2867         FLAC__uint32 x = 0x80000000;
2868         unsigned count = count_channel_mask_bits(mask);
2869         while(x && count > channels) {
2870                 if(mask & x) {
2871                         mask &= ~x;
2872                         count--;
2873                 }
2874                 x >>= 1;
2875         }
2876         FLAC__ASSERT(count_channel_mask_bits(mask) == channels);
2877         return mask;
2878 }
2879 #endif