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