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