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