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