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