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