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