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