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