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