fix bug where some Ogg-relative stuff was not #ifdef'ed
[flac.git] / src / flac / encode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001,2002,2003  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 defined _WIN32 && !defined __CYGWIN__
20 /* where MSVC puts unlink() */
21 # include <io.h>
22 #else
23 # include <unistd.h>
24 #endif
25 #include <limits.h> /* for LONG_MAX */
26 #include <math.h> /* for floor() */
27 #include <stdarg.h>
28 #include <stdio.h> /* for FILE etc. */
29 #include <stdlib.h> /* for malloc */
30 #include <string.h> /* for strcmp() */
31 #include "FLAC/all.h"
32 #include "share/grabbag.h"
33 #include "encode.h"
34
35 #ifdef HAVE_CONFIG_H
36 #include <config.h>
37 #endif
38
39 #ifdef FLAC__HAS_OGG
40 #include "OggFLAC/stream_encoder.h"
41 #endif
42
43 #ifdef min
44 #undef min
45 #endif
46 #define min(x,y) ((x)<(y)?(x):(y))
47
48 /* this MUST be >= 588 so that sector aligning can take place with one read */
49 #define CHUNK_OF_SAMPLES 2048
50
51 typedef struct {
52 #ifdef FLAC__HAS_OGG
53         FLAC__bool use_ogg;
54 #endif
55         FLAC__bool verify;
56         FLAC__bool verbose;
57         FLAC__bool is_stdout;
58         const char *inbasefilename;
59         const char *outfilename;
60
61         FLAC__uint64 skip;
62         FLAC__uint64 until; /* a value of 0 mean end-of-stream (i.e. --until=-0) */
63         FLAC__bool replay_gain;
64         unsigned channels;
65         unsigned bits_per_sample;
66         unsigned sample_rate;
67         FLAC__uint64 unencoded_size;
68         FLAC__uint64 total_samples_to_encode;
69         FLAC__uint64 bytes_written;
70         FLAC__uint64 samples_written;
71         unsigned blocksize;
72         unsigned stats_mask;
73
74         /*
75          * We use flac.stream for encoding native FLAC to stdout
76          * We use flac.file for encoding native FLAC to a regular file
77          * We use ogg.stream for encoding Ogg FLAC to either stdout or a regular file
78          */
79         union {
80                 union {
81                         FLAC__StreamEncoder *stream;
82                         FLAC__FileEncoder *file;
83                 } flac;
84 #ifdef FLAC__HAS_OGG
85                 union {
86                         OggFLAC__StreamEncoder *stream;
87                 } ogg;
88 #endif
89         } encoder;
90
91         FILE *fin;
92         FILE *fout;
93         FLAC__StreamMetadata *seek_table_template;
94 } EncoderSession;
95
96
97 static FLAC__bool is_big_endian_host_;
98
99 static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
100 static signed char *scbuffer_ = (signed char *)ucbuffer_;
101 static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_;
102 static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_;
103
104 static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
105 static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
106
107
108 /*
109  * unpublished debug routines from the FLAC libs
110  */
111 extern FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
112 extern FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
113 extern FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
114 extern FLAC__bool FLAC__file_encoder_disable_constant_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
115 extern FLAC__bool FLAC__file_encoder_disable_fixed_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
116 extern FLAC__bool FLAC__file_encoder_disable_verbatim_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
117 #ifdef FLAC__HAS_OGG
118 extern FLAC__bool OggFLAC__stream_encoder_disable_constant_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
119 extern FLAC__bool OggFLAC__stream_encoder_disable_fixed_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
120 extern FLAC__bool OggFLAC__stream_encoder_disable_verbatim_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
121 #endif
122
123 /*
124  * local routines
125  */
126 static FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FLAC__bool verbose, FILE *infile, const char *infilename, const char *outfilename);
127 static void EncoderSession_destroy(EncoderSession *e);
128 static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero);
129 static int EncoderSession_finish_error(EncoderSession *e);
130 static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate);
131 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
132 static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
133 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
134 static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps);
135 #ifdef FLAC__HAS_OGG
136 static FLAC__StreamEncoderWriteStatus ogg_stream_encoder_write_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
137 #endif
138 static FLAC__StreamEncoderWriteStatus flac_stream_encoder_write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
139 static void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
140 static void flac_file_encoder_progress_callback(const FLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
141 static FLAC__bool parse_cuesheet_(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__uint64 lead_out_offset);
142 static void print_stats(const EncoderSession *encoder_session);
143 static void print_error_with_state(const EncoderSession *e, const char *message);
144 static void print_verify_error(EncoderSession *e);
145 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
146 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
147 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
148 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
149 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
150
151 /*
152  * public routines
153  */
154 int
155 flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const char *outfilename,
156         const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
157 {
158         EncoderSession encoder_session;
159         FLAC__uint16 x;
160         FLAC__uint32 xx;
161         unsigned int channels= 0U, bps= 0U, sample_rate= 0U, sample_frames= 0U;
162         FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
163         int info_align_carry= -1, info_align_zero= -1;
164
165         (void)infilesize; /* silence compiler warning about unused parameter */
166         (void)lookahead; /* silence compiler warning about unused parameter */
167         (void)lookahead_length; /* silence compiler warning about unused parameter */
168
169         if(!
170                 EncoderSession_construct(
171                         &encoder_session,
172 #ifdef FLAC__HAS_OGG
173                         options.common.use_ogg,
174 #else
175                         /*use_ogg=*/false,
176 #endif
177                         options.common.verify,
178                         options.common.verbose,
179                         infile,
180                         infilename,
181                         outfilename
182                 )
183         )
184                 return 1;
185
186         /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
187
188         while(1) {
189                 size_t c= 0U;
190                 char chunk_id[4];
191
192                 /* chunk identifier; really conservative about behavior of fread() and feof() */
193                 if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
194                         break;
195                 else if(c<4U || feof(infile)) {
196                         fprintf(stderr, "%s: ERROR: incomplete chunk identifier\n", encoder_session.inbasefilename);
197                         return EncoderSession_finish_error(&encoder_session);
198                 }
199
200                 if(got_comm_chunk==false && !strncmp(chunk_id, "COMM", 4)) { /* common chunk */
201                         unsigned long skip;
202
203                         /* COMM chunk size */
204                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
205                                 return EncoderSession_finish_error(&encoder_session);
206                         else if(xx<18U) {
207                                 fprintf(stderr, "%s: ERROR: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
208                                 return EncoderSession_finish_error(&encoder_session);
209                         }
210                         else if(xx!=18U)
211                                 fprintf(stderr, "%s: WARNING: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
212                         skip= (xx-18U)+(xx & 1U);
213
214                         /* number of channels */
215                         if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
216                                 return EncoderSession_finish_error(&encoder_session);
217                         else if(x==0U || x>FLAC__MAX_CHANNELS) {
218                                 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned int)x);
219                                 return EncoderSession_finish_error(&encoder_session);
220                         }
221                         else if(options.common.sector_align && x!=2U) {
222                                 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
223                                 return EncoderSession_finish_error(&encoder_session);
224                         }
225                         channels= x;
226
227                         /* number of sample frames */
228                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
229                                 return EncoderSession_finish_error(&encoder_session);
230                         sample_frames= xx;
231
232                         /* bits per sample */
233                         if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
234                                 return EncoderSession_finish_error(&encoder_session);
235                         else if(x!=8U && x!=16U && x!=24U) {
236                                 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_session.inbasefilename, (unsigned int)x);
237                                 return EncoderSession_finish_error(&encoder_session);
238                         }
239                         else if(options.common.sector_align && x!=16U) {
240                                 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
241                                 return EncoderSession_finish_error(&encoder_session);
242                         }
243                         bps= x;
244
245                         /* sample rate */
246                         if(!read_sane_extended(infile, &xx, false, encoder_session.inbasefilename))
247                                 return EncoderSession_finish_error(&encoder_session);
248                         else if(!FLAC__format_sample_rate_is_valid(xx)) {
249                                 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned int)xx);
250                                 return EncoderSession_finish_error(&encoder_session);
251                         }
252                         else if(options.common.sector_align && xx!=44100U) {
253                                 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)xx);
254                                 return EncoderSession_finish_error(&encoder_session);
255                         }
256                         sample_rate= xx;
257
258                         /* skip any extra data in the COMM chunk */
259                         FLAC__ASSERT(skip<=LONG_MAX);
260                         while(skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
261                                 unsigned int need= min(skip, sizeof ucbuffer_);
262                                 if(fread(ucbuffer_, 1U, need, infile)<need) {
263                                         fprintf(stderr, "%s: ERROR during read while skipping extra COMM data\n", encoder_session.inbasefilename);
264                                         return EncoderSession_finish_error(&encoder_session);
265                                 }
266                                 skip-= need;
267                         }
268
269                         /*
270                          * now that we know the sample rate, canonicalize the
271                          * --skip string to a number of samples:
272                          */
273                         flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, sample_rate);
274                         FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
275                         encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
276                         FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
277
278                         got_comm_chunk= true;
279                 }
280                 else if(got_ssnd_chunk==false && !strncmp(chunk_id, "SSND", 4)) { /* sound data chunk */
281                         unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
282                         size_t bytes_per_frame= channels*(bps>>3);
283                         FLAC__uint64 total_samples_in_input, trim = 0;
284                         FLAC__bool pad= false;
285
286                         if(got_comm_chunk==false) {
287                                 fprintf(stderr, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", encoder_session.inbasefilename);
288                                 return EncoderSession_finish_error(&encoder_session);
289                         }
290
291                         /* SSND chunk size */
292                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
293                                 return EncoderSession_finish_error(&encoder_session);
294                         else if(xx!=(sample_frames*bytes_per_frame + 8U)) {
295                                 fprintf(stderr, "%s: ERROR: SSND chunk size inconsistent with sample frame count\n", encoder_session.inbasefilename);
296                                 return EncoderSession_finish_error(&encoder_session);
297                         }
298                         data_bytes= xx;
299                         pad= (data_bytes & 1U) ? true : false;
300                         data_bytes-= 8U; /* discount the offset and block size fields */
301
302                         /* offset */
303                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
304                                 return EncoderSession_finish_error(&encoder_session);
305                         else if(xx!=0U) {
306                                 fprintf(stderr, "%s: ERROR: offset is %u; must be 0\n", encoder_session.inbasefilename, (unsigned int)xx);
307                                 return EncoderSession_finish_error(&encoder_session);
308                         }
309                         offset= xx;
310
311                         /* block size */
312                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
313                                 return EncoderSession_finish_error(&encoder_session);
314                         else if(xx!=0U) {
315                                 fprintf(stderr, "%s: ERROR: block size is %u; must be 0\n", encoder_session.inbasefilename, (unsigned int)xx);
316                                 return EncoderSession_finish_error(&encoder_session);
317                         }
318                         block_size= xx;
319
320                         /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
321                         FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
322                         total_samples_in_input = data_bytes / bytes_per_frame + *options.common.align_reservoir_samples;
323
324                         /*
325                          * now that we know the input size, canonicalize the
326                          * --until string to an absolute sample number:
327                          */
328                         if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, sample_rate, encoder_session.skip, total_samples_in_input))
329                                 return EncoderSession_finish_error(&encoder_session);
330                         encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
331                         FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
332
333                         if(encoder_session.skip>0U) {
334                                 FLAC__uint64 remaining= encoder_session.skip*bytes_per_frame;
335
336                                 /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
337                                 /* is guaranteed to be less than LONG_MAX */
338                                 while(remaining>0U)
339                                 {
340                                         unsigned long skip= (unsigned long)(remaining % (1U<<30));
341
342                                         FLAC__ASSERT(skip<=LONG_MAX);
343                                         while(skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
344                                                 unsigned int need= min(skip, sizeof ucbuffer_);
345                                                 if(fread(ucbuffer_, 1U, need, infile)<need) {
346                                                         fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
347                                                         return EncoderSession_finish_error(&encoder_session);
348                                                 }
349                                                 skip-= need;
350                                         }
351
352                                         remaining-= skip;
353                                 }
354                         }
355
356                         data_bytes-= (unsigned int)encoder_session.skip*bytes_per_frame; /*@@@ WATCHOUT: 4GB limit */
357                         encoder_session.total_samples_to_encode= total_samples_in_input - encoder_session.skip;
358                         if(encoder_session.until > 0) {
359                                 trim = total_samples_in_input - encoder_session.until;
360                                 FLAC__ASSERT(total_samples_in_input > 0);
361                                 FLAC__ASSERT(!options.common.sector_align);
362                                 data_bytes-= (unsigned int)trim*bytes_per_frame;
363                                 encoder_session.total_samples_to_encode-= trim;
364                         }
365                         if(options.common.sector_align) {
366                                 align_remainder= (unsigned int)(encoder_session.total_samples_to_encode % 588U);
367                                 if(options.common.is_last_file)
368                                         encoder_session.total_samples_to_encode+= (588U-align_remainder); /* will pad with zeroes */
369                                 else
370                                         encoder_session.total_samples_to_encode-= align_remainder; /* will stop short and carry over to next file */
371                         }
372
373                         /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
374                         encoder_session.unencoded_size= encoder_session.total_samples_to_encode*bytes_per_frame+54;
375
376                         if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
377                                 return EncoderSession_finish_error(&encoder_session);
378
379                         /* first do any samples in the reservoir */
380                         if(options.common.sector_align && *options.common.align_reservoir_samples>0U) {
381
382                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
383                                         print_error_with_state(&encoder_session, "ERROR during encoding");
384                                         return EncoderSession_finish_error(&encoder_session);
385                                 }
386                         }
387
388                         /* decrement the data_bytes counter if we need to align the file */
389                         if(options.common.sector_align) {
390                                 if(options.common.is_last_file)
391                                         *options.common.align_reservoir_samples= 0U;
392                                 else {
393                                         *options.common.align_reservoir_samples= align_remainder;
394                                         data_bytes-= (*options.common.align_reservoir_samples)*bytes_per_frame;
395                                 }
396                         }
397
398                         /* now do from the file */
399                         while(data_bytes>0) {
400                                 size_t bytes_read= fread(ucbuffer_, 1U, min(data_bytes, CHUNK_OF_SAMPLES*bytes_per_frame), infile);
401
402                                 if(bytes_read==0U) {
403                                         if(ferror(infile)) {
404                                                 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
405                                                 return EncoderSession_finish_error(&encoder_session);
406                                         }
407                                         else if(feof(infile)) {
408                                                 fprintf(stderr, "%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);
409                                                 data_bytes= 0;
410                                         }
411                                 }
412                                 else {
413                                         if(bytes_read % bytes_per_frame != 0U) {
414                                                 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
415                                                 return EncoderSession_finish_error(&encoder_session);
416                                         }
417                                         else {
418                                                 unsigned int frames= bytes_read/bytes_per_frame;
419                                                 format_input(input_, frames, true, false, channels, bps);
420
421                                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, frames)) {
422                                                         print_error_with_state(&encoder_session, "ERROR during encoding");
423                                                         return EncoderSession_finish_error(&encoder_session);
424                                                 }
425                                                 else
426                                                         data_bytes-= bytes_read;
427                                         }
428                                 }
429                         }
430
431                         if(trim>0) {
432                                 FLAC__uint64 remaining= (unsigned int)trim*bytes_per_frame;
433
434                                 FLAC__ASSERT(!options.common.sector_align);
435
436                                 /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
437                                 /* is guaranteed to be less than LONG_MAX */
438                                 while(remaining>0U)
439                                 {
440                                         unsigned long skip= (unsigned long)(remaining % (1U<<30));
441
442                                         FLAC__ASSERT(skip<=LONG_MAX);
443                                         while(skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
444                                                 unsigned int need= min(skip, sizeof ucbuffer_);
445                                                 if(fread(ucbuffer_, 1U, need, infile)<need) {
446                                                         fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
447                                                         return EncoderSession_finish_error(&encoder_session);
448                                                 }
449                                                 skip-= need;
450                                         }
451
452                                         remaining-= skip;
453                                 }
454                         }
455
456                         /* now read unaligned samples into reservoir or pad with zeroes if necessary */
457                         if(options.common.sector_align) {
458                                 if(options.common.is_last_file) {
459                                         unsigned int pad_frames= 588U-align_remainder;
460
461                                         if(pad_frames<588U) {
462                                                 unsigned int i;
463
464                                                 info_align_zero= pad_frames;
465                                                 for(i= 0U; i<channels; ++i)
466                                                         memset(input_[i], 0, pad_frames*(bps>>3));
467
468                                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, pad_frames)) {
469                                                         print_error_with_state(&encoder_session, "ERROR during encoding");
470                                                         return EncoderSession_finish_error(&encoder_session);
471                                                 }
472                                         }
473                                 }
474                                 else {
475                                         if(*options.common.align_reservoir_samples > 0) {
476                                                 size_t bytes_read= fread(ucbuffer_, 1U, (*options.common.align_reservoir_samples)*bytes_per_frame, infile);
477
478                                                 FLAC__ASSERT(CHUNK_OF_SAMPLES>=588U);
479                                                 if(bytes_read==0U && ferror(infile)) {
480                                                         fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
481                                                         return EncoderSession_finish_error(&encoder_session);
482                                                 }
483                                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame)
484                                                         fprintf(stderr, "%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);
485                                                 else {
486                                                         info_align_carry= *options.common.align_reservoir_samples;
487                                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, true, false, channels, bps);
488                                                 }
489                                         }
490                                 }
491                         }
492
493                         if(pad==true) {
494                                 unsigned char tmp;
495
496                                 if(fread(&tmp, 1U, 1U, infile)<1U) {
497                                         fprintf(stderr, "%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(!strncmp(chunk_id, "COMM", 4))
506                                 fprintf(stderr, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_session.inbasefilename);
507                         else if(!strncmp(chunk_id, "SSND", 4))
508                                 fprintf(stderr, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_session.inbasefilename);
509                         else
510                                 fprintf(stderr, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_session.inbasefilename, chunk_id);
511
512                         /* chunk size */
513                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
514                                 return EncoderSession_finish_error(&encoder_session);
515                         else {
516                                 unsigned long skip= xx+(xx & 1U);
517
518                                 FLAC__ASSERT(skip<=LONG_MAX);
519                                 while(skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
520                                         unsigned int need= min(skip, sizeof ucbuffer_);
521                                         if(fread(ucbuffer_, 1U, need, infile)<need) {
522                                                 fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_session.inbasefilename);
523                                                 return EncoderSession_finish_error(&encoder_session);
524                                         }
525                                         skip-= need;
526                                 }
527                         }
528                 }
529         }
530
531         if(got_ssnd_chunk==false && sample_frames!=0U) {
532                 fprintf(stderr, "%s: ERROR: missing SSND chunk\n", encoder_session.inbasefilename);
533                 return EncoderSession_finish_error(&encoder_session);
534         }
535
536         return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
537 }
538
539 int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
540 {
541         EncoderSession encoder_session;
542         FLAC__bool is_unsigned_samples = false;
543         unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
544         size_t bytes_per_wide_sample, bytes_read;
545         FLAC__uint16 x;
546         FLAC__uint32 xx;
547         FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
548         unsigned align_remainder = 0;
549         int info_align_carry = -1, info_align_zero = -1;
550
551         (void)infilesize;
552         (void)lookahead;
553         (void)lookahead_length;
554
555         if(!
556                 EncoderSession_construct(
557                         &encoder_session,
558 #ifdef FLAC__HAS_OGG
559                         options.common.use_ogg,
560 #else
561                         /*use_ogg=*/false,
562 #endif
563                         options.common.verify,
564                         options.common.verbose,
565                         infile,
566                         infilename,
567                         outfilename
568                 )
569         )
570                 return 1;
571
572         /*
573          * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
574          */
575         while(!feof(infile)) {
576                 if(!read_little_endian_uint32(infile, &xx, true, encoder_session.inbasefilename))
577                         return EncoderSession_finish_error(&encoder_session);
578                 if(feof(infile))
579                         break;
580                 if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
581                         /* fmt sub-chunk size */
582                         if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
583                                 return EncoderSession_finish_error(&encoder_session);
584                         if(xx < 16) {
585                                 fprintf(stderr, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
586                                 return EncoderSession_finish_error(&encoder_session);
587                         }
588                         else if(xx != 16 && xx != 18) {
589                                 fprintf(stderr, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
590                         }
591                         data_bytes = xx;
592                         /* compression code */
593                         if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
594                                 return EncoderSession_finish_error(&encoder_session);
595                         if(x != 1) {
596                                 fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_session.inbasefilename, (unsigned)x);
597                                 return EncoderSession_finish_error(&encoder_session);
598                         }
599                         /* number of channels */
600                         if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
601                                 return EncoderSession_finish_error(&encoder_session);
602                         if(x == 0 || x > FLAC__MAX_CHANNELS) {
603                                 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned)x);
604                                 return EncoderSession_finish_error(&encoder_session);
605                         }
606                         else if(options.common.sector_align && x != 2) {
607                                 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
608                                 return EncoderSession_finish_error(&encoder_session);
609                         }
610                         channels = x;
611                         /* sample rate */
612                         if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
613                                 return EncoderSession_finish_error(&encoder_session);
614                         if(!FLAC__format_sample_rate_is_valid(xx)) {
615                                 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned)xx);
616                                 return EncoderSession_finish_error(&encoder_session);
617                         }
618                         else if(options.common.sector_align && xx != 44100) {
619                                 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned)xx);
620                                 return EncoderSession_finish_error(&encoder_session);
621                         }
622                         sample_rate = xx;
623                         /* avg bytes per second (ignored) */
624                         if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
625                                 return EncoderSession_finish_error(&encoder_session);
626                         /* block align (ignored) */
627                         if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
628                                 return EncoderSession_finish_error(&encoder_session);
629                         /* bits per sample */
630                         if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
631                                 return EncoderSession_finish_error(&encoder_session);
632                         if(x != 8 && x != 16 && x != 24) {
633                                 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_session.inbasefilename, (unsigned)x);
634                                 return EncoderSession_finish_error(&encoder_session);
635                         }
636                         else if(options.common.sector_align && x != 16) {
637                                 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
638                                 return EncoderSession_finish_error(&encoder_session);
639                         }
640                         bps = x;
641                         is_unsigned_samples = (x == 8);
642
643                         /* skip any extra data in the fmt sub-chunk */
644                         data_bytes -= 16;
645                         if(data_bytes > 0) {
646                                 unsigned left, need;
647                                 for(left = data_bytes; left > 0; ) {
648                                         need = min(left, CHUNK_OF_SAMPLES);
649                                         if(fread(ucbuffer_, 1U, need, infile) < need) {
650                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
651                                                 return EncoderSession_finish_error(&encoder_session);
652                                         }
653                                         left -= need;
654                                 }
655                         }
656
657                         /*
658                          * now that we know the sample rate, canonicalize the
659                          * --skip string to a number of samples:
660                          */
661                         flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, sample_rate);
662                         FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
663                         encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
664                         FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
665
666                         got_fmt_chunk = true;
667                 }
668                 else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
669                         FLAC__uint64 total_samples_in_input, trim = 0;
670
671                         /* data size */
672                         if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
673                                 return EncoderSession_finish_error(&encoder_session);
674                         data_bytes = xx;
675
676                         bytes_per_wide_sample = channels * (bps >> 3);
677
678                         /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
679                         FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
680                         total_samples_in_input = data_bytes / bytes_per_wide_sample + *options.common.align_reservoir_samples;
681
682                         /*
683                          * now that we know the input size, canonicalize the
684                          * --until string to an absolute sample number:
685                          */
686                         if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, sample_rate, encoder_session.skip, total_samples_in_input))
687                                 return EncoderSession_finish_error(&encoder_session);
688                         encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
689                         FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
690
691                         if(encoder_session.skip > 0) {
692                                 if(fseek(infile, bytes_per_wide_sample * (unsigned)encoder_session.skip, SEEK_CUR) < 0) {
693                                         /* can't seek input, read ahead manually... */
694                                         unsigned left, need;
695                                         for(left = (unsigned)encoder_session.skip; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
696                                                 need = min(left, CHUNK_OF_SAMPLES);
697                                                 if(fread(ucbuffer_, bytes_per_wide_sample, need, infile) < need) {
698                                                         fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
699                                                         return EncoderSession_finish_error(&encoder_session);
700                                                 }
701                                                 left -= need;
702                                         }
703                                 }
704                         }
705
706                         data_bytes -= (unsigned)encoder_session.skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
707                         encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
708                         if(encoder_session.until > 0) {
709                                 trim = total_samples_in_input - encoder_session.until;
710                                 FLAC__ASSERT(total_samples_in_input > 0);
711                                 FLAC__ASSERT(!options.common.sector_align);
712                                 data_bytes -= (unsigned int)trim * bytes_per_wide_sample;
713                                 encoder_session.total_samples_to_encode -= trim;
714                         }
715                         if(options.common.sector_align) {
716                                 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
717                                 if(options.common.is_last_file)
718                                         encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
719                                 else
720                                         encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
721                         }
722
723                         /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
724                         encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample + 44;
725
726                         if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
727                                 return EncoderSession_finish_error(&encoder_session);
728
729                         /*
730                          * first do any samples in the reservoir
731                          */
732                         if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
733                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
734                                         print_error_with_state(&encoder_session, "ERROR during encoding");
735                                         return EncoderSession_finish_error(&encoder_session);
736                                 }
737                         }
738
739                         /*
740                          * decrement the data_bytes counter if we need to align the file
741                          */
742                         if(options.common.sector_align) {
743                                 if(options.common.is_last_file) {
744                                         *options.common.align_reservoir_samples = 0;
745                                 }
746                                 else {
747                                         *options.common.align_reservoir_samples = align_remainder;
748                                         data_bytes -= (*options.common.align_reservoir_samples) * bytes_per_wide_sample;
749                                 }
750                         }
751
752                         /*
753                          * now do from the file
754                          */
755                         while(data_bytes > 0) {
756                                 bytes_read = fread(ucbuffer_, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
757                                 if(bytes_read == 0) {
758                                         if(ferror(infile)) {
759                                                 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
760                                                 return EncoderSession_finish_error(&encoder_session);
761                                         }
762                                         else if(feof(infile)) {
763                                                 fprintf(stderr, "%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);
764                                                 data_bytes = 0;
765                                         }
766                                 }
767                                 else {
768                                         if(bytes_read % bytes_per_wide_sample != 0) {
769                                                 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
770                                                 return EncoderSession_finish_error(&encoder_session);
771                                         }
772                                         else {
773                                                 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
774                                                 format_input(input_, wide_samples, false, is_unsigned_samples, channels, bps);
775
776                                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
777                                                         print_error_with_state(&encoder_session, "ERROR during encoding");
778                                                         return EncoderSession_finish_error(&encoder_session);
779                                                 }
780                                                 data_bytes -= bytes_read;
781                                         }
782                                 }
783                         }
784
785                         if(trim > 0) {
786                                 if(fseek(infile, bytes_per_wide_sample * (unsigned)trim, SEEK_CUR) < 0) {
787                                         /* can't seek input, read ahead manually... */
788                                         unsigned left, need;
789                                         for(left = (unsigned)trim; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
790                                                 need = min(left, CHUNK_OF_SAMPLES);
791                                                 if(fread(ucbuffer_, bytes_per_wide_sample, need, infile) < need) {
792                                                         fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
793                                                         return EncoderSession_finish_error(&encoder_session);
794                                                 }
795                                                 left -= need;
796                                         }
797                                 }
798                         }
799
800                         /*
801                          * now read unaligned samples into reservoir or pad with zeroes if necessary
802                          */
803                         if(options.common.sector_align) {
804                                 if(options.common.is_last_file) {
805                                         unsigned wide_samples = 588 - align_remainder;
806                                         if(wide_samples < 588) {
807                                                 unsigned channel;
808
809                                                 info_align_zero = wide_samples;
810                                                 data_bytes = wide_samples * (bps >> 3);
811                                                 for(channel = 0; channel < channels; channel++)
812                                                         memset(input_[channel], 0, data_bytes);
813
814                                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
815                                                         print_error_with_state(&encoder_session, "ERROR during encoding");
816                                                         return EncoderSession_finish_error(&encoder_session);
817                                                 }
818                                         }
819                                 }
820                                 else {
821                                         if(*options.common.align_reservoir_samples > 0) {
822                                                 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
823                                                 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
824                                                 if(bytes_read == 0 && ferror(infile)) {
825                                                         fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
826                                                         return EncoderSession_finish_error(&encoder_session);
827                                                 }
828                                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
829                                                         fprintf(stderr, "%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);
830                                                         data_bytes = 0;
831                                                 }
832                                                 else {
833                                                         info_align_carry = *options.common.align_reservoir_samples;
834                                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, is_unsigned_samples, channels, bps);
835                                                 }
836                                         }
837                                 }
838                         }
839
840                         got_data_chunk = true;
841                 }
842                 else {
843                         if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
844                                 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_session.inbasefilename);
845                         }
846                         else if(xx == 0x61746164) { /* "data" */
847                                 if(got_data_chunk) {
848                                         fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_session.inbasefilename);
849                                 }
850                                 else if(!got_fmt_chunk) {
851                                         fprintf(stderr, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_session.inbasefilename);
852                                         return EncoderSession_finish_error(&encoder_session);
853                                 }
854                                 else {
855                                         FLAC__ASSERT(0);
856                                 }
857                         }
858                         else {
859                                 fprintf(stderr, "%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));
860                         }
861                         /* sub-chunk size */
862                         if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
863                                 return EncoderSession_finish_error(&encoder_session);
864                         if(fseek(infile, xx, SEEK_CUR) < 0) {
865                                 /* can't seek input, read ahead manually... */
866                                 unsigned left, need;
867                                 const unsigned chunk = sizeof(ucbuffer_);
868                                 for(left = xx; left > 0; ) {
869                                         need = min(left, chunk);
870                                         if(fread(ucbuffer_, 1, need, infile) < need) {
871                                                 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_session.inbasefilename);
872                                                 return EncoderSession_finish_error(&encoder_session);
873                                         }
874                                         left -= need;
875                                 }
876                         }
877                 }
878         }
879
880         return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
881 }
882
883 int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, raw_encode_options_t options)
884 {
885         EncoderSession encoder_session;
886         size_t bytes_read;
887         const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
888         unsigned align_remainder = 0;
889         int info_align_carry = -1, info_align_zero = -1;
890         FLAC__uint64 total_samples_in_input = 0;;
891
892         FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
893         FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
894         FLAC__ASSERT(!options.common.sector_align || options.sample_rate == 44100);
895         FLAC__ASSERT(!options.common.sector_align || infilesize >= 0);
896         FLAC__ASSERT(!options.common.replay_gain || options.channels <= 2);
897         FLAC__ASSERT(!options.common.replay_gain || grabbag__replaygain_is_valid_sample_frequency(options.sample_rate));
898
899         if(!
900                 EncoderSession_construct(
901                         &encoder_session,
902 #ifdef FLAC__HAS_OGG
903                         options.common.use_ogg,
904 #else
905                         /*use_ogg=*/false,
906 #endif
907                         options.common.verify,
908                         options.common.verbose,
909                         infile,
910                         infilename,
911                         outfilename
912                 )
913         )
914                 return 1;
915
916         /*
917          * now that we know the sample rate, canonicalize the
918          * --skip string to a number of samples:
919          */
920         flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, options.sample_rate);
921         FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
922         encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
923         FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
924
925         if(infilesize < 0)
926                 total_samples_in_input = 0;
927         else {
928                 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
929                 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
930                 total_samples_in_input = (unsigned)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
931         }
932
933         /*
934          * now that we know the input size, canonicalize the
935          * --until strings to a number of samples:
936          */
937         if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, options.sample_rate, encoder_session.skip, total_samples_in_input))
938                 return EncoderSession_finish_error(&encoder_session);
939         encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
940         FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
941
942         encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
943         if(encoder_session.until > 0) {
944                 const FLAC__uint64 trim = total_samples_in_input - encoder_session.until;
945                 FLAC__ASSERT(total_samples_in_input > 0);
946                 FLAC__ASSERT(!options.common.sector_align);
947                 encoder_session.total_samples_to_encode -= trim;
948         }
949         if(infilesize >= 0 && options.common.sector_align) {
950                 FLAC__ASSERT(encoder_session.skip == 0);
951                 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
952                 if(options.common.is_last_file)
953                         encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
954                 else
955                         encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
956         }
957         encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample;
958
959         if(encoder_session.verbose && encoder_session.total_samples_to_encode <= 0)
960                 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
961
962         if(encoder_session.skip > 0) {
963                 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)encoder_session.skip;
964                 if(skip_bytes > lookahead_length) {
965                         skip_bytes -= lookahead_length;
966                         lookahead_length = 0;
967                         if(fseek(infile, (long)skip_bytes, SEEK_CUR) < 0) {
968                                 /* can't seek input, read ahead manually... */
969                                 unsigned left, need;
970                                 const unsigned chunk = sizeof(ucbuffer_);
971                                 for(left = skip_bytes; left > 0; ) {
972                                         need = min(left, chunk);
973                                         if(fread(ucbuffer_, 1, need, infile) < need) {
974                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
975                                                 return EncoderSession_finish_error(&encoder_session);
976                                         }
977                                         left -= need;
978                                 }
979                         }
980                 }
981                 else {
982                         lookahead += skip_bytes;
983                         lookahead_length -= skip_bytes;
984                 }
985         }
986
987         if(!EncoderSession_init_encoder(&encoder_session, options.common, options.channels, options.bps, options.sample_rate))
988                 return EncoderSession_finish_error(&encoder_session);
989
990         /*
991          * first do any samples in the reservoir
992          */
993         if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
994                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
995                         print_error_with_state(&encoder_session, "ERROR during encoding");
996                         return EncoderSession_finish_error(&encoder_session);
997                 }
998         }
999
1000         /*
1001          * decrement infilesize if we need to align the file
1002          */
1003         if(options.common.sector_align) {
1004                 FLAC__ASSERT(infilesize >= 0);
1005                 if(options.common.is_last_file) {
1006                         *options.common.align_reservoir_samples = 0;
1007                 }
1008                 else {
1009                         *options.common.align_reservoir_samples = align_remainder;
1010                         infilesize -= (long)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
1011                         FLAC__ASSERT(infilesize >= 0);
1012                 }
1013         }
1014
1015         /*
1016          * now do from the file
1017          */
1018         if(infilesize < 0) {
1019                 while(!feof(infile)) {
1020                         if(lookahead_length > 0) {
1021                                 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1022                                 memcpy(ucbuffer_, lookahead, lookahead_length);
1023                                 bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
1024                                 if(ferror(infile)) {
1025                                         fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
1026                                         return EncoderSession_finish_error(&encoder_session);
1027                                 }
1028                                 lookahead_length = 0;
1029                         }
1030                         else
1031                                 bytes_read = fread(ucbuffer_, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
1032
1033                         if(bytes_read == 0) {
1034                                 if(ferror(infile)) {
1035                                         fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
1036                                         return EncoderSession_finish_error(&encoder_session);
1037                                 }
1038                         }
1039                         else if(bytes_read % bytes_per_wide_sample != 0) {
1040                                 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1041                                 return EncoderSession_finish_error(&encoder_session);
1042                         }
1043                         else {
1044                                 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1045                                 format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
1046
1047                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1048                                         print_error_with_state(&encoder_session, "ERROR during encoding");
1049                                         return EncoderSession_finish_error(&encoder_session);
1050                                 }
1051                         }
1052                 }
1053         }
1054         else {
1055                 const FLAC__uint64 max_input_bytes = encoder_session.total_samples_to_encode * bytes_per_wide_sample;
1056                 FLAC__uint64 total_input_bytes_read = 0;
1057                 while(total_input_bytes_read < max_input_bytes) {
1058                         size_t wanted = (CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1059                         wanted = min(wanted, (size_t)(max_input_bytes - total_input_bytes_read));
1060
1061                         if(lookahead_length > 0) {
1062                                 FLAC__ASSERT(lookahead_length < wanted);
1063                                 memcpy(ucbuffer_, lookahead, lookahead_length);
1064                                 bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), wanted - lookahead_length, infile) + lookahead_length;
1065                                 if(ferror(infile)) {
1066                                         fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
1067                                         return EncoderSession_finish_error(&encoder_session);
1068                                 }
1069                                 lookahead_length = 0;
1070                         }
1071                         else
1072                                 bytes_read = fread(ucbuffer_, sizeof(unsigned char), wanted, infile);
1073
1074                         if(bytes_read == 0) {
1075                                 if(ferror(infile)) {
1076                                         fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
1077                                         return EncoderSession_finish_error(&encoder_session);
1078                                 }
1079                                 else if(feof(infile)) {
1080                                         fprintf(stderr, "%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);
1081                                         total_input_bytes_read = max_input_bytes;
1082                                 }
1083                         }
1084                         else {
1085                                 if(bytes_read % bytes_per_wide_sample != 0) {
1086                                         fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1087                                         return EncoderSession_finish_error(&encoder_session);
1088                                 }
1089                                 else {
1090                                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1091                                         format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
1092
1093                                         if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1094                                                 print_error_with_state(&encoder_session, "ERROR during encoding");
1095                                                 return EncoderSession_finish_error(&encoder_session);
1096                                         }
1097                                         total_input_bytes_read += bytes_read;
1098                                 }
1099                         }
1100                 }
1101         }
1102
1103         /*
1104          * now read unaligned samples into reservoir or pad with zeroes if necessary
1105          */
1106         if(options.common.sector_align) {
1107                 if(options.common.is_last_file) {
1108                         unsigned wide_samples = 588 - align_remainder;
1109                         if(wide_samples < 588) {
1110                                 unsigned channel, data_bytes;
1111
1112                                 info_align_zero = wide_samples;
1113                                 data_bytes = wide_samples * (options.bps >> 3);
1114                                 for(channel = 0; channel < options.channels; channel++)
1115                                         memset(input_[channel], 0, data_bytes);
1116
1117                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1118                                         print_error_with_state(&encoder_session, "ERROR during encoding");
1119                                         return EncoderSession_finish_error(&encoder_session);
1120                                 }
1121                         }
1122                 }
1123                 else {
1124                         if(*options.common.align_reservoir_samples > 0) {
1125                                 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1126                                 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
1127                                 if(bytes_read == 0 && ferror(infile)) {
1128                                         fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
1129                                         return EncoderSession_finish_error(&encoder_session);
1130                                 }
1131                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
1132                                         fprintf(stderr, "%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);
1133                                 }
1134                                 else {
1135                                         info_align_carry = *options.common.align_reservoir_samples;
1136                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, options.is_unsigned_samples, options.channels, options.bps);
1137                                 }
1138                         }
1139                 }
1140         }
1141
1142         return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
1143 }
1144
1145 FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FLAC__bool verbose, FILE *infile, const char *infilename, const char *outfilename)
1146 {
1147         unsigned i;
1148         FLAC__uint32 test = 1;
1149
1150         /*
1151          * initialize globals
1152          */
1153
1154         is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
1155
1156         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1157                 input_[i] = &(in_[i][0]);
1158
1159
1160         /*
1161          * initialize instance
1162          */
1163
1164 #ifdef FLAC__HAS_OGG
1165         e->use_ogg = use_ogg;
1166 #else
1167         (void)use_ogg;
1168 #endif
1169         e->verify = verify;
1170         e->verbose = verbose;
1171
1172         e->is_stdout = (0 == strcmp(outfilename, "-"));
1173
1174         e->inbasefilename = grabbag__file_get_basename(infilename);
1175         e->outfilename = outfilename;
1176
1177         e->skip = 0; /* filled in later after the sample_rate is known */
1178         e->unencoded_size = 0;
1179         e->total_samples_to_encode = 0;
1180         e->bytes_written = 0;
1181         e->samples_written = 0;
1182         e->blocksize = 0;
1183         e->stats_mask = 0;
1184
1185         e->encoder.flac.stream = 0;
1186         e->encoder.flac.file = 0;
1187 #ifdef FLAC__HAS_OGG
1188         e->encoder.ogg.stream = 0;
1189 #endif
1190
1191         e->fin = infile;
1192         e->fout = 0;
1193         e->seek_table_template = 0;
1194
1195         if(e->is_stdout) {
1196                 e->fout = grabbag__file_get_binary_stdout();
1197         }
1198 #ifdef FLAC__HAS_OGG
1199         else {
1200                 if(e->use_ogg) {
1201                         if(0 == (e->fout = fopen(outfilename, "wb"))) {
1202                                 fprintf(stderr, "%s: ERROR: can't open output file %s\n", e->inbasefilename, outfilename);
1203                                 EncoderSession_destroy(e);
1204                                 return false;
1205                         }
1206                 }
1207         }
1208 #endif
1209
1210         if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1211                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1212                 return false;
1213         }
1214
1215 #ifdef FLAC__HAS_OGG
1216         if(e->use_ogg) {
1217                 e->encoder.ogg.stream = OggFLAC__stream_encoder_new();
1218                 if(0 == e->encoder.ogg.stream) {
1219                         fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1220                         EncoderSession_destroy(e);
1221                         return false;
1222                 }
1223         }
1224         else
1225 #endif
1226         if(e->is_stdout) {
1227                 e->encoder.flac.stream = FLAC__stream_encoder_new();
1228                 if(0 == e->encoder.flac.stream) {
1229                         fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1230                         EncoderSession_destroy(e);
1231                         return false;
1232                 }
1233         }
1234         else {
1235                 e->encoder.flac.file = FLAC__file_encoder_new();
1236                 if(0 == e->encoder.flac.file) {
1237                         fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1238                         EncoderSession_destroy(e);
1239                         return false;
1240                 }
1241         }
1242
1243         return true;
1244 }
1245
1246 void EncoderSession_destroy(EncoderSession *e)
1247 {
1248         if(e->fin != stdin)
1249                 fclose(e->fin);
1250         if(0 != e->fout && e->fout != stdout)
1251                 fclose(e->fout);
1252
1253 #ifdef FLAC__HAS_OGG
1254         if(e->use_ogg) {
1255                 if(0 != e->encoder.ogg.stream) {
1256                         OggFLAC__stream_encoder_delete(e->encoder.ogg.stream);
1257                         e->encoder.ogg.stream = 0;
1258                 }
1259         }
1260         else
1261 #endif
1262         if(e->is_stdout) {
1263                 if(0 != e->encoder.flac.stream) {
1264                         FLAC__stream_encoder_delete(e->encoder.flac.stream);
1265                         e->encoder.flac.stream = 0;
1266                 }
1267         }
1268         else {
1269                 if(0 != e->encoder.flac.file) {
1270                         FLAC__file_encoder_delete(e->encoder.flac.file);
1271                         e->encoder.flac.file = 0;
1272                 }
1273         }
1274
1275         if(0 != e->seek_table_template) {
1276                 FLAC__metadata_object_delete(e->seek_table_template);
1277                 e->seek_table_template = 0;
1278         }
1279 }
1280
1281 int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero)
1282 {
1283         FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1284         int ret = 0;
1285
1286 #ifdef FLAC__HAS_OGG
1287         if(e->use_ogg) {
1288                 if(e->encoder.ogg.stream) {
1289                         fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1290                         OggFLAC__stream_encoder_finish(e->encoder.ogg.stream);
1291                 }
1292         }
1293         else
1294 #endif
1295         if(e->is_stdout) {
1296                 if(e->encoder.flac.stream) {
1297                         fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1298                         FLAC__stream_encoder_finish(e->encoder.flac.stream);
1299                 }
1300         }
1301         else {
1302                 if(e->encoder.flac.file) {
1303                         fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1304                         FLAC__file_encoder_finish(e->encoder.flac.file);
1305                 }
1306         }
1307
1308         if(e->verbose && e->total_samples_to_encode > 0) {
1309                 print_stats(e);
1310                 fprintf(stderr, "\n");
1311         }
1312
1313         if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) {
1314                 print_verify_error(e);
1315                 ret = 1;
1316         }
1317         else {
1318                 if(info_align_carry >= 0)
1319                         fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", e->inbasefilename, info_align_carry);
1320                 if(info_align_zero >= 0)
1321                         fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", e->inbasefilename, info_align_zero);
1322         }
1323
1324         EncoderSession_destroy(e);
1325
1326         return ret;
1327 }
1328
1329 int EncoderSession_finish_error(EncoderSession *e)
1330 {
1331         FLAC__StreamEncoderState fse_state;
1332
1333         if(e->verbose && e->total_samples_to_encode > 0)
1334                 fprintf(stderr, "\n");
1335
1336 #ifdef FLAC__HAS_OGG
1337         if(e->use_ogg) {
1338                 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1339         }
1340         else
1341 #endif
1342         if(e->is_stdout) {
1343                 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1344         }
1345         else {
1346                 fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1347         }
1348
1349         if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1350                 print_verify_error(e);
1351         else
1352                 unlink(e->outfilename);
1353
1354         EncoderSession_destroy(e);
1355
1356         return 1;
1357 }
1358
1359 FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate)
1360 {
1361         unsigned num_metadata;
1362         FLAC__StreamMetadata padding, *cuesheet = 0;
1363         FLAC__StreamMetadata *metadata[4];
1364
1365         e->replay_gain = options.replay_gain;
1366         e->channels = channels;
1367         e->bits_per_sample = bps;
1368         e->sample_rate = sample_rate;
1369
1370         if(e->replay_gain) {
1371                 if(channels != 1 && channels != 2) {
1372                         fprintf(stderr, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
1373                         return false;
1374                 }
1375                 if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) {
1376                         fprintf(stderr, "%s: ERROR, invalid sample rate (%u) for --replay-gain\n", e->inbasefilename, sample_rate);
1377                         return false;
1378                 }
1379                 if(options.is_first_file) {
1380                         if(!grabbag__replaygain_init(sample_rate)) {
1381                                 fprintf(stderr, "%s: ERROR initializing ReplayGain stage\n", e->inbasefilename);
1382                                 return false;
1383                         }
1384                 }
1385         }
1386
1387         if(channels != 2)
1388                 options.do_mid_side = options.loose_mid_side = false;
1389
1390         if(!parse_cuesheet_(&cuesheet, options.cuesheet_filename, e->inbasefilename, e->total_samples_to_encode))
1391                 return false;
1392
1393         if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? cuesheet : 0, e)) {
1394                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1395                 if(0 != cuesheet)
1396                         free(cuesheet);
1397                 return false;
1398         }
1399
1400         num_metadata = 0;
1401         if(e->seek_table_template->data.seek_table.num_points > 0) {
1402                 e->seek_table_template->is_last = false; /* the encoder will set this for us */
1403                 metadata[num_metadata++] = e->seek_table_template;
1404         }
1405         if(0 != cuesheet)
1406                 metadata[num_metadata++] = cuesheet;
1407         metadata[num_metadata++] = options.vorbis_comment;
1408         if(options.padding > 0) {
1409                 padding.is_last = false; /* the encoder will set this for us */
1410                 padding.type = FLAC__METADATA_TYPE_PADDING;
1411                 padding.length = (unsigned)options.padding;
1412                 metadata[num_metadata++] = &padding;
1413         }
1414
1415         e->blocksize = options.blocksize;
1416         e->stats_mask = (options.do_exhaustive_model_search || options.do_qlp_coeff_prec_search)? 0x0f : 0x3f;
1417
1418 #ifdef FLAC__HAS_OGG
1419         if(e->use_ogg) {
1420                 if(options.has_serial_number)
1421                         OggFLAC__stream_encoder_set_serial_number(e->encoder.ogg.stream, options.serial_number);
1422                 OggFLAC__stream_encoder_set_verify(e->encoder.ogg.stream, options.verify);
1423                 OggFLAC__stream_encoder_set_streamable_subset(e->encoder.ogg.stream, !options.lax);
1424                 OggFLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.ogg.stream, options.do_mid_side);
1425                 OggFLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.ogg.stream, options.loose_mid_side);
1426                 OggFLAC__stream_encoder_set_channels(e->encoder.ogg.stream, channels);
1427                 OggFLAC__stream_encoder_set_bits_per_sample(e->encoder.ogg.stream, bps);
1428                 OggFLAC__stream_encoder_set_sample_rate(e->encoder.ogg.stream, sample_rate);
1429                 OggFLAC__stream_encoder_set_blocksize(e->encoder.ogg.stream, options.blocksize);
1430                 OggFLAC__stream_encoder_set_max_lpc_order(e->encoder.ogg.stream, options.max_lpc_order);
1431                 OggFLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.ogg.stream, options.qlp_coeff_precision);
1432                 OggFLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg.stream, options.do_qlp_coeff_prec_search);
1433                 OggFLAC__stream_encoder_set_do_escape_coding(e->encoder.ogg.stream, options.do_escape_coding);
1434                 OggFLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.ogg.stream, options.do_exhaustive_model_search);
1435                 OggFLAC__stream_encoder_set_min_residual_partition_order(e->encoder.ogg.stream, options.min_residual_partition_order);
1436                 OggFLAC__stream_encoder_set_max_residual_partition_order(e->encoder.ogg.stream, options.max_residual_partition_order);
1437                 OggFLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.ogg.stream, options.rice_parameter_search_dist);
1438                 OggFLAC__stream_encoder_set_total_samples_estimate(e->encoder.ogg.stream, e->total_samples_to_encode);
1439                 OggFLAC__stream_encoder_set_metadata(e->encoder.ogg.stream, (num_metadata > 0)? metadata : 0, num_metadata);
1440                 OggFLAC__stream_encoder_set_write_callback(e->encoder.ogg.stream, ogg_stream_encoder_write_callback);
1441                 OggFLAC__stream_encoder_set_client_data(e->encoder.ogg.stream, e);
1442
1443                 OggFLAC__stream_encoder_disable_constant_subframes(e->encoder.ogg.stream, options.debug.disable_constant_subframes);
1444                 OggFLAC__stream_encoder_disable_fixed_subframes(e->encoder.ogg.stream, options.debug.disable_fixed_subframes);
1445                 OggFLAC__stream_encoder_disable_verbatim_subframes(e->encoder.ogg.stream, options.debug.disable_verbatim_subframes);
1446
1447                 if(OggFLAC__stream_encoder_init(e->encoder.ogg.stream) != FLAC__STREAM_ENCODER_OK) {
1448                         print_error_with_state(e, "ERROR initializing encoder");
1449                         if(0 != cuesheet)
1450                                 free(cuesheet);
1451                         return false;
1452                 }
1453         }
1454         else
1455 #endif
1456         if(e->is_stdout) {
1457                 FLAC__stream_encoder_set_verify(e->encoder.flac.stream, options.verify);
1458                 FLAC__stream_encoder_set_streamable_subset(e->encoder.flac.stream, !options.lax);
1459                 FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.flac.stream, options.do_mid_side);
1460                 FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.flac.stream, options.loose_mid_side);
1461                 FLAC__stream_encoder_set_channels(e->encoder.flac.stream, channels);
1462                 FLAC__stream_encoder_set_bits_per_sample(e->encoder.flac.stream, bps);
1463                 FLAC__stream_encoder_set_sample_rate(e->encoder.flac.stream, sample_rate);
1464                 FLAC__stream_encoder_set_blocksize(e->encoder.flac.stream, options.blocksize);
1465                 FLAC__stream_encoder_set_max_lpc_order(e->encoder.flac.stream, options.max_lpc_order);
1466                 FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.flac.stream, options.qlp_coeff_precision);
1467                 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.stream, options.do_qlp_coeff_prec_search);
1468                 FLAC__stream_encoder_set_do_escape_coding(e->encoder.flac.stream, options.do_escape_coding);
1469                 FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.flac.stream, options.do_exhaustive_model_search);
1470                 FLAC__stream_encoder_set_min_residual_partition_order(e->encoder.flac.stream, options.min_residual_partition_order);
1471                 FLAC__stream_encoder_set_max_residual_partition_order(e->encoder.flac.stream, options.max_residual_partition_order);
1472                 FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.flac.stream, options.rice_parameter_search_dist);
1473                 FLAC__stream_encoder_set_total_samples_estimate(e->encoder.flac.stream, e->total_samples_to_encode);
1474                 FLAC__stream_encoder_set_metadata(e->encoder.flac.stream, (num_metadata > 0)? metadata : 0, num_metadata);
1475                 FLAC__stream_encoder_set_write_callback(e->encoder.flac.stream, flac_stream_encoder_write_callback);
1476                 FLAC__stream_encoder_set_metadata_callback(e->encoder.flac.stream, flac_stream_encoder_metadata_callback);
1477                 FLAC__stream_encoder_set_client_data(e->encoder.flac.stream, e);
1478
1479                 FLAC__stream_encoder_disable_constant_subframes(e->encoder.flac.stream, options.debug.disable_constant_subframes);
1480                 FLAC__stream_encoder_disable_fixed_subframes(e->encoder.flac.stream, options.debug.disable_fixed_subframes);
1481                 FLAC__stream_encoder_disable_verbatim_subframes(e->encoder.flac.stream, options.debug.disable_verbatim_subframes);
1482
1483                 if(FLAC__stream_encoder_init(e->encoder.flac.stream) != FLAC__STREAM_ENCODER_OK) {
1484                         print_error_with_state(e, "ERROR initializing encoder");
1485                         if(0 != cuesheet)
1486                                 free(cuesheet);
1487                         return false;
1488                 }
1489         }
1490         else {
1491                 FLAC__file_encoder_set_filename(e->encoder.flac.file, e->outfilename);
1492                 FLAC__file_encoder_set_verify(e->encoder.flac.file, options.verify);
1493                 FLAC__file_encoder_set_streamable_subset(e->encoder.flac.file, !options.lax);
1494                 FLAC__file_encoder_set_do_mid_side_stereo(e->encoder.flac.file, options.do_mid_side);
1495                 FLAC__file_encoder_set_loose_mid_side_stereo(e->encoder.flac.file, options.loose_mid_side);
1496                 FLAC__file_encoder_set_channels(e->encoder.flac.file, channels);
1497                 FLAC__file_encoder_set_bits_per_sample(e->encoder.flac.file, bps);
1498                 FLAC__file_encoder_set_sample_rate(e->encoder.flac.file, sample_rate);
1499                 FLAC__file_encoder_set_blocksize(e->encoder.flac.file, options.blocksize);
1500                 FLAC__file_encoder_set_max_lpc_order(e->encoder.flac.file, options.max_lpc_order);
1501                 FLAC__file_encoder_set_qlp_coeff_precision(e->encoder.flac.file, options.qlp_coeff_precision);
1502                 FLAC__file_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.file, options.do_qlp_coeff_prec_search);
1503                 FLAC__file_encoder_set_do_escape_coding(e->encoder.flac.file, options.do_escape_coding);
1504                 FLAC__file_encoder_set_do_exhaustive_model_search(e->encoder.flac.file, options.do_exhaustive_model_search);
1505                 FLAC__file_encoder_set_min_residual_partition_order(e->encoder.flac.file, options.min_residual_partition_order);
1506                 FLAC__file_encoder_set_max_residual_partition_order(e->encoder.flac.file, options.max_residual_partition_order);
1507                 FLAC__file_encoder_set_rice_parameter_search_dist(e->encoder.flac.file, options.rice_parameter_search_dist);
1508                 FLAC__file_encoder_set_total_samples_estimate(e->encoder.flac.file, e->total_samples_to_encode);
1509                 FLAC__file_encoder_set_metadata(e->encoder.flac.file, (num_metadata > 0)? metadata : 0, num_metadata);
1510                 FLAC__file_encoder_set_progress_callback(e->encoder.flac.file, flac_file_encoder_progress_callback);
1511                 FLAC__file_encoder_set_client_data(e->encoder.flac.file, e);
1512
1513                 FLAC__file_encoder_disable_constant_subframes(e->encoder.flac.file, options.debug.disable_constant_subframes);
1514                 FLAC__file_encoder_disable_fixed_subframes(e->encoder.flac.file, options.debug.disable_fixed_subframes);
1515                 FLAC__file_encoder_disable_verbatim_subframes(e->encoder.flac.file, options.debug.disable_verbatim_subframes);
1516
1517                 if(FLAC__file_encoder_init(e->encoder.flac.file) != FLAC__FILE_ENCODER_OK) {
1518                         print_error_with_state(e, "ERROR initializing encoder");
1519                         if(0 != cuesheet)
1520                                 free(cuesheet);
1521                         return false;
1522                 }
1523         }
1524
1525         if(0 != cuesheet)
1526                 free(cuesheet);
1527
1528         return true;
1529 }
1530
1531 FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples)
1532 {
1533         if(e->replay_gain) {
1534                 if(!grabbag__replaygain_analyze(buffer, e->channels==2, e->bits_per_sample, samples))
1535                         fprintf(stderr, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename);
1536         }
1537
1538 #ifdef FLAC__HAS_OGG
1539         if(e->use_ogg) {
1540                 return OggFLAC__stream_encoder_process(e->encoder.ogg.stream, buffer, samples);
1541         }
1542         else
1543 #endif
1544         if(e->is_stdout) {
1545                 return FLAC__stream_encoder_process(e->encoder.flac.stream, buffer, samples);
1546         }
1547         else {
1548                 return FLAC__file_encoder_process(e->encoder.flac.file, buffer, samples);
1549         }
1550 }
1551
1552 FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e)
1553 {
1554         FLAC__bool only_placeholders;
1555         FLAC__bool has_real_points;
1556
1557         if(num_requested_seek_points == 0 && 0 == cuesheet)
1558                 return true;
1559
1560         if(num_requested_seek_points < 0) {
1561                 requested_seek_points = "10s;";
1562                 num_requested_seek_points = 1;
1563         }
1564
1565         if(e->is_stdout)
1566                 only_placeholders = true;
1567 #ifdef FLAC__HAS_OGG
1568         else if(e->use_ogg)
1569                 only_placeholders = true;
1570 #endif
1571         else
1572                 only_placeholders = false;
1573
1574         if(num_requested_seek_points > 0) {
1575                 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))
1576                         return false;
1577         }
1578
1579         if(0 != cuesheet) {
1580                 unsigned i, j;
1581                 const FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet;
1582                 for(i = 0; i < cs->num_tracks; i++) {
1583                         const FLAC__StreamMetadata_CueSheet_Track *tr = cs->tracks+i;
1584                         for(j = 0; j < tr->num_indices; j++) {
1585                                 if(!FLAC__metadata_object_seektable_template_append_point(e->seek_table_template, tr->offset + tr->indices[j].offset))
1586                                         return false;
1587                                 has_real_points = true;
1588                         }
1589                 }
1590                 if(has_real_points)
1591                         if(!FLAC__metadata_object_seektable_template_sort(e->seek_table_template, /*compact=*/true))
1592                                 return false;
1593         }
1594
1595         if(has_real_points) {
1596                 if(e->is_stdout)
1597                         fprintf(stderr, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename);
1598 #ifdef FLAC__HAS_OGG
1599                 else if(e->use_ogg)
1600                         fprintf(stderr, "%s: WARNING, cannot write back seekpoints when encoding to Ogg yet\n", e->inbasefilename);
1601 #endif
1602         }
1603
1604         return true;
1605 }
1606
1607 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
1608 {
1609         /* convert from mm:ss.sss to sample number if necessary */
1610         flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
1611
1612         /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
1613         if(spec->is_relative && spec->value.samples == 0) {
1614                 spec->is_relative = false;
1615                 return true;
1616         }
1617
1618         /* in any other case the total samples in the input must be known */
1619         if(total_samples_in_input == 0) {
1620                 fprintf(stderr, "%s: ERROR, cannot use --until when input length is unknown\n", inbasefilename);
1621                 return false;
1622         }
1623
1624         FLAC__ASSERT(spec->value_is_samples);
1625
1626         /* convert relative specifications to absolute */
1627         if(spec->is_relative) {
1628                 if(spec->value.samples <= 0)
1629                         spec->value.samples += (FLAC__int64)total_samples_in_input;
1630                 else
1631                         spec->value.samples += skip;
1632                 spec->is_relative = false;
1633         }
1634
1635         /* error check */
1636         if(spec->value.samples < 0) {
1637                 fprintf(stderr, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
1638                 return false;
1639         }
1640         if((FLAC__uint64)spec->value.samples <= skip) {
1641                 fprintf(stderr, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
1642                 return false;
1643         }
1644         if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
1645                 fprintf(stderr, "%s: ERROR, --until value is after end of input\n", inbasefilename);
1646                 return false;
1647         }
1648
1649         return true;
1650 }
1651
1652 void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps)
1653 {
1654         unsigned wide_sample, sample, channel, byte;
1655
1656         if(bps == 8) {
1657                 if(is_unsigned_samples) {
1658                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1659                                 for(channel = 0; channel < channels; channel++, sample++)
1660                                         dest[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
1661                 }
1662                 else {
1663                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1664                                 for(channel = 0; channel < channels; channel++, sample++)
1665                                         dest[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
1666                 }
1667         }
1668         else if(bps == 16) {
1669                 if(is_big_endian != is_big_endian_host_) {
1670                         unsigned char tmp;
1671                         const unsigned bytes = wide_samples * channels * (bps >> 3);
1672                         for(byte = 0; byte < bytes; byte += 2) {
1673                                 tmp = ucbuffer_[byte];
1674                                 ucbuffer_[byte] = ucbuffer_[byte+1];
1675                                 ucbuffer_[byte+1] = tmp;
1676                         }
1677                 }
1678                 if(is_unsigned_samples) {
1679                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1680                                 for(channel = 0; channel < channels; channel++, sample++)
1681                                         dest[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
1682                 }
1683                 else {
1684                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1685                                 for(channel = 0; channel < channels; channel++, sample++)
1686                                         dest[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
1687                 }
1688         }
1689         else if(bps == 24) {
1690                 if(!is_big_endian) {
1691                         unsigned char tmp;
1692                         const unsigned bytes = wide_samples * channels * (bps >> 3);
1693                         for(byte = 0; byte < bytes; byte += 3) {
1694                                 tmp = ucbuffer_[byte];
1695                                 ucbuffer_[byte] = ucbuffer_[byte+2];
1696                                 ucbuffer_[byte+2] = tmp;
1697                         }
1698                 }
1699                 if(is_unsigned_samples) {
1700                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1701                                 for(channel = 0; channel < channels; channel++, sample++) {
1702                                         dest[channel][wide_sample]  = ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1703                                         dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1704                                         dest[channel][wide_sample] |= ucbuffer_[byte++];
1705                                         dest[channel][wide_sample] -= 0x800000;
1706                                 }
1707                 }
1708                 else {
1709                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1710                                 for(channel = 0; channel < channels; channel++, sample++) {
1711                                         dest[channel][wide_sample]  = scbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1712                                         dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1713                                         dest[channel][wide_sample] |= ucbuffer_[byte++];
1714                                 }
1715                 }
1716         }
1717         else {
1718                 FLAC__ASSERT(0);
1719         }
1720 }
1721
1722 #ifdef FLAC__HAS_OGG
1723 FLAC__StreamEncoderWriteStatus ogg_stream_encoder_write_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
1724 {
1725         EncoderSession *encoder_session = (EncoderSession*)client_data;
1726
1727         (void)encoder;
1728
1729         encoder_session->bytes_written += bytes;
1730         /*
1731          * With Ogg FLAC we don't get one write callback per frame and
1732          * we don't have good number for 'samples', so we estimate based
1733          * on the frame number and the knowledge that all blocks (except
1734          * the last) are the same size.
1735          */
1736         (void)samples;
1737         encoder_session->samples_written = (current_frame+1) * encoder_session->blocksize;
1738
1739         if(encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
1740                 print_stats(encoder_session);
1741
1742         if(flac__utils_fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
1743                 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1744         else
1745                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1746 }
1747 #endif
1748
1749 FLAC__StreamEncoderWriteStatus flac_stream_encoder_write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
1750 {
1751         EncoderSession *encoder_session = (EncoderSession*)client_data;
1752
1753         (void)encoder;
1754
1755         encoder_session->bytes_written += bytes;
1756         encoder_session->samples_written += samples;
1757
1758         if(samples && encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
1759                 print_stats(encoder_session);
1760
1761         if(flac__utils_fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
1762                 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1763         else
1764                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1765 }
1766
1767 void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
1768 {
1769         /*
1770          * Nothing to do; if we get here, we're decoding to stdout, in
1771          * which case we can't seek backwards to write new metadata.
1772          */
1773         (void)encoder, (void)metadata, (void)client_data;
1774 }
1775
1776 void flac_file_encoder_progress_callback(const FLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
1777 {
1778         EncoderSession *encoder_session = (EncoderSession*)client_data;
1779
1780         (void)encoder, (void)total_frames_estimate;
1781
1782         encoder_session->bytes_written = bytes_written;
1783         encoder_session->samples_written = samples_written;
1784
1785         if(encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !((frames_written-1) & encoder_session->stats_mask))
1786                 print_stats(encoder_session);
1787 }
1788
1789 FLAC__bool parse_cuesheet_(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__uint64 lead_out_offset)
1790 {
1791         FILE *f;
1792         unsigned last_line_read;
1793         const char *error_message;
1794
1795         if(0 == cuesheet_filename)
1796                 return true;
1797
1798         if(lead_out_offset == 0) {
1799                 fprintf(stderr, "%s: ERROR cannot import cuesheet when the number of input samples to encode is unknown\n", inbasefilename);
1800                 return false;
1801         }
1802
1803         if(0 == (f = fopen(cuesheet_filename, "r"))) {
1804                 fprintf(stderr, "%s: ERROR opening cuesheet \"%s\" for reading\n", inbasefilename, cuesheet_filename);
1805                 return false;
1806         }
1807
1808         *cuesheet = grabbag__cuesheet_parse(f, &error_message, &last_line_read, /*@@@@is_cdda=*/true, lead_out_offset);
1809
1810         fclose(f);
1811
1812         if(0 == *cuesheet) {
1813                 fprintf(stderr, "%s: ERROR parsing cuesheet \"%s\" on line %u: %s\n", inbasefilename, cuesheet_filename, last_line_read, error_message);
1814                 return false;
1815         }
1816
1817         return true;
1818 }
1819
1820 void print_stats(const EncoderSession *encoder_session)
1821 {
1822         const FLAC__uint64 samples_written = min(encoder_session->total_samples_to_encode, encoder_session->samples_written);
1823 #if defined _MSC_VER || defined __MINGW32__
1824         /* with VC++ you have to spoon feed it the casting */
1825         const double progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)encoder_session->total_samples_to_encode;
1826         const double ratio = (double)(FLAC__int64)encoder_session->bytes_written / ((double)(FLAC__int64)encoder_session->unencoded_size * progress);
1827 #else
1828         const double progress = (double)samples_written / (double)encoder_session->total_samples_to_encode;
1829         const double ratio = (double)encoder_session->bytes_written / ((double)encoder_session->unencoded_size * progress);
1830 #endif
1831
1832         if(samples_written == encoder_session->total_samples_to_encode) {
1833                 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1834                         encoder_session->inbasefilename,
1835                         encoder_session->verify? " Verify OK," : "",
1836                         (unsigned)encoder_session->bytes_written,
1837                         ratio
1838                 );
1839         }
1840         else {
1841                 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_session->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1842         }
1843 }
1844
1845 void print_error_with_state(const EncoderSession *e, const char *message)
1846 {
1847         const int ilen = strlen(e->inbasefilename) + 1;
1848
1849         fprintf(stderr, "\n%s: %s\n", e->inbasefilename, message);
1850
1851 #ifdef FLAC__HAS_OGG
1852         if(e->use_ogg) {
1853                 const OggFLAC__StreamEncoderState ose_state = OggFLAC__stream_encoder_get_state(e->encoder.ogg.stream);
1854                 if(ose_state != OggFLAC__STREAM_ENCODER_FLAC_STREAM_ENCODER_ERROR) {
1855                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ose_state, OggFLAC__StreamEncoderStateString[ose_state]);
1856                 }
1857                 else {
1858                         const FLAC__StreamEncoderState fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1859                         if(fse_state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) {
1860                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fse_state, FLAC__StreamEncoderStateString[fse_state]);
1861                         }
1862                         else {
1863                                 const FLAC__StreamDecoderState fsd_state = OggFLAC__stream_encoder_get_verify_decoder_state(e->encoder.ogg.stream);
1864                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1865                         }
1866                 }
1867         }
1868         else
1869 #endif
1870         if(e->is_stdout) {
1871                 const FLAC__StreamEncoderState fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1872                 if(fse_state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) {
1873                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fse_state, FLAC__StreamEncoderStateString[fse_state]);
1874                 }
1875                 else {
1876                         const FLAC__StreamDecoderState fsd_state = FLAC__stream_encoder_get_verify_decoder_state(e->encoder.flac.stream);
1877                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1878                 }
1879         }
1880         else {
1881                 const FLAC__FileEncoderState ffe_state = FLAC__file_encoder_get_state(e->encoder.flac.file);
1882                 if(ffe_state != FLAC__FILE_ENCODER_SEEKABLE_STREAM_ENCODER_ERROR) {
1883                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ffe_state, FLAC__FileEncoderStateString[ffe_state]);
1884                 }
1885                 else {
1886                         const FLAC__SeekableStreamEncoderState fsse_state = FLAC__file_encoder_get_seekable_stream_encoder_state(e->encoder.flac.file);
1887                         if(fsse_state != FLAC__SEEKABLE_STREAM_ENCODER_STREAM_ENCODER_ERROR) {
1888                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsse_state, FLAC__SeekableStreamEncoderStateString[fsse_state]);
1889                         }
1890                         else {
1891                                 const FLAC__StreamEncoderState fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1892                                 if(fse_state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) {
1893                                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fse_state, FLAC__StreamEncoderStateString[fse_state]);
1894                                 }
1895                                 else {
1896                                         const FLAC__StreamDecoderState fsd_state = FLAC__file_encoder_get_verify_decoder_state(e->encoder.flac.file);
1897                                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1898                                 }
1899                         }
1900                 }
1901         }
1902 }
1903
1904 void print_verify_error(EncoderSession *e)
1905 {
1906         FLAC__uint64 absolute_sample;
1907         unsigned frame_number;
1908         unsigned channel;
1909         unsigned sample;
1910         FLAC__int32 expected;
1911         FLAC__int32 got;
1912
1913 #ifdef FLAC__HAS_OGG
1914         if(e->use_ogg) {
1915                 OggFLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.ogg.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1916         }
1917         else
1918 #endif
1919         if(e->is_stdout) {
1920                 FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.flac.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1921         }
1922         else {
1923                 FLAC__file_encoder_get_verify_decoder_error_stats(e->encoder.flac.file, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1924         }
1925
1926         fprintf(stderr, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
1927         fprintf(stderr, "       Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)absolute_sample, frame_number, channel, sample, expected, got);
1928         fprintf(stderr, "       Please submit a bug report to\n");
1929         fprintf(stderr, "           http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1930         fprintf(stderr, "       Make sure to include an email contact in the comment and/or use the\n");
1931         fprintf(stderr, "       \"Monitor\" feature to monitor the bug status.\n");
1932         fprintf(stderr, "Verify FAILED!  Do not trust %s\n", e->outfilename);
1933 }
1934
1935 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1936 {
1937         size_t bytes_read = fread(val, 1, 2, f);
1938
1939         if(bytes_read == 0) {
1940                 if(!eof_ok) {
1941                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1942                         return false;
1943                 }
1944                 else
1945                         return true;
1946         }
1947         else if(bytes_read < 2) {
1948                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1949                 return false;
1950         }
1951         else {
1952                 if(is_big_endian_host_) {
1953                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1954                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1955                 }
1956                 return true;
1957         }
1958 }
1959
1960 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1961 {
1962         size_t bytes_read = fread(val, 1, 4, f);
1963
1964         if(bytes_read == 0) {
1965                 if(!eof_ok) {
1966                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1967                         return false;
1968                 }
1969                 else
1970                         return true;
1971         }
1972         else if(bytes_read < 4) {
1973                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1974                 return false;
1975         }
1976         else {
1977                 if(is_big_endian_host_) {
1978                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1979                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1980                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1981                 }
1982                 return true;
1983         }
1984 }
1985
1986 FLAC__bool
1987 read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1988 {
1989         unsigned char buf[4];
1990         size_t bytes_read= fread(buf, 1, 2, f);
1991
1992         if(bytes_read==0U && eof_ok)
1993                 return true;
1994         else if(bytes_read<2U) {
1995                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1996                 return false;
1997         }
1998
1999         /* this is independent of host endianness */
2000         *val= (FLAC__uint16)(buf[0])<<8 | buf[1];
2001
2002         return true;
2003 }
2004
2005 FLAC__bool
2006 read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2007 {
2008         unsigned char buf[4];
2009         size_t bytes_read= fread(buf, 1, 4, f);
2010
2011         if(bytes_read==0U && eof_ok)
2012                 return true;
2013         else if(bytes_read<4U) {
2014                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
2015                 return false;
2016         }
2017
2018         /* this is independent of host endianness */
2019         *val= (FLAC__uint32)(buf[0])<<24 | (FLAC__uint32)(buf[1])<<16 |
2020                 (FLAC__uint32)(buf[2])<<8 | buf[3];
2021
2022         return true;
2023 }
2024
2025 FLAC__bool
2026 read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2027         /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
2028          * convert it into an integral value and store in 'val'.  Return false if only
2029          * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f' and 'eof_ok' is
2030          * false, or if the value is negative, between zero and one, or too large to be
2031          * represented by 'val'; return true otherwise.
2032          */
2033 {
2034         unsigned int i;
2035         unsigned char buf[10];
2036         size_t bytes_read= fread(buf, 1U, 10U, f);
2037         FLAC__int16 e= ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
2038         FLAC__int16 shift= 63-e;
2039         FLAC__uint64 p= 0U;
2040
2041         if(bytes_read==0U && eof_ok)
2042                 return true;
2043         else if(bytes_read<10U) {
2044                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
2045                 return false;
2046         }
2047         else if((buf[0]>>7)==1U || e<0 || e>63) {
2048                 fprintf(stderr, "%s: ERROR: invalid floating-point value\n", fn);
2049                 return false;
2050         }
2051
2052         for(i= 0U; i<8U; ++i)
2053                 p|= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
2054         *val= (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1));
2055
2056         return true;
2057 }