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