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