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