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