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