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