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