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