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