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