use new file encoder from libFLAC, still needs fixes for Ogg support
[flac.git] / src / flac / encode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001,2002  Josh Coalson
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17  */
18
19 #if defined _WIN32 && !defined __CYGWIN__
20 /* where MSVC puts unlink() */
21 # include <io.h>
22 #else
23 # include <unistd.h>
24 #endif
25 #include <limits.h> /* for LONG_MAX */
26 #include <math.h> /* for floor() */
27 #include <stdio.h> /* for FILE et al. */
28 #include <stdlib.h> /* for malloc */
29 #include <string.h> /* for strcmp() */
30 #include "FLAC/all.h"
31 #include "encode.h"
32 #include "file.h"
33 #ifdef FLAC__HAS_OGG
34 #include "OggFLAC/stream_encoder.h"
35 #endif
36
37 #ifdef min
38 #undef min
39 #endif
40 #define min(x,y) ((x)<(y)?(x):(y))
41
42 /* this MUST be >= 588 so that sector aligning can take place with one read */
43 #define CHUNK_OF_SAMPLES 2048
44
45 typedef struct {
46         const char *inbasefilename;
47         FILE *fout;
48         const char *outfilename;
49         FLAC__StreamEncoder *encoder;
50         FLAC__bool verify;
51         FLAC__bool verbose;
52         FLAC__uint64 unencoded_size;
53         FLAC__uint64 total_samples_to_encode;
54         FLAC__uint64 bytes_written;
55         FLAC__uint64 samples_written;
56         FLAC__uint64 stream_offset; /* i.e. number of bytes before the first byte of the the first frame's header */
57         unsigned current_frame;
58         FLAC__StreamMetadata *seek_table;
59         unsigned first_seek_point_to_check;
60         FLAC__bool verify_failed;
61 #ifdef FLAC__HAS_OGG
62         FLAC__bool use_ogg;
63         OggFLAC__StreamEncoder *ogg_encoder;
64 #endif
65 } encoder_wrapper_struct;
66
67 static FLAC__bool is_big_endian_host;
68
69 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
70 static signed char *scbuffer = (signed char *)ucbuffer;
71 static FLAC__uint16 *usbuffer = (FLAC__uint16 *)ucbuffer;
72 static FLAC__int16 *ssbuffer = (FLAC__int16 *)ucbuffer;
73
74 static FLAC__int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
75 static FLAC__int32 *input[FLAC__MAX_CHANNELS];
76
77 /* local routines */
78 static FLAC__bool init(encoder_wrapper_struct *encoder_wrapper);
79 static FLAC__bool init_encoder(encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper);
80 static FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, FLAC__StreamMetadata *seek_table);
81 static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps);
82 static FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
83 static void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
84 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
85 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
86 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
87 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
88 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
89 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
90 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
91 static FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val);
92
93 int
94 flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const char *outfilename,
95         const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
96 {
97         encoder_wrapper_struct encoder_wrapper;
98         FLAC__uint16 x;
99         FLAC__uint32 xx;
100         unsigned int channels= 0U, bps= 0U, sample_rate= 0U, sample_frames= 0U;
101         FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
102         int info_align_carry= -1, info_align_zero= -1;
103         enum { NORMAL, DONE, ERROR, MISMATCH } status= NORMAL;
104
105         FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
106
107         encoder_wrapper.encoder = 0;
108         encoder_wrapper.verify = options.common.verify;
109         encoder_wrapper.verbose = options.common.verbose;
110         encoder_wrapper.bytes_written = 0;
111         encoder_wrapper.samples_written = 0;
112         encoder_wrapper.stream_offset = 0;
113         encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
114         encoder_wrapper.outfilename = outfilename;
115         encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
116         encoder_wrapper.first_seek_point_to_check = 0;
117         encoder_wrapper.verify_failed = false;
118 #ifdef FLAC__HAS_OGG
119         encoder_wrapper.use_ogg = options.common.use_ogg;
120         encoder_wrapper.ogg_encoder = 0;
121 #endif
122
123         if(0 == encoder_wrapper.seek_table) {
124                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
125                 return 1;
126         }
127
128         (void)infilesize; /* silence compiler warning about unused parameter */
129         (void)lookahead; /* silence compiler warning about unused parameter */
130         (void)lookahead_length; /* silence compiler warning about unused parameter */
131
132         if(0 == strcmp(outfilename, "-")) {
133                 encoder_wrapper.fout = file__get_binary_stdout();
134         }
135         else {
136                 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
137                         fprintf(stderr, "%s: ERROR: can't open output file %s\n", encoder_wrapper.inbasefilename, outfilename);
138                         if(infile != stdin)
139                                 fclose(infile);
140                         return 1;
141                 }
142         }
143
144         if(!init(&encoder_wrapper))
145                 status= ERROR;
146
147         /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
148
149         while(status==NORMAL) {
150                 size_t c= 0U;
151                 char chunk_id[4];
152
153                 /* chunk identifier; really conservative about behavior of fread() and feof() */
154                 if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
155                         status= DONE;
156                 else if(c<4U || feof(infile)) {
157                         fprintf(stderr, "%s: ERROR: incomplete chunk identifier\n", encoder_wrapper.inbasefilename);
158                         status= ERROR;
159                 }
160
161                 if(status==NORMAL && got_comm_chunk==false && !strncmp(chunk_id, "COMM", 4)) { /* common chunk */
162                         unsigned long skip;
163
164                         if(status==NORMAL) {
165                                 /* COMM chunk size */
166                                 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
167                                         status= ERROR;
168                                 else if(xx<18U) {
169                                         fprintf(stderr, "%s: ERROR: non-standard 'COMM' chunk has length = %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
170                                         status= ERROR;
171                                 }
172                                 else if(xx!=18U)
173                                         fprintf(stderr, "%s: WARNING: non-standard 'COMM' chunk has length = %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
174                                 skip= (xx-18U)+(xx & 1U);
175                         }
176
177                         if(status==NORMAL) {
178                                 /* number of channels */
179                                 if(!read_big_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
180                                         status= ERROR;
181                                 else if(x==0U || x>FLAC__MAX_CHANNELS) {
182                                         fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned int)x);
183                                         status= ERROR;
184                                 }
185                                 else if(options.common.sector_align && x!=2U) {
186                                         fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)x);
187                                         status= ERROR;
188                                 }
189                                 channels= x;
190                         }
191
192                         if(status==NORMAL) {
193                                 /* number of sample frames */
194                                 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
195                                         status= ERROR;
196                                 sample_frames= xx;
197                         }
198
199                         if(status==NORMAL) {
200                                 /* bits per sample */
201                                 if(!read_big_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
202                                         status= ERROR;
203                                 else if(x!=8U && x!=16U && x!=24U) {
204                                         fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned int)x);
205                                         status= ERROR;
206                                 }
207                                 else if(options.common.sector_align && x!=16U) {
208                                         fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)x);
209                                         status= ERROR;
210                                 }
211                                 bps= x;
212                         }
213
214                         if(status==NORMAL) {
215                                 /* sample rate */
216                                 if(!read_sane_extended(infile, &xx, false, encoder_wrapper.inbasefilename))
217                                         status= ERROR;
218                                 else if(!FLAC__format_sample_rate_is_valid(xx)) {
219                                         fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
220                                         status= ERROR;
221                                 }
222                                 else if(options.common.sector_align && xx!=44100U) {
223                                         fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
224                                         status= ERROR;
225                                 }
226                                 sample_rate= xx;
227                         }
228
229                         /* skip any extra data in the COMM chunk */
230                         FLAC__ASSERT(skip<=LONG_MAX);
231                         while(status==NORMAL && skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
232                                 unsigned int need= min(skip, sizeof ucbuffer);
233                                 if(fread(ucbuffer, 1U, need, infile)<need) {
234                                         fprintf(stderr, "%s: ERROR during read while skipping extra COMM data\n", encoder_wrapper.inbasefilename);
235                                         status= ERROR;
236                                 }
237                                 skip-= need;
238                         }
239
240                         got_comm_chunk= true;
241                 }
242                 else if(status==NORMAL && got_ssnd_chunk==false && !strncmp(chunk_id, "SSND", 4)) { /* sound data chunk */
243                         unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
244                         size_t bytes_per_frame= channels*(bps>>3);
245                         FLAC__bool pad= false;
246
247                         if(status==NORMAL && got_comm_chunk==false) {
248                                 fprintf(stderr, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", encoder_wrapper.inbasefilename);
249                                 status= ERROR;
250                         }
251
252                         if(status==NORMAL) {
253                                 /* SSND chunk size */
254                                 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
255                                         status= ERROR;
256                                 else if(xx!=(sample_frames*bytes_per_frame + 8U)) {
257                                         fprintf(stderr, "%s: ERROR: SSND chunk size inconsistent with sample frame count\n", encoder_wrapper.inbasefilename);
258                                         status= ERROR;
259                                 }
260                                 data_bytes= xx;
261                                 pad= (data_bytes & 1U) ? true : false;
262                         }
263
264                         if(status==NORMAL) {
265                                 /* offset */
266                                 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
267                                         status= ERROR;
268                                 else if(xx!=0U) {
269                                         fprintf(stderr, "%s: ERROR: offset is %u; must be 0\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
270                                         status= ERROR;
271                                 }
272                                 offset= xx;
273                         }
274
275                         if(status==NORMAL) {
276                                 /* block size */
277                                 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
278                                         status= ERROR;
279                                 else if(xx!=0U) {
280                                         fprintf(stderr, "%s: ERROR: block size is %u; must be 0\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
281                                         status= ERROR;
282                                 }
283                                 block_size= xx;
284                         }
285
286                         if(status==NORMAL && options.common.skip>0U) {
287                                 FLAC__uint64 remaining= options.common.skip*bytes_per_frame;
288
289                                 /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
290                                 /* is guaranteed to be less than LONG_MAX */
291                                 for(; remaining>0U; remaining-= remaining>(1U<<30) ? remaining : (1U<<30))
292                                 {
293                                         unsigned long skip= remaining % (1U<<30);
294
295                                         FLAC__ASSERT(skip<=LONG_MAX);
296                                         while(status==NORMAL && skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
297                                                 unsigned int need= min(skip, sizeof ucbuffer);
298                                                 if(fread(ucbuffer, 1U, need, infile)<need) {
299                                                         fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
300                                                         status= ERROR;
301                                                 }
302                                                 skip-= need;
303                                         }
304                                 }
305                         }
306
307                         if(status==NORMAL) {
308                                 data_bytes-= (8U + (unsigned int)options.common.skip*bytes_per_frame); /*@@@ WATCHOUT: 4GB limit */
309                                 encoder_wrapper.total_samples_to_encode= data_bytes/bytes_per_frame + *options.common.align_reservoir_samples;
310                                 if(options.common.sector_align) {
311                                         align_remainder= (unsigned int)(encoder_wrapper.total_samples_to_encode % 588U);
312                                         if(options.common.is_last_file)
313                                                 encoder_wrapper.total_samples_to_encode+= (588U-align_remainder); /* will pad with zeroes */
314                                         else
315                                                 encoder_wrapper.total_samples_to_encode-= align_remainder; /* will stop short and carry over to next file */
316                                 }
317
318                                 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
319                                 encoder_wrapper.unencoded_size= encoder_wrapper.total_samples_to_encode*bytes_per_frame+54;
320
321                                 if(!init_encoder(options.common, channels, bps, sample_rate, &encoder_wrapper))
322                                         status= ERROR;
323                         }
324
325                         /* first do any samples in the reservoir */
326                         if(status==NORMAL && options.common.sector_align && *options.common.align_reservoir_samples>0U) {
327
328                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
329                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
330                                         encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
331                                         status= ERROR;
332                                 }
333                         }
334
335                         /* decrement the data_bytes counter if we need to align the file */
336                         if(status==NORMAL && options.common.sector_align) {
337                                 if(options.common.is_last_file)
338                                         *options.common.align_reservoir_samples= 0U;
339                                 else {
340                                         *options.common.align_reservoir_samples= align_remainder;
341                                         data_bytes-= (*options.common.align_reservoir_samples)*bytes_per_frame;
342                                 }
343                         }
344
345                         /* now do from the file */
346                         while(status==NORMAL && data_bytes>0) {
347                                 size_t bytes_read= fread(ucbuffer, 1U, min(data_bytes, CHUNK_OF_SAMPLES*bytes_per_frame), infile);
348
349                                 if(bytes_read==0U) {
350                                         if(ferror(infile)) {
351                                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
352                                                 status= ERROR;
353                                         }
354                                         else if(feof(infile)) {
355                                                 fprintf(stderr, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned int)encoder_wrapper.total_samples_to_encode, (unsigned int)encoder_wrapper.samples_written);
356                                                 data_bytes= 0;
357                                         }
358                                 }
359                                 else {
360                                         if(bytes_read % bytes_per_frame != 0U) {
361                                                 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
362                                                 status= ERROR;
363                                         }
364                                         else {
365                                                 unsigned int frames= bytes_read/bytes_per_frame;
366                                                 format_input(input, frames, true, false, channels, bps);
367
368                                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)input, frames)) {
369                                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
370                                                         encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
371                                                         status= ERROR;
372                                                 }
373                                                 else
374                                                         data_bytes-= bytes_read;
375                                         }
376                                 }
377                         }
378
379                         /* now read unaligned samples into reservoir or pad with zeroes if necessary */
380                         if(status==NORMAL && options.common.sector_align) {
381                                 if(options.common.is_last_file) {
382                                         unsigned int pad_frames= 588U-align_remainder;
383
384                                         if(pad_frames<588U) {
385                                                 unsigned int i;
386
387                                                 info_align_zero= pad_frames;
388                                                 for(i= 0U; i<channels; ++i)
389                                                         memset(input[i], 0, pad_frames*(bps>>3));
390
391                                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)input, pad_frames)) {
392                                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
393                                                         encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
394                                                         status= ERROR;
395                                                 }
396                                         }
397                                 }
398                                 else {
399                                         if(*options.common.align_reservoir_samples > 0) {
400                                                 size_t bytes_read= fread(ucbuffer, 1U, (*options.common.align_reservoir_samples)*bytes_per_frame, infile);
401
402                                                 FLAC__ASSERT(CHUNK_OF_SAMPLES>=588U);
403                                                 if(bytes_read==0U && ferror(infile)) {
404                                                         fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
405                                                         status= ERROR;
406                                                 }
407                                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame)
408                                                         fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned int)bytes_read, (unsigned int)encoder_wrapper.total_samples_to_encode, (unsigned int)encoder_wrapper.samples_written);
409                                                 else {
410                                                         info_align_carry= *options.common.align_reservoir_samples;
411                                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, true, false, channels, bps);
412                                                 }
413                                         }
414                                 }
415                         }
416
417                         if(status==NORMAL && pad==true) {
418                                 unsigned char tmp;
419
420                                 if(fread(&tmp, 1U, 1U, infile)<1U) {
421                                         fprintf(stderr, "%s: ERROR during read of SSND pad byte\n", encoder_wrapper.inbasefilename);
422                                         status= ERROR;
423                                 }
424                         }
425
426                         got_ssnd_chunk= true;
427                 }
428                 else if(status==NORMAL) { /* other chunk */
429                         if(!strncmp(chunk_id, "COMM", 4))
430                                 fprintf(stderr, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_wrapper.inbasefilename);
431                         else if(!strncmp(chunk_id, "SSND", 4))
432                                 fprintf(stderr, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_wrapper.inbasefilename);
433                         else
434                                 fprintf(stderr, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_wrapper.inbasefilename, chunk_id);
435
436                         /* chunk size */
437                         if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
438                                 status= ERROR;
439                         else {
440                                 unsigned long skip= xx+(xx & 1U);
441
442                                 FLAC__ASSERT(skip<=LONG_MAX);
443                                 while(status==NORMAL && skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
444                                         unsigned int need= min(skip, sizeof ucbuffer);
445                                         if(fread(ucbuffer, 1U, need, infile)<need) {
446                                                 fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_wrapper.inbasefilename);
447                                                 status= ERROR;
448                                         }
449                                         skip-= need;
450                                 }
451                         }
452                 }
453         }
454
455         if(got_ssnd_chunk==false && sample_frames!=0U) {
456                 fprintf(stderr, "%s: ERROR: missing SSND chunk\n", encoder_wrapper.inbasefilename);
457                 status= ERROR;
458         }
459
460         if(encoder_wrapper.encoder) {
461                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
462                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
463         }
464         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
465                 if(status==DONE)
466                         print_stats(&encoder_wrapper);
467                 fprintf(stderr, "\n");
468         }
469
470         if(0 != encoder_wrapper.seek_table)
471                 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
472         if(options.common.verify) {
473                 if(encoder_wrapper.verify_failed) {
474                         fprintf(stderr, "Verify FAILED!  Do not trust %s\n", outfilename);
475                         status= MISMATCH;
476                 }
477         }
478
479         if(infile != stdin)
480                 fclose(infile);
481
482         if(status==DONE) {
483                 if(info_align_carry >= 0)
484                         fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
485                 if(info_align_zero >= 0)
486                         fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
487         }
488         else if(status==ERROR)
489                 unlink(outfilename);
490
491         return status==ERROR || status==MISMATCH;
492 }
493
494 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)
495 {
496         encoder_wrapper_struct encoder_wrapper;
497         FLAC__bool is_unsigned_samples = false;
498         unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
499         size_t bytes_per_wide_sample, bytes_read;
500         FLAC__uint16 x;
501         FLAC__uint32 xx;
502         FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
503         unsigned align_remainder = 0;
504         int info_align_carry = -1, info_align_zero = -1;
505
506         FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
507
508         encoder_wrapper.encoder = 0;
509         encoder_wrapper.verify = options.common.verify;
510         encoder_wrapper.verbose = options.common.verbose;
511         encoder_wrapper.bytes_written = 0;
512         encoder_wrapper.samples_written = 0;
513         encoder_wrapper.stream_offset = 0;
514         encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
515         encoder_wrapper.outfilename = outfilename;
516         encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
517         encoder_wrapper.first_seek_point_to_check = 0;
518         encoder_wrapper.verify_failed = false;
519 #ifdef FLAC__HAS_OGG
520         encoder_wrapper.use_ogg = options.common.use_ogg;
521         encoder_wrapper.ogg_encoder = 0;
522 #endif
523         (void)infilesize;
524         (void)lookahead;
525         (void)lookahead_length;
526
527         if(0 == encoder_wrapper.seek_table) {
528                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
529                 return 1;
530         }
531
532         if(0 == strcmp(outfilename, "-")) {
533                 encoder_wrapper.fout = file__get_binary_stdout();
534         }
535         else {
536                 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
537                         fprintf(stderr, "%s: ERROR: can't open output file %s\n", encoder_wrapper.inbasefilename, outfilename);
538                         if(infile != stdin)
539                                 fclose(infile);
540                         return 1;
541                 }
542         }
543
544         if(!init(&encoder_wrapper))
545                 goto wav_abort_;
546
547         /*
548          * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
549          */
550         while(!feof(infile)) {
551                 if(!read_little_endian_uint32(infile, &xx, true, encoder_wrapper.inbasefilename))
552                         goto wav_abort_;
553                 if(feof(infile))
554                         break;
555                 if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
556                         /* fmt sub-chunk size */
557                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
558                                 goto wav_abort_;
559                         if(xx < 16) {
560                                 fprintf(stderr, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
561                                 goto wav_abort_;
562                         }
563                         else if(xx != 16 && xx != 18) {
564                                 fprintf(stderr, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
565                         }
566                         data_bytes = xx;
567                         /* compression code */
568                         if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
569                                 goto wav_abort_;
570                         if(x != 1) {
571                                 fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
572                                 goto wav_abort_;
573                         }
574                         /* number of channels */
575                         if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
576                                 goto wav_abort_;
577                         if(x == 0 || x > FLAC__MAX_CHANNELS) {
578                                 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
579                                 goto wav_abort_;
580                         }
581                         else if(options.common.sector_align && x != 2) {
582                                 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)x);
583                                 goto wav_abort_;
584                         }
585                         channels = x;
586                         /* sample rate */
587                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
588                                 goto wav_abort_;
589                         if(!FLAC__format_sample_rate_is_valid(xx)) {
590                                 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
591                                 goto wav_abort_;
592                         }
593                         else if(options.common.sector_align && xx != 44100) {
594                                 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)xx);
595                                 goto wav_abort_;
596                         }
597                         sample_rate = xx;
598                         /* avg bytes per second (ignored) */
599                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
600                                 goto wav_abort_;
601                         /* block align (ignored) */
602                         if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
603                                 goto wav_abort_;
604                         /* bits per sample */
605                         if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
606                                 goto wav_abort_;
607                         if(x != 8 && x != 16 && x != 24) {
608                                 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
609                                 goto wav_abort_;
610                         }
611                         else if(options.common.sector_align && x != 16) {
612                                 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)x);
613                                 goto wav_abort_;
614                         }
615                         bps = x;
616                         is_unsigned_samples = (x == 8);
617
618                         /* skip any extra data in the fmt sub-chunk */
619                         data_bytes -= 16;
620                         if(data_bytes > 0) {
621                                 unsigned left, need;
622                                 for(left = data_bytes; left > 0; ) {
623                                         need = min(left, CHUNK_OF_SAMPLES);
624                                         if(fread(ucbuffer, 1U, need, infile) < need) {
625                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
626                                                 goto wav_abort_;
627                                         }
628                                         left -= need;
629                                 }
630                         }
631
632                         got_fmt_chunk = true;
633                 }
634                 else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
635                         /* data size */
636                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
637                                 goto wav_abort_;
638                         data_bytes = xx;
639
640                         bytes_per_wide_sample = channels * (bps >> 3);
641
642                         if(options.common.skip > 0) {
643                                 if(fseek(infile, bytes_per_wide_sample * (unsigned)options.common.skip, SEEK_CUR) < 0) {
644                                         /* can't seek input, read ahead manually... */
645                                         unsigned left, need;
646                                         for(left = (unsigned)options.common.skip; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
647                                                 need = min(left, CHUNK_OF_SAMPLES);
648                                                 if(fread(ucbuffer, bytes_per_wide_sample, need, infile) < need) {
649                                                         fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
650                                                         goto wav_abort_;
651                                                 }
652                                                 left -= need;
653                                         }
654                                 }
655                         }
656
657                         data_bytes -= (unsigned)options.common.skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
658                         encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample + *options.common.align_reservoir_samples;
659                         if(options.common.sector_align) {
660                                 align_remainder = (unsigned)(encoder_wrapper.total_samples_to_encode % 588);
661                                 if(options.common.is_last_file)
662                                         encoder_wrapper.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
663                                 else
664                                         encoder_wrapper.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
665                         }
666
667                         /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
668                         encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44;
669
670                         if(!init_encoder(options.common, channels, bps, sample_rate, &encoder_wrapper))
671                                 goto wav_abort_;
672
673                         /*
674                          * first do any samples in the reservoir
675                          */
676                         if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
677                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
678                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
679                                         encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
680                                         goto wav_abort_;
681                                 }
682                         }
683
684                         /*
685                          * decrement the data_bytes counter if we need to align the file
686                          */
687                         if(options.common.sector_align) {
688                                 if(options.common.is_last_file) {
689                                         *options.common.align_reservoir_samples = 0;
690                                 }
691                                 else {
692                                         *options.common.align_reservoir_samples = align_remainder;
693                                         data_bytes -= (*options.common.align_reservoir_samples) * bytes_per_wide_sample;
694                                 }
695                         }
696
697                         /*
698                          * now do from the file
699                          */
700                         while(data_bytes > 0) {
701                                 bytes_read = fread(ucbuffer, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
702                                 if(bytes_read == 0) {
703                                         if(ferror(infile)) {
704                                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
705                                                 goto wav_abort_;
706                                         }
707                                         else if(feof(infile)) {
708                                                 fprintf(stderr, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
709                                                 data_bytes = 0;
710                                         }
711                                 }
712                                 else {
713                                         if(bytes_read % bytes_per_wide_sample != 0) {
714                                                 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
715                                                 goto wav_abort_;
716                                         }
717                                         else {
718                                                 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
719                                                 format_input(input, wide_samples, false, is_unsigned_samples, channels, bps);
720
721                                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
722                                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
723                                                         encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
724                                                         goto wav_abort_;
725                                                 }
726                                                 data_bytes -= bytes_read;
727                                         }
728                                 }
729                         }
730
731                         /*
732                          * now read unaligned samples into reservoir or pad with zeroes if necessary
733                          */
734                         if(options.common.sector_align) {
735                                 if(options.common.is_last_file) {
736                                         unsigned wide_samples = 588 - align_remainder;
737                                         if(wide_samples < 588) {
738                                                 unsigned channel;
739
740                                                 info_align_zero = wide_samples;
741                                                 data_bytes = wide_samples * (bps >> 3);
742                                                 for(channel = 0; channel < channels; channel++)
743                                                         memset(input[channel], 0, data_bytes);
744
745                                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
746                                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
747                                                         encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
748                                                         goto wav_abort_;
749                                                 }
750                                         }
751                                 }
752                                 else {
753                                         if(*options.common.align_reservoir_samples > 0) {
754                                                 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
755                                                 bytes_read = fread(ucbuffer, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
756                                                 if(bytes_read == 0 && ferror(infile)) {
757                                                         fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
758                                                         goto wav_abort_;
759                                                 }
760                                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
761                                                         fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
762                                                         data_bytes = 0;
763                                                 }
764                                                 else {
765                                                         info_align_carry = *options.common.align_reservoir_samples;
766                                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, is_unsigned_samples, channels, bps);
767                                                 }
768                                         }
769                                 }
770                         }
771
772                         got_data_chunk = true;
773                 }
774                 else {
775                         if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
776                                 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_wrapper.inbasefilename);
777                         }
778                         else if(xx == 0x61746164) { /* "data" */
779                                 if(got_data_chunk) {
780                                         fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_wrapper.inbasefilename);
781                                 }
782                                 else if(!got_fmt_chunk) {
783                                         fprintf(stderr, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_wrapper.inbasefilename);
784                                         goto wav_abort_;
785                                 }
786                                 else {
787                                         FLAC__ASSERT(0);
788                                 }
789                         }
790                         else {
791                                 fprintf(stderr, "%s: WARNING: skipping unknown sub-chunk '%c%c%c%c'\n", encoder_wrapper.inbasefilename, (char)(xx&255), (char)((xx>>8)&255), (char)((xx>>16)&255), (char)(xx>>24));
792                         }
793                         /* sub-chunk size */
794                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
795                                 goto wav_abort_;
796                         if(fseek(infile, xx, SEEK_CUR) < 0) {
797                                 /* can't seek input, read ahead manually... */
798                                 unsigned left, need;
799                                 const unsigned chunk = sizeof(ucbuffer);
800                                 for(left = xx; left > 0; ) {
801                                         need = min(left, chunk);
802                                         if(fread(ucbuffer, 1, need, infile) < need) {
803                                                 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_wrapper.inbasefilename);
804                                                 goto wav_abort_;
805                                         }
806                                         left -= need;
807                                 }
808                         }
809                 }
810         }
811
812         if(encoder_wrapper.encoder) {
813                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
814                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
815         }
816         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
817                 print_stats(&encoder_wrapper);
818                 fprintf(stderr, "\n");
819         }
820         if(0 != encoder_wrapper.seek_table)
821                 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
822         if(options.common.verify) {
823                 if(encoder_wrapper.verify_failed) {
824                         fprintf(stderr, "Verify FAILED!  Do not trust %s\n", outfilename);
825                         return 1;
826                 }
827         }
828         if(info_align_carry >= 0)
829                 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
830         if(info_align_zero >= 0)
831                 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
832         if(infile != stdin)
833                 fclose(infile);
834         return 0;
835 wav_abort_:
836         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
837                 fprintf(stderr, "\n");
838         if(encoder_wrapper.encoder) {
839                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
840                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
841         }
842         if(0 != encoder_wrapper.seek_table)
843                 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
844         if(options.common.verify) {
845                 if(encoder_wrapper.verify_failed) {
846                         fprintf(stderr, "Verify FAILED!  Do not trust %s\n", outfilename);
847                         return 1;
848                 }
849         }
850         if(infile != stdin)
851                 fclose(infile);
852         unlink(outfilename);
853         return 1;
854 }
855
856 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)
857 {
858         encoder_wrapper_struct encoder_wrapper;
859         size_t bytes_read;
860         const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
861         unsigned align_remainder = 0;
862         int info_align_carry = -1, info_align_zero = -1;
863
864         FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
865         FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
866         FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
867         FLAC__ASSERT(!options.common.sector_align || options.sample_rate == 44100);
868         FLAC__ASSERT(!options.common.sector_align || infilesize >= 0);
869
870         encoder_wrapper.encoder = 0;
871         encoder_wrapper.verify = options.common.verify;
872         encoder_wrapper.verbose = options.common.verbose;
873         encoder_wrapper.bytes_written = 0;
874         encoder_wrapper.samples_written = 0;
875         encoder_wrapper.stream_offset = 0;
876         encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
877         encoder_wrapper.outfilename = outfilename;
878         encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
879         encoder_wrapper.first_seek_point_to_check = 0;
880         encoder_wrapper.verify_failed = false;
881 #ifdef FLAC__HAS_OGG
882         encoder_wrapper.use_ogg = options.common.use_ogg;
883         encoder_wrapper.ogg_encoder = 0;
884 #endif
885
886         if(0 == encoder_wrapper.seek_table) {
887                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
888                 return 1;
889         }
890
891         if(0 == strcmp(outfilename, "-")) {
892                 encoder_wrapper.fout = file__get_binary_stdout();
893         }
894         else {
895                 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
896                         fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
897                         if(infile != stdin)
898                                 fclose(infile);
899                         return 1;
900                 }
901         }
902
903         if(!init(&encoder_wrapper))
904                 goto raw_abort_;
905
906         /* get the file length */
907         if(infilesize < 0) {
908                 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
909         }
910         else {
911                 if(options.common.sector_align) {
912                         FLAC__ASSERT(options.common.skip == 0);
913                         encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
914                         align_remainder = (unsigned)(encoder_wrapper.total_samples_to_encode % 588);
915                         if(options.common.is_last_file)
916                                 encoder_wrapper.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
917                         else
918                                 encoder_wrapper.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
919                 }
920                 else {
921                         encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - options.common.skip;
922                 }
923
924                 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample;
925         }
926
927         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
928                 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
929
930         if(options.common.skip > 0) {
931                 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)options.common.skip;
932                 if(skip_bytes > lookahead_length) {
933                         skip_bytes -= lookahead_length;
934                         lookahead_length = 0;
935                         if(fseek(infile, (long)skip_bytes, SEEK_CUR) < 0) {
936                                 /* can't seek input, read ahead manually... */
937                                 unsigned left, need;
938                                 const unsigned chunk = sizeof(ucbuffer);
939                                 for(left = skip_bytes; left > 0; ) {
940                                         need = min(left, chunk);
941                                         if(fread(ucbuffer, 1, need, infile) < need) {
942                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
943                                                 goto raw_abort_;
944                                         }
945                                         left -= need;
946                                 }
947                         }
948                 }
949                 else {
950                         lookahead += skip_bytes;
951                         lookahead_length -= skip_bytes;
952                 }
953         }
954
955         if(!init_encoder(options.common, options.channels, options.bps, options.sample_rate, &encoder_wrapper))
956                 goto raw_abort_;
957
958         /*
959          * first do any samples in the reservoir
960          */
961         if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
962                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
963                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
964                         encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
965                         goto raw_abort_;
966                 }
967         }
968
969         /*
970          * decrement infilesize if we need to align the file
971          */
972         if(options.common.sector_align) {
973                 FLAC__ASSERT(infilesize >= 0);
974                 if(options.common.is_last_file) {
975                         *options.common.align_reservoir_samples = 0;
976                 }
977                 else {
978                         *options.common.align_reservoir_samples = align_remainder;
979                         infilesize -= (long)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
980                 }
981         }
982
983         /*
984          * now do from the file
985          */
986         while(!feof(infile)) {
987                 if(lookahead_length > 0) {
988                         FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
989                         memcpy(ucbuffer, lookahead, lookahead_length);
990                         bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
991                         if(ferror(infile)) {
992                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
993                                 goto raw_abort_;
994                         }
995                         lookahead_length = 0;
996                 }
997                 else
998                         bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
999
1000                 if(bytes_read == 0) {
1001                         if(ferror(infile)) {
1002                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
1003                                 goto raw_abort_;
1004                         }
1005                 }
1006                 else if(bytes_read % bytes_per_wide_sample != 0) {
1007                         fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
1008                         goto raw_abort_;
1009                 }
1010                 else {
1011                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1012                         format_input(input, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
1013
1014                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
1015                                 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
1016                                 encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
1017                                 goto raw_abort_;
1018                         }
1019                 }
1020         }
1021
1022         /*
1023          * now read unaligned samples into reservoir or pad with zeroes if necessary
1024          */
1025         if(options.common.sector_align) {
1026                 if(options.common.is_last_file) {
1027                         unsigned wide_samples = 588 - align_remainder;
1028                         if(wide_samples < 588) {
1029                                 unsigned channel, data_bytes;
1030
1031                                 info_align_zero = wide_samples;
1032                                 data_bytes = wide_samples * (options.bps >> 3);
1033                                 for(channel = 0; channel < options.channels; channel++)
1034                                         memset(input[channel], 0, data_bytes);
1035
1036                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
1037                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
1038                                         encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
1039                                         goto raw_abort_;
1040                                 }
1041                         }
1042                 }
1043                 else {
1044                         if(*options.common.align_reservoir_samples > 0) {
1045                                 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1046                                 bytes_read = fread(ucbuffer, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
1047                                 if(bytes_read == 0 && ferror(infile)) {
1048                                         fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
1049                                         goto raw_abort_;
1050                                 }
1051                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
1052                                         fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
1053                                 }
1054                                 else {
1055                                         info_align_carry = *options.common.align_reservoir_samples;
1056                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, options.is_unsigned_samples, options.channels, options.bps);
1057                                 }
1058                         }
1059                 }
1060         }
1061
1062         if(encoder_wrapper.encoder) {
1063                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
1064                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
1065         }
1066         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
1067                 print_stats(&encoder_wrapper);
1068                 fprintf(stderr, "\n");
1069         }
1070         if(0 != encoder_wrapper.seek_table)
1071                 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
1072         if(options.common.verify) {
1073                 if(encoder_wrapper.verify_failed) {
1074                         fprintf(stderr, "Verify FAILED!  Do not trust %s\n", outfilename);
1075                         return 1;
1076                 }
1077         }
1078         if(info_align_carry >= 0)
1079                 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
1080         if(info_align_zero >= 0)
1081                 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
1082         if(infile != stdin)
1083                 fclose(infile);
1084         return 0;
1085 raw_abort_:
1086         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
1087                 fprintf(stderr, "\n");
1088         if(encoder_wrapper.encoder) {
1089                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
1090                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
1091         }
1092         if(0 != encoder_wrapper.seek_table)
1093                 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
1094         if(options.common.verify) {
1095                 if(encoder_wrapper.verify_failed) {
1096                         fprintf(stderr, "Verify FAILED!  Do not trust %s\n", outfilename);
1097                         return 1;
1098                 }
1099         }
1100         if(infile != stdin)
1101                 fclose(infile);
1102         unlink(outfilename);
1103         return 1;
1104 }
1105
1106 FLAC__bool init(encoder_wrapper_struct *encoder_wrapper)
1107 {
1108         unsigned i;
1109         FLAC__uint32 test = 1;
1110
1111         is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
1112
1113         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1114                 input[i] = &(in[i][0]);
1115
1116         encoder_wrapper->encoder = FLAC__stream_encoder_new();
1117         if(0 == encoder_wrapper->encoder) {
1118                 fprintf(stderr, "%s: ERROR creating the encoder instance\n", encoder_wrapper->inbasefilename);
1119                 return false;
1120         }
1121
1122         return true;
1123 }
1124
1125 FLAC__bool init_encoder(encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper)
1126 {
1127         unsigned num_metadata;
1128         FLAC__StreamMetadata padding;
1129         FLAC__StreamMetadata *metadata[2];
1130
1131         if(channels != 2)
1132                 options.do_mid_side = options.loose_mid_side = false;
1133
1134         if(!convert_to_seek_table(options.requested_seek_points, options.num_requested_seek_points, encoder_wrapper->total_samples_to_encode, encoder_wrapper->seek_table)) {
1135                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper->inbasefilename);
1136                 return false;
1137         }
1138
1139         num_metadata = 0;
1140         if(encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1141                 encoder_wrapper->seek_table->is_last = false; /* the encoder will set this for us */
1142                 metadata[num_metadata++] = encoder_wrapper->seek_table;
1143         }
1144         if(options.padding > 0) {
1145                 padding.is_last = false; /* the encoder will set this for us */
1146                 padding.type = FLAC__METADATA_TYPE_PADDING;
1147                 padding.length = (unsigned)options.padding;
1148                 metadata[num_metadata++] = &padding;
1149         }
1150
1151         FLAC__stream_encoder_set_verify(encoder_wrapper->encoder, options.verify);
1152         FLAC__stream_encoder_set_streamable_subset(encoder_wrapper->encoder, !options.lax);
1153         FLAC__stream_encoder_set_do_mid_side_stereo(encoder_wrapper->encoder, options.do_mid_side);
1154         FLAC__stream_encoder_set_loose_mid_side_stereo(encoder_wrapper->encoder, options.loose_mid_side);
1155         FLAC__stream_encoder_set_channels(encoder_wrapper->encoder, channels);
1156         FLAC__stream_encoder_set_bits_per_sample(encoder_wrapper->encoder, bps);
1157         FLAC__stream_encoder_set_sample_rate(encoder_wrapper->encoder, sample_rate);
1158         FLAC__stream_encoder_set_blocksize(encoder_wrapper->encoder, options.blocksize);
1159         FLAC__stream_encoder_set_max_lpc_order(encoder_wrapper->encoder, options.max_lpc_order);
1160         FLAC__stream_encoder_set_qlp_coeff_precision(encoder_wrapper->encoder, options.qlp_coeff_precision);
1161         FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder_wrapper->encoder, options.do_qlp_coeff_prec_search);
1162         FLAC__stream_encoder_set_do_escape_coding(encoder_wrapper->encoder, options.do_escape_coding);
1163         FLAC__stream_encoder_set_do_exhaustive_model_search(encoder_wrapper->encoder, options.do_exhaustive_model_search);
1164         FLAC__stream_encoder_set_min_residual_partition_order(encoder_wrapper->encoder, options.min_residual_partition_order);
1165         FLAC__stream_encoder_set_max_residual_partition_order(encoder_wrapper->encoder, options.max_residual_partition_order);
1166         FLAC__stream_encoder_set_rice_parameter_search_dist(encoder_wrapper->encoder, options.rice_parameter_search_dist);
1167         FLAC__stream_encoder_set_total_samples_estimate(encoder_wrapper->encoder, encoder_wrapper->total_samples_to_encode);
1168         FLAC__stream_encoder_set_metadata(encoder_wrapper->encoder, (num_metadata > 0)? metadata : 0, num_metadata);
1169         FLAC__stream_encoder_set_write_callback(encoder_wrapper->encoder, write_callback);
1170         FLAC__stream_encoder_set_metadata_callback(encoder_wrapper->encoder, metadata_callback);
1171         FLAC__stream_encoder_set_client_data(encoder_wrapper->encoder, encoder_wrapper);
1172
1173         if(FLAC__stream_encoder_init(encoder_wrapper->encoder) != FLAC__STREAM_ENCODER_OK) {
1174                 fprintf(stderr, "%s: ERROR initializing encoder, state = %d:%s\n", encoder_wrapper->inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper->encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper->encoder)]);
1175                 encoder_wrapper->verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
1176                 return false;
1177         }
1178
1179         /* the above call writes all the metadata, so we save the stream offset now */
1180         encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
1181
1182         return true;
1183 }
1184
1185 FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, FLAC__StreamMetadata *seek_table)
1186 {
1187         unsigned i, real_points, placeholders;
1188         char *pt = requested_seek_points, *q;
1189
1190         if(num_requested_seek_points == 0)
1191                 return true;
1192
1193         if(num_requested_seek_points < 0) {
1194                 strcpy(requested_seek_points, "100x<");
1195                 num_requested_seek_points = 1;
1196         }
1197
1198         /* first count how many individual seek points we may need */
1199         real_points = placeholders = 0;
1200         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
1201                 q = strchr(pt, '<');
1202                 FLAC__ASSERT(0 != q);
1203                 *q = '\0';
1204
1205                 if(0 == strcmp(pt, "X")) { /* -S X */
1206                         placeholders++;
1207                 }
1208                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
1209                         if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
1210                                 real_points += (unsigned)atoi(pt);
1211                 }
1212                 else { /* -S # */
1213                         real_points++;
1214                 }
1215                 *q++ = '<';
1216
1217                 pt = q;
1218         }
1219         pt = requested_seek_points;
1220
1221         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
1222                 q = strchr(pt, '<');
1223                 FLAC__ASSERT(0 != q);
1224                 *q++ = '\0';
1225
1226                 if(0 == strcmp(pt, "X")) { /* -S X */
1227                         if(!FLAC__metadata_object_seektable_template_append_placeholders(seek_table, 1))
1228                                 return false;
1229                 }
1230                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
1231                         if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
1232                                 if(!FLAC__metadata_object_seektable_template_append_spaced_points(seek_table, atoi(pt), stream_samples))
1233                                         return false;
1234                         }
1235                 }
1236                 else { /* -S # */
1237                         FLAC__uint64 n = (unsigned)atoi(pt);
1238                         if(!FLAC__metadata_object_seektable_template_append_point(seek_table, n))
1239                                 return false;
1240                 }
1241
1242                 pt = q;
1243         }
1244
1245         if(!FLAC__metadata_object_seektable_template_sort(seek_table, /*compact=*/true))
1246                 return false;
1247
1248         return true;
1249 }
1250
1251 void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps)
1252 {
1253         unsigned wide_sample, sample, channel, byte;
1254
1255         if(bps == 8) {
1256                 if(is_unsigned_samples) {
1257                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1258                                 for(channel = 0; channel < channels; channel++, sample++)
1259                                         dest[channel][wide_sample] = (FLAC__int32)ucbuffer[sample] - 0x80;
1260                 }
1261                 else {
1262                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1263                                 for(channel = 0; channel < channels; channel++, sample++)
1264                                         dest[channel][wide_sample] = (FLAC__int32)scbuffer[sample];
1265                 }
1266         }
1267         else if(bps == 16) {
1268                 if(is_big_endian != is_big_endian_host) {
1269                         unsigned char tmp;
1270                         const unsigned bytes = wide_samples * channels * (bps >> 3);
1271                         for(byte = 0; byte < bytes; byte += 2) {
1272                                 tmp = ucbuffer[byte];
1273                                 ucbuffer[byte] = ucbuffer[byte+1];
1274                                 ucbuffer[byte+1] = tmp;
1275                         }
1276                 }
1277                 if(is_unsigned_samples) {
1278                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1279                                 for(channel = 0; channel < channels; channel++, sample++)
1280                                         dest[channel][wide_sample] = (FLAC__int32)usbuffer[sample] - 0x8000;
1281                 }
1282                 else {
1283                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1284                                 for(channel = 0; channel < channels; channel++, sample++)
1285                                         dest[channel][wide_sample] = (FLAC__int32)ssbuffer[sample];
1286                 }
1287         }
1288         else if(bps == 24) {
1289                 if(!is_big_endian) {
1290                         unsigned char tmp;
1291                         const unsigned bytes = wide_samples * channels * (bps >> 3);
1292                         for(byte = 0; byte < bytes; byte += 3) {
1293                                 tmp = ucbuffer[byte];
1294                                 ucbuffer[byte] = ucbuffer[byte+2];
1295                                 ucbuffer[byte+2] = tmp;
1296                         }
1297                 }
1298                 if(is_unsigned_samples) {
1299                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1300                                 for(channel = 0; channel < channels; channel++, sample++) {
1301                                         dest[channel][wide_sample]  = ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1302                                         dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1303                                         dest[channel][wide_sample] |= ucbuffer[byte++];
1304                                         dest[channel][wide_sample] -= 0x800000;
1305                                 }
1306                 }
1307                 else {
1308                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1309                                 for(channel = 0; channel < channels; channel++, sample++) {
1310                                         dest[channel][wide_sample]  = scbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1311                                         dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1312                                         dest[channel][wide_sample] |= ucbuffer[byte++];
1313                                 }
1314                 }
1315         }
1316         else {
1317                 FLAC__ASSERT(0);
1318         }
1319 }
1320
1321 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
1322 {
1323         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1324         const unsigned mask = (FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
1325
1326         /* mark the current seek point if hit (if stream_offset == 0 that means we're still writing metadata and haven't hit the first frame yet) */
1327         if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1328                 /*@@@ WATCHOUT: assumes the encoder is fixed-blocksize, which will be true indefinitely: */
1329                 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1330                 const FLAC__uint64 frame_first_sample = (FLAC__uint64)current_frame * (FLAC__uint64)blocksize;
1331                 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
1332                 FLAC__uint64 test_sample;
1333                 unsigned i;
1334                 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1335                         test_sample = encoder_wrapper->seek_table->data.seek_table.points[i].sample_number;
1336                         if(test_sample > frame_last_sample) {
1337                                 break;
1338                         }
1339                         else if(test_sample >= frame_first_sample) {
1340                                 encoder_wrapper->seek_table->data.seek_table.points[i].sample_number = frame_first_sample;
1341                                 encoder_wrapper->seek_table->data.seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
1342                                 encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples = blocksize;
1343                                 encoder_wrapper->first_seek_point_to_check++;
1344                                 /* DO NOT: "break;" and here's why:
1345                                  * The seektable template may contain more than one target
1346                                  * sample for any given frame; we will keep looping, generating
1347                                  * duplicate seekpoints for them, and we'll clean it up later,
1348                                  * just before writing the seektable back to the metadata.
1349                                  */
1350                         }
1351                         else {
1352                                 encoder_wrapper->first_seek_point_to_check++;
1353                         }
1354                 }
1355         }
1356
1357         encoder_wrapper->bytes_written += bytes;
1358         encoder_wrapper->samples_written += samples;
1359         encoder_wrapper->current_frame = current_frame;
1360
1361         if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
1362                 print_stats(encoder_wrapper);
1363
1364         if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_wrapper->fout) == bytes)
1365                 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1366         else
1367                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1368 }
1369
1370 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
1371 {
1372         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1373         FLAC__byte b;
1374         FILE *f = encoder_wrapper->fout;
1375         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
1376         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
1377         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
1378
1379         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
1380
1381         /*
1382          * If we are writing to an ogg stream, there is no need to go back
1383          * and update the STREAMINFO or SEEKTABLE blocks; the values we would
1384          * update are not necessary with Ogg as the transport.  We can't do
1385          * it reliably anyway without knowing the Ogg structure.
1386          */
1387 #ifdef FLAC__HAS_OGG
1388         if(encoder_wrapper->use_ogg)
1389                 return;
1390 #endif
1391
1392         /*
1393          * we get called by the encoder when the encoding process has
1394          * finished so that we can update the STREAMINFO and SEEKTABLE
1395          * blocks.
1396          */
1397
1398         (void)encoder; /* silence compiler warning about unused parameter */
1399
1400         if(f != stdout) {
1401                 fclose(encoder_wrapper->fout);
1402                 if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
1403                         return;
1404         }
1405
1406         /* all this is based on intimate knowledge of the stream header
1407          * layout, but a change to the header format that would break this
1408          * would also break all streams encoded in the previous format.
1409          */
1410
1411         if(-1 == fseek(f, 26, SEEK_SET)) goto end_;
1412         fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
1413
1414         /* if we get this far we know we can seek so no need to check the
1415          * return value from fseek()
1416          */
1417         fseek(f, 21, SEEK_SET);
1418         if(fread(&b, 1, 1, f) != 1) goto framesize_;
1419         fseek(f, 21, SEEK_SET);
1420         b = (b & 0xf0) | (FLAC__byte)((samples >> 32) & 0x0F);
1421         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1422         b = (FLAC__byte)((samples >> 24) & 0xFF);
1423         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1424         b = (FLAC__byte)((samples >> 16) & 0xFF);
1425         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1426         b = (FLAC__byte)((samples >> 8) & 0xFF);
1427         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1428         b = (FLAC__byte)(samples & 0xFF);
1429         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1430
1431 framesize_:
1432         fseek(f, 12, SEEK_SET);
1433         b = (FLAC__byte)((min_framesize >> 16) & 0xFF);
1434         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1435         b = (FLAC__byte)((min_framesize >> 8) & 0xFF);
1436         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1437         b = (FLAC__byte)(min_framesize & 0xFF);
1438         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1439         b = (FLAC__byte)((max_framesize >> 16) & 0xFF);
1440         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1441         b = (FLAC__byte)((max_framesize >> 8) & 0xFF);
1442         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1443         b = (FLAC__byte)(max_framesize & 0xFF);
1444         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1445
1446 seektable_:
1447         if(encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1448                 long pos;
1449                 unsigned i;
1450
1451                 (void)FLAC__metadata_object_seektable_template_sort(encoder_wrapper->seek_table, /*compact=*/false);
1452
1453                 FLAC__ASSERT(FLAC__metadata_object_seektable_is_legal(encoder_wrapper->seek_table));
1454
1455                 /* convert any unused seek points to placeholders */
1456                 for(i = 0; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1457                         if(encoder_wrapper->seek_table->data.seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
1458                                 break;
1459                         else if(encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples == 0)
1460                                 encoder_wrapper->seek_table->data.seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
1461                 }
1462
1463                 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
1464                 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1465                 pos += metadata->length;
1466                 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1467                 fseek(f, pos, SEEK_SET);
1468                 for(i = 0; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1469                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table->data.seek_table.points[i].sample_number)) goto end_;
1470                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table->data.seek_table.points[i].stream_offset)) goto end_;
1471                         if(!write_big_endian_uint16(f, (FLAC__uint16)encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples)) goto end_;
1472                 }
1473         }
1474
1475 end_:
1476         fclose(f);
1477         return;
1478 }
1479
1480 #if 0
1481 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
1482 {
1483                         fprintf(stderr, "\n%s: ERROR: mismatch in decoded data, verify FAILED!\n", encoder_wrapper->inbasefilename);
1484                         fprintf(stderr, "       Please submit a bug report to\n");
1485                         fprintf(stderr, "           http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1486                         fprintf(stderr, "       Make sure to include an email contact in the comment and/or use the\n");
1487                         fprintf(stderr, "       \"Monitor\" feature to monitor the bug status.\n");
1488
1489                         fprintf(stderr, "       Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)frame->header.number.sample_number + sample, (unsigned)frame->header.number.sample_number / FLAC__stream_decoder_get_blocksize(decoder), channel, sample, expect, got);
1490 }
1491 #endif
1492
1493 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1494 {
1495 #if defined _MSC_VER || defined __MINGW32__
1496         /* with VC++ you have to spoon feed it the casting */
1497         const double progress = (double)(FLAC__int64)encoder_wrapper->samples_written / (double)(FLAC__int64)encoder_wrapper->total_samples_to_encode;
1498         const double ratio = (double)(FLAC__int64)encoder_wrapper->bytes_written / ((double)(FLAC__int64)encoder_wrapper->unencoded_size * progress);
1499 #else
1500         const double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1501         const double ratio = (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress);
1502 #endif
1503
1504         if(encoder_wrapper->samples_written == encoder_wrapper->total_samples_to_encode) {
1505                 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1506                         encoder_wrapper->inbasefilename,
1507                         encoder_wrapper->verify? (encoder_wrapper->verify_failed? " Verify FAILED!" : " Verify OK,") : "",
1508                         (unsigned)encoder_wrapper->bytes_written,
1509                         ratio
1510                 );
1511         }
1512         else {
1513                 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_wrapper->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1514         }
1515 }
1516
1517 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1518 {
1519         size_t bytes_read = fread(val, 1, 2, f);
1520
1521         if(bytes_read == 0) {
1522                 if(!eof_ok) {
1523                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1524                         return false;
1525                 }
1526                 else
1527                         return true;
1528         }
1529         else if(bytes_read < 2) {
1530                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1531                 return false;
1532         }
1533         else {
1534                 if(is_big_endian_host) {
1535                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1536                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1537                 }
1538                 return true;
1539         }
1540 }
1541
1542 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1543 {
1544         size_t bytes_read = fread(val, 1, 4, f);
1545
1546         if(bytes_read == 0) {
1547                 if(!eof_ok) {
1548                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1549                         return false;
1550                 }
1551                 else
1552                         return true;
1553         }
1554         else if(bytes_read < 4) {
1555                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1556                 return false;
1557         }
1558         else {
1559                 if(is_big_endian_host) {
1560                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1561                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1562                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1563                 }
1564                 return true;
1565         }
1566 }
1567
1568 FLAC__bool
1569 read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1570 {
1571         unsigned char buf[4];
1572         size_t bytes_read= fread(buf, 1, 2, f);
1573
1574         if(bytes_read==0U && eof_ok)
1575                 return true;
1576         else if(bytes_read<2U) {
1577                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1578                 return false;
1579         }
1580
1581         /* this is independent of host endianness */
1582         *val= (FLAC__uint16)(buf[0])<<8 | buf[1];
1583
1584         return true;
1585 }
1586
1587 FLAC__bool
1588 read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1589 {
1590         unsigned char buf[4];
1591         size_t bytes_read= fread(buf, 1, 4, f);
1592
1593         if(bytes_read==0U && eof_ok)
1594                 return true;
1595         else if(bytes_read<4U) {
1596                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1597                 return false;
1598         }
1599
1600         /* this is independent of host endianness */
1601         *val= (FLAC__uint32)(buf[0])<<24 | (FLAC__uint32)(buf[1])<<16 |
1602                 (FLAC__uint32)(buf[2])<<8 | buf[3];
1603
1604         return true;
1605 }
1606
1607 FLAC__bool
1608 read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1609         /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
1610          * convert it into an integral value and store in 'val'.  Return false if only
1611          * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f' and 'eof_ok' is
1612          * false, or if the value is negative, between zero and one, or too large to be
1613          * represented by 'val'; return true otherwise.
1614          */
1615 {
1616         unsigned int i;
1617         unsigned char buf[10];
1618         size_t bytes_read= fread(buf, 1U, 10U, f);
1619         FLAC__int16 e= ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
1620         FLAC__int16 shift= 63-e;
1621         FLAC__uint64 p= 0U;
1622
1623         if(bytes_read==0U && eof_ok)
1624                 return true;
1625         else if(bytes_read<10U) {
1626                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1627                 return false;
1628         }
1629         else if((buf[0]>>7)==1U || e<0 || e>63) {
1630                 fprintf(stderr, "%s: ERROR: invalid floating-point value\n", fn);
1631                 return false;
1632         }
1633
1634         for(i= 0U; i<8U; ++i)
1635                 p|= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
1636         *val= (FLAC__uint32)(p>>shift)+(p>>(shift-1) & 0x1);
1637
1638         return true;
1639 }
1640
1641 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
1642 {
1643         if(!is_big_endian_host) {
1644                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1645                 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1646         }
1647         return fwrite(&val, 1, 2, f) == 2;
1648 }
1649
1650 FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val)
1651 {
1652         if(!is_big_endian_host) {
1653                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1654                 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1655                 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1656                 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1657                 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1658         }
1659         return fwrite(&val, 1, 8, f) == 8;
1660 }