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