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