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