OSDN Git Service

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