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