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