revamp the ordinal types
[flac.git] / src / flac / encode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001  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 <math.h> /* for floor() */
26 #include <stdio.h> /* for FILE et al. */
27 #include <stdlib.h> /* for malloc */
28 #include <string.h> /* for strcmp() */
29 #include "FLAC/all.h"
30 #include "encode.h"
31 #include "file.h"
32
33 #ifdef min
34 #undef min
35 #endif
36 #define min(x,y) ((x)<(y)?(x):(y))
37
38 #define CHUNK_OF_SAMPLES 2048
39
40 typedef enum {
41         FLAC__VERIFY_OK,
42         FLAC__VERIFY_FAILED_IN_FRAME,
43         FLAC__VERIFY_FAILED_IN_METADATA
44 } verify_code;
45
46 static const char *verify_code_string[] = {
47         "FLAC__VERIFY_OK",
48         "FLAC__VERIFY_FAILED_IN_FRAME",
49         "FLAC__VERIFY_FAILED_IN_METADATA"
50 };
51
52 typedef struct {
53         FLAC__int32 *original[FLAC__MAX_CHANNELS];
54         unsigned size; /* of each original[] in samples */
55         unsigned tail; /* in wide samples */
56         const FLAC__byte *encoded_signal;
57         unsigned encoded_signal_capacity;
58         unsigned encoded_bytes;
59         FLAC__bool into_frames;
60         verify_code result;
61         FLAC__StreamDecoder *decoder;
62 } verify_fifo_struct;
63
64 typedef struct {
65         const char *inbasefilename;
66         FILE *fout;
67         const char *outfilename;
68         FLAC__StreamEncoder *encoder;
69         FLAC__bool verify;
70         FLAC__bool verbose;
71         FLAC__uint64 unencoded_size;
72         FLAC__uint64 total_samples_to_encode;
73         FLAC__uint64 bytes_written;
74         FLAC__uint64 samples_written;
75         FLAC__uint64 stream_offset; /* i.e. number of bytes before the first byte of the the first frame's header */
76         unsigned current_frame;
77         verify_fifo_struct verify_fifo;
78         FLAC__StreamMetaData_SeekTable seek_table;
79         unsigned first_seek_point_to_check;
80 } encoder_wrapper_struct;
81
82 static FLAC__bool is_big_endian_host;
83
84 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__MAX_BITS_PER_SAMPLE+7)/8)];
85 static signed char *scbuffer = (signed char *)ucbuffer;
86 static FLAC__uint16 *usbuffer = (FLAC__uint16 *)ucbuffer;
87 static FLAC__int16 *ssbuffer = (FLAC__int16 *)ucbuffer;
88
89 static FLAC__int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
90 static FLAC__int32 *input[FLAC__MAX_CHANNELS];
91
92 /* local routines */
93 static FLAC__bool init(encoder_wrapper_struct *encoder_wrapper);
94 static FLAC__bool init_encoder(FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, unsigned padding, char *requested_seek_points, int num_requested_seek_points, encoder_wrapper_struct *encoder_wrapper);
95 static FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table);
96 static void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, FLAC__uint64 sample, FLAC__uint64 stream_samples, FLAC__uint64 blocksize);
97 static int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r);
98 static void format_input(unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
99 static FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
100 static void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
101 static FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
102 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data);
103 static void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
104 static void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
105 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
106 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
107 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
108 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
109 static FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val);
110
111 int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, FLAC__bool verbose, FLAC__uint64 skip, FLAC__bool verify, FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned padding, char *requested_seek_points, int num_requested_seek_points)
112 {
113         encoder_wrapper_struct encoder_wrapper;
114         FLAC__bool is_unsigned_samples = false;
115         unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
116         size_t bytes_per_wide_sample, bytes_read;
117         FLAC__uint16 x;
118         FLAC__uint32 xx;
119         FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
120
121         encoder_wrapper.encoder = 0;
122         encoder_wrapper.verify = verify;
123         encoder_wrapper.verbose = verbose;
124         encoder_wrapper.bytes_written = 0;
125         encoder_wrapper.samples_written = 0;
126         encoder_wrapper.stream_offset = 0;
127         encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
128         encoder_wrapper.outfilename = outfilename;
129         encoder_wrapper.seek_table.points = 0;
130         encoder_wrapper.first_seek_point_to_check = 0;
131         (void)infilesize;
132         (void)lookahead;
133         (void)lookahead_length;
134
135         if(0 == strcmp(outfilename, "-")) {
136                 encoder_wrapper.fout = stdout;
137         }
138         else {
139                 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
140                         fprintf(stderr, "%s: ERROR: can't open output file %s\n", encoder_wrapper.inbasefilename, outfilename);
141                         fclose(infile);
142                         return 1;
143                 }
144         }
145
146         if(!init(&encoder_wrapper))
147                 goto wav_abort_;
148
149         /*
150          * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
151          */
152         while(!feof(infile)) {
153                 if(!read_little_endian_uint32(infile, &xx, true, encoder_wrapper.inbasefilename))
154                         goto wav_abort_;
155                 if(feof(infile))
156                         break;
157                 if(xx == 0x20746d66) { /* "fmt " */
158                         if(got_fmt_chunk) {
159                                 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_wrapper.inbasefilename);
160                         }
161                         else {
162                                 /* fmt sub-chunk size */
163                                 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
164                                         goto wav_abort_;
165                                 if(xx != 16) {
166                                         fprintf(stderr, "%s: ERROR: unsupported non-standard 'fmt ' sub-chunk has length %u != 16\n", encoder_wrapper.inbasefilename, (unsigned)xx);
167                                         goto wav_abort_;
168                                 }
169                                 /* compression code */
170                                 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
171                                         goto wav_abort_;
172                                 if(x != 1) {
173                                         fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
174                                         goto wav_abort_;
175                                 }
176                                 /* number of channels */
177                                 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
178                                         goto wav_abort_;
179                                 if(x == 0 || x > FLAC__MAX_CHANNELS) {
180                                         fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
181                                         goto wav_abort_;
182                                 }
183                                 channels = x;
184                                 /* sample rate */
185                                 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
186                                         goto wav_abort_;
187                                 if(xx == 0 || xx > FLAC__MAX_SAMPLE_RATE) {
188                                         fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
189                                         goto wav_abort_;
190                                 }
191                                 sample_rate = xx;
192                                 /* avg bytes per second (ignored) */
193                                 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
194                                         goto wav_abort_;
195                                 /* block align (ignored) */
196                                 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
197                                         goto wav_abort_;
198                                 /* bits per sample */
199                                 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
200                                         goto wav_abort_;
201                                 if(x != 8 && x != 16) {
202                                         fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
203                                         goto wav_abort_;
204                                 }
205                                 bps = x;
206                                 is_unsigned_samples = (x == 8);
207
208                                 got_fmt_chunk = true;
209                         }
210                 }
211                 else if(xx == 0x61746164) { /* "data" */
212                         if(got_data_chunk) {
213                                 fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_wrapper.inbasefilename);
214                         }
215                         else if(!got_fmt_chunk) {
216                                 fprintf(stderr, "%s: ERROR: got data sub-chunk before fmt sub-chunk\n", encoder_wrapper.inbasefilename);
217                                 goto wav_abort_;
218                         }
219                         else {
220                                 /* data size */
221                                 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
222                                         goto wav_abort_;
223                                 data_bytes = xx;
224
225                                 bytes_per_wide_sample = channels * (bps >> 3);
226
227                                 if(skip > 0) {
228                                         if(infile != stdin) {
229                                                 if(-1 == fseek(infile, bytes_per_wide_sample * (unsigned)skip, SEEK_CUR)) {
230                                                         fprintf(stderr, "%s: ERROR during seek while skipping samples\n", encoder_wrapper.inbasefilename);
231                                                         goto wav_abort_;
232                                                 }
233                                         }
234                                         else {
235                                                 unsigned left, need;
236                                                 for(left = skip; left > 0; ) {
237                                                         need = min(left, CHUNK_OF_SAMPLES);
238                                                         if(fread(ucbuffer, 1, bytes_per_wide_sample * need, infile) < need) {
239                                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
240                                                                 goto wav_abort_;
241                                                         }
242                                                         left -= need;
243                                                 }
244                                         }
245                                 }
246
247                                 data_bytes -= skip * bytes_per_wide_sample;
248                                 encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample;
249                                 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44; /* 44 for the size of the WAV headers */
250
251                                 if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, do_qlp_coeff_prec_search, min_residual_partition_order, max_residual_partition_order, rice_parameter_search_dist, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, requested_seek_points, num_requested_seek_points, &encoder_wrapper))
252                                         goto wav_abort_;
253
254                                 encoder_wrapper.verify_fifo.into_frames = true;
255
256                                 while(data_bytes > 0) {
257                                         bytes_read = fread(ucbuffer, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
258                                         if(bytes_read == 0) {
259                                                 if(ferror(infile)) {
260                                                         fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
261                                                         goto wav_abort_;
262                                                 }
263                                                 else if(feof(infile)) {
264                                                         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);
265                                                         data_bytes = 0;
266                                                 }
267                                         }
268                                         else {
269                                                 if(bytes_read % bytes_per_wide_sample != 0) {
270                                                         fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
271                                                         goto wav_abort_;
272                                                 }
273                                                 else {
274                                                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
275                                                         format_input(wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
276
277                                                         /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
278                                                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
279                                                                 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)]);
280                                                                 goto wav_abort_;
281                                                         }
282                                                         data_bytes -= bytes_read;
283                                                 }
284                                         }
285                                 }
286                                 got_data_chunk = true;
287                         }
288                 }
289                 else {
290                         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));
291                         /* sub-chunk size */
292                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
293                                 goto wav_abort_;
294                         if(infile != stdin) {
295                                 if(-1 == fseek(infile, xx, SEEK_CUR)) {
296                                         fprintf(stderr, "%s: ERROR during seek while skipping unsupported sub-chunk\n", encoder_wrapper.inbasefilename);
297                                         goto wav_abort_;
298                                 }
299                         }
300                         else {
301                                 unsigned left, need;
302                                 const unsigned chunk = sizeof(ucbuffer);
303                                 for(left = xx; left > 0; ) {
304                                         need = min(left, chunk);
305                                         if(fread(ucbuffer, 1, need, infile) < need) {
306                                                 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_wrapper.inbasefilename);
307                                                 goto wav_abort_;
308                                         }
309                                         left -= need;
310                                 }
311                         }
312                 }
313         }
314
315         if(encoder_wrapper.encoder) {
316                 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
317                         FLAC__stream_encoder_finish(encoder_wrapper.encoder);
318                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
319         }
320         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
321                 print_stats(&encoder_wrapper);
322                 fprintf(stderr, "\n");
323         }
324         if(0 != encoder_wrapper.seek_table.points)
325                 free(encoder_wrapper.seek_table.points);
326         if(verify) {
327                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
328                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
329                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
330                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
331                         return 1;
332                 }
333         }
334         if(infile != stdin)
335                 fclose(infile);
336         return 0;
337 wav_abort_:
338         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
339                 fprintf(stderr, "\n");
340         if(encoder_wrapper.encoder) {
341                 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
342                         FLAC__stream_encoder_finish(encoder_wrapper.encoder);
343                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
344         }
345         if(0 != encoder_wrapper.seek_table.points)
346                 free(encoder_wrapper.seek_table.points);
347         if(verify) {
348                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
349                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
350                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
351                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
352                         return 1;
353                 }
354         }
355         if(infile != stdin)
356                 fclose(infile);
357         unlink(outfilename);
358         return 1;
359 }
360
361 int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, FLAC__bool verbose, FLAC__uint64 skip, FLAC__bool verify, FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned padding, char *requested_seek_points, int num_requested_seek_points, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned sample_rate)
362 {
363         encoder_wrapper_struct encoder_wrapper;
364         size_t bytes_read;
365         const size_t bytes_per_wide_sample = channels * (bps >> 3);
366
367         encoder_wrapper.encoder = 0;
368         encoder_wrapper.verify = verify;
369         encoder_wrapper.verbose = verbose;
370         encoder_wrapper.bytes_written = 0;
371         encoder_wrapper.samples_written = 0;
372         encoder_wrapper.stream_offset = 0;
373         encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
374         encoder_wrapper.outfilename = outfilename;
375         encoder_wrapper.seek_table.points = 0;
376         encoder_wrapper.first_seek_point_to_check = 0;
377
378         if(0 == strcmp(outfilename, "-")) {
379                 encoder_wrapper.fout = stdout;
380         }
381         else {
382                 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
383                         fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
384                         fclose(infile);
385                         return 1;
386                 }
387         }
388
389         if(!init(&encoder_wrapper))
390                 goto raw_abort_;
391
392         /* get the file length */
393         if(infilesize < 0) {
394                 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
395         }
396         else {
397                 encoder_wrapper.unencoded_size = (unsigned)infilesize - skip * bytes_per_wide_sample;
398                 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - skip;
399         }
400
401         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
402                 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
403
404         if(skip > 0) {
405                 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)skip;
406                 if(skip_bytes > lookahead_length) {
407                         skip_bytes -= lookahead_length;
408                         lookahead_length = 0;
409                         if(infile != stdin) {
410                                 if(-1 == fseek(infile, (long)skip_bytes, SEEK_SET)) {
411                                         fprintf(stderr, "%s: ERROR during seek while skipping samples\n", encoder_wrapper.inbasefilename);
412                                         goto raw_abort_;
413                                 }
414                         }
415                         else {
416                                 unsigned left, need;
417                                 const unsigned chunk = sizeof(ucbuffer);
418                                 for(left = skip_bytes; left > 0; ) {
419                                         need = min(left, chunk);
420                                         if(fread(ucbuffer, 1, need, infile) < need) {
421                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
422                                                 goto raw_abort_;
423                                         }
424                                         left -= need;
425                                 }
426                         }
427                 }
428                 else {
429                         lookahead += skip_bytes;
430                         lookahead_length -= skip_bytes;
431                 }
432         }
433         else {
434                 fseek(infile, 0, SEEK_SET);
435         }
436
437         if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, do_qlp_coeff_prec_search, min_residual_partition_order, max_residual_partition_order, rice_parameter_search_dist, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, requested_seek_points, num_requested_seek_points, &encoder_wrapper))
438                 goto raw_abort_;
439
440         encoder_wrapper.verify_fifo.into_frames = true;
441
442         while(!feof(infile)) {
443                 if(lookahead_length > 0) {
444                         FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
445                         memcpy(ucbuffer, lookahead, lookahead_length);
446                         bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
447                         if(ferror(infile)) {
448                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
449                                 goto raw_abort_;
450                         }
451                         lookahead_length = 0;
452                 }
453                 else
454                         bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
455
456                 if(bytes_read == 0) {
457                         if(ferror(infile)) {
458                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
459                                 goto raw_abort_;
460                         }
461                 }
462                 else if(bytes_read % bytes_per_wide_sample != 0) {
463                         fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
464                         goto raw_abort_;
465                 }
466                 else {
467                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
468                         format_input(wide_samples, is_big_endian, is_unsigned_samples, channels, bps, &encoder_wrapper);
469
470                         /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
471                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
472                                 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)]);
473                                 goto raw_abort_;
474                         }
475                 }
476         }
477
478         if(encoder_wrapper.encoder) {
479                 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
480                         FLAC__stream_encoder_finish(encoder_wrapper.encoder);
481                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
482         }
483         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
484                 print_stats(&encoder_wrapper);
485                 fprintf(stderr, "\n");
486         }
487         if(0 != encoder_wrapper.seek_table.points)
488                 free(encoder_wrapper.seek_table.points);
489         if(verify) {
490                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
491                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
492                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
493                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
494                         return 1;
495                 }
496         }
497         if(infile != stdin)
498                 fclose(infile);
499         return 0;
500 raw_abort_:
501         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
502                 fprintf(stderr, "\n");
503         if(encoder_wrapper.encoder) {
504                 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
505                         FLAC__stream_encoder_finish(encoder_wrapper.encoder);
506                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
507         }
508         if(0 != encoder_wrapper.seek_table.points)
509                 free(encoder_wrapper.seek_table.points);
510         if(verify) {
511                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
512                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
513                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
514                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
515                         return 1;
516                 }
517         }
518         if(infile != stdin)
519                 fclose(infile);
520         unlink(outfilename);
521         return 1;
522 }
523
524 FLAC__bool init(encoder_wrapper_struct *encoder_wrapper)
525 {
526         unsigned i;
527         FLAC__uint32 test = 1;
528
529         is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
530
531         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
532                 input[i] = &(in[i][0]);
533
534         encoder_wrapper->encoder = FLAC__stream_encoder_new();
535         if(0 == encoder_wrapper->encoder) {
536                 fprintf(stderr, "%s: ERROR creating the encoder instance\n", encoder_wrapper->inbasefilename);
537                 return false;
538         }
539
540         return true;
541 }
542
543 FLAC__bool init_encoder(FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, unsigned padding, char *requested_seek_points, int num_requested_seek_points, encoder_wrapper_struct *encoder_wrapper)
544 {
545         unsigned i;
546
547         if(channels != 2)
548                 do_mid_side = loose_mid_side = false;
549
550         if(encoder_wrapper->verify) {
551                 /* set up the fifo which will hold the original signal to compare against */
552                 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
553                 for(i = 0; i < channels; i++) {
554                         if(0 == (encoder_wrapper->verify_fifo.original[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder_wrapper->verify_fifo.size))) {
555                                 fprintf(stderr, "%s: ERROR allocating verify buffers\n", encoder_wrapper->inbasefilename);
556                                 return false;
557                         }
558                 }
559                 encoder_wrapper->verify_fifo.tail = 0;
560                 encoder_wrapper->verify_fifo.into_frames = false;
561                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
562
563                 /* set up a stream decoder for verification */
564                 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_new();
565                 if(0 == encoder_wrapper->verify_fifo.decoder) {
566                         fprintf(stderr, "%s: ERROR creating the verify decoder instance\n", encoder_wrapper->inbasefilename);
567                         return false;
568                 }
569                 FLAC__stream_decoder_set_read_callback(encoder_wrapper->verify_fifo.decoder, verify_read_callback);
570                 FLAC__stream_decoder_set_write_callback(encoder_wrapper->verify_fifo.decoder, verify_write_callback);
571                 FLAC__stream_decoder_set_metadata_callback(encoder_wrapper->verify_fifo.decoder, verify_metadata_callback);
572                 FLAC__stream_decoder_set_error_callback(encoder_wrapper->verify_fifo.decoder, verify_error_callback);
573                 FLAC__stream_decoder_set_client_data(encoder_wrapper->verify_fifo.decoder, encoder_wrapper);
574                 if(FLAC__stream_decoder_init(encoder_wrapper->verify_fifo.decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
575                         fprintf(stderr, "%s: ERROR initializing decoder, state = %d:%s\n", encoder_wrapper->inbasefilename, FLAC__stream_decoder_get_state(encoder_wrapper->verify_fifo.decoder), FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(encoder_wrapper->verify_fifo.decoder)]);
576                         return false;
577                 }
578         }
579
580         if(!convert_to_seek_table(requested_seek_points, num_requested_seek_points, encoder_wrapper->total_samples_to_encode, blocksize, &encoder_wrapper->seek_table)) {
581                 fprintf(stderr, "%s: ERROR allocating seek table\n", encoder_wrapper->inbasefilename);
582                 return false;
583         }
584
585         FLAC__stream_encoder_set_streamable_subset(encoder_wrapper->encoder, !lax);
586         FLAC__stream_encoder_set_do_mid_side_stereo(encoder_wrapper->encoder, do_mid_side);
587         FLAC__stream_encoder_set_loose_mid_side_stereo(encoder_wrapper->encoder, loose_mid_side);
588         FLAC__stream_encoder_set_channels(encoder_wrapper->encoder, channels);
589         FLAC__stream_encoder_set_bits_per_sample(encoder_wrapper->encoder, bps);
590         FLAC__stream_encoder_set_sample_rate(encoder_wrapper->encoder, sample_rate);
591         FLAC__stream_encoder_set_blocksize(encoder_wrapper->encoder, blocksize);
592         FLAC__stream_encoder_set_max_lpc_order(encoder_wrapper->encoder, max_lpc_order);
593         FLAC__stream_encoder_set_qlp_coeff_precision(encoder_wrapper->encoder, qlp_coeff_precision);
594         FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder_wrapper->encoder, do_qlp_coeff_prec_search);
595         FLAC__stream_encoder_set_do_exhaustive_model_search(encoder_wrapper->encoder, do_exhaustive_model_search);
596         FLAC__stream_encoder_set_min_residual_partition_order(encoder_wrapper->encoder, min_residual_partition_order);
597         FLAC__stream_encoder_set_max_residual_partition_order(encoder_wrapper->encoder, max_residual_partition_order);
598         FLAC__stream_encoder_set_rice_parameter_search_dist(encoder_wrapper->encoder, rice_parameter_search_dist);
599         FLAC__stream_encoder_set_total_samples_estimate(encoder_wrapper->encoder, encoder_wrapper->total_samples_to_encode);
600         FLAC__stream_encoder_set_seek_table(encoder_wrapper->encoder, (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0);
601         FLAC__stream_encoder_set_padding(encoder_wrapper->encoder, padding);
602         FLAC__stream_encoder_set_last_metadata_is_last(encoder_wrapper->encoder, true);
603         FLAC__stream_encoder_set_write_callback(encoder_wrapper->encoder, write_callback);
604         FLAC__stream_encoder_set_metadata_callback(encoder_wrapper->encoder, metadata_callback);
605         FLAC__stream_encoder_set_client_data(encoder_wrapper->encoder, encoder_wrapper);
606
607         if(FLAC__stream_encoder_init(encoder_wrapper->encoder) != FLAC__STREAM_ENCODER_OK) {
608                 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)]);
609                 return false;
610         }
611
612         /* the above call writes all the metadata, so we save the stream offset now */
613         encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
614
615         return true;
616 }
617
618 FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table)
619 {
620         unsigned i, j, real_points, placeholders;
621         char *pt = requested_seek_points, *q;
622         FLAC__bool first;
623
624         seek_table->num_points = 0;
625
626         if(num_requested_seek_points == 0)
627                 return true;
628
629         if(num_requested_seek_points < 0) {
630                 strcpy(requested_seek_points, "100x<");
631                 num_requested_seek_points = 1;
632         }
633
634         /* first count how many individual seek point we may need */
635         real_points = placeholders = 0;
636         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
637                 q = strchr(pt, '<');
638                 FLAC__ASSERT(0 != q);
639                 *q = '\0';
640
641                 if(0 == strcmp(pt, "X")) { /* -S X */
642                         placeholders++;
643                 }
644                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
645                         if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
646                                 real_points += (unsigned)atoi(pt);
647                 }
648                 else { /* -S # */
649                         real_points++;
650                 }
651                 *q++ = '<';
652
653                 pt = q;
654         }
655         pt = requested_seek_points;
656
657         /* make some space */
658         if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
659                 return false;
660
661         /* initialize the seek_table.  we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
662         for(i = 0; i < real_points+placeholders; i++) {
663                 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
664                 seek_table->points[i].stream_offset = 0;
665                 seek_table->points[i].frame_samples = 0;
666         }
667
668         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
669                 q = strchr(pt, '<');
670                 FLAC__ASSERT(0 != q);
671                 *q++ = '\0';
672
673                 if(0 == strcmp(pt, "X")) { /* -S X */
674                         ; /* we append placeholders later */
675                 }
676                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
677                         if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
678                                 unsigned j, n;
679                                 n = (unsigned)atoi(pt);
680                                 for(j = 0; j < n; j++)
681                                         append_point_to_seek_table(seek_table, stream_samples * (FLAC__uint64)j / (FLAC__uint64)n, stream_samples, blocksize);
682                         }
683                 }
684                 else { /* -S # */
685                         append_point_to_seek_table(seek_table, (FLAC__uint64)atoi(pt), stream_samples, blocksize);
686                 }
687
688                 pt = q;
689         }
690
691         /* sort the seekpoints */
692         qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
693
694         /* uniqify the seekpoints */
695         first = true;
696         for(i = j = 0; i < seek_table->num_points; i++) {
697                 if(!first) {
698                         if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
699                                 continue;
700                 }
701                 first = false;
702                 seek_table->points[j++] = seek_table->points[i];
703         }
704         seek_table->num_points = j;
705
706         /* append placeholders */
707         for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
708                 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
709         seek_table->num_points += placeholders;
710
711         return true;
712 }
713
714 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, FLAC__uint64 sample, FLAC__uint64 stream_samples, FLAC__uint64 blocksize)
715 {
716         const FLAC__uint64 target_sample = (sample / blocksize) * blocksize;
717
718         if(stream_samples == 0 || target_sample < stream_samples)
719                 seek_table->points[seek_table->num_points++].sample_number = target_sample;
720 }
721
722 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
723 {
724         /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
725         if(l->sample_number == r->sample_number)
726                 return 0;
727         else if(l->sample_number < r->sample_number)
728                 return -1;
729         else
730                 return 1;
731 }
732
733 void format_input(unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
734 {
735         unsigned wide_sample, sample, channel, byte;
736
737         if(bps == 8) {
738                 if(is_unsigned_samples) {
739                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
740                                 for(channel = 0; channel < channels; channel++, sample++)
741                                         input[channel][wide_sample] = (FLAC__int32)ucbuffer[sample] - 0x80;
742                 }
743                 else {
744                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
745                                 for(channel = 0; channel < channels; channel++, sample++)
746                                         input[channel][wide_sample] = (FLAC__int32)scbuffer[sample];
747                 }
748         }
749         else if(bps == 16) {
750                 if(is_big_endian != is_big_endian_host) {
751                         unsigned char tmp;
752                         const unsigned bytes = wide_samples * channels * (bps >> 3);
753                         for(byte = 0; byte < bytes; byte += 2) {
754                                 tmp = ucbuffer[byte];
755                                 ucbuffer[byte] = ucbuffer[byte+1];
756                                 ucbuffer[byte+1] = tmp;
757                         }
758                 }
759                 if(is_unsigned_samples) {
760                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
761                                 for(channel = 0; channel < channels; channel++, sample++)
762                                         input[channel][wide_sample] = (FLAC__int32)usbuffer[sample] - 0x8000;
763                 }
764                 else {
765                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
766                                 for(channel = 0; channel < channels; channel++, sample++)
767                                         input[channel][wide_sample] = (FLAC__int32)ssbuffer[sample];
768                 }
769         }
770         else if(bps == 24) {
771                 if(!is_big_endian) {
772                         unsigned char tmp;
773                         const unsigned bytes = wide_samples * channels * (bps >> 3);
774                         for(byte = 0; byte < bytes; byte += 3) {
775                                 tmp = ucbuffer[byte];
776                                 ucbuffer[byte] = ucbuffer[byte+2];
777                                 ucbuffer[byte+2] = tmp;
778                         }
779                 }
780                 if(is_unsigned_samples) {
781                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
782                                 for(channel = 0; channel < channels; channel++, sample++) {
783                                         input[channel][wide_sample]  = ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
784                                         input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
785                                         input[channel][wide_sample] |= ucbuffer[byte++];
786                                         input[channel][wide_sample] -= 0x800000;
787                                 }
788                 }
789                 else {
790                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
791                                 for(channel = 0; channel < channels; channel++, sample++) {
792                                         input[channel][wide_sample]  = scbuffer[byte++]; input[channel][wide_sample] <<= 8;
793                                         input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
794                                         input[channel][wide_sample] |= ucbuffer[byte++];
795                                 }
796                 }
797         }
798         else {
799                 FLAC__ASSERT(0);
800         }
801
802         if(encoder_wrapper->verify) {
803                 for(channel = 0; channel < channels; channel++)
804                         memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], &input[channel][0], sizeof(FLAC__int32) * wide_samples);
805                 encoder_wrapper->verify_fifo.tail += wide_samples;
806                 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
807         }
808 }
809
810 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
811 {
812         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
813         const unsigned mask = (FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
814
815         /* 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) */
816         if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
817                 FLAC__uint64 current_sample = (FLAC__uint64)current_frame * (FLAC__uint64)FLAC__stream_encoder_get_blocksize(encoder), test_sample;
818                 unsigned i;
819                 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
820                         test_sample = encoder_wrapper->seek_table.points[i].sample_number;
821                         if(test_sample > current_sample) {
822                                 break;
823                         }
824                         else if(test_sample == current_sample) {
825                                 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
826                                 encoder_wrapper->seek_table.points[i].frame_samples = FLAC__stream_encoder_get_blocksize(encoder);
827                                 encoder_wrapper->first_seek_point_to_check++;
828                                 break;
829                         }
830                         else {
831                                 encoder_wrapper->first_seek_point_to_check++;
832                         }
833                 }
834         }
835
836         encoder_wrapper->bytes_written += bytes;
837         encoder_wrapper->samples_written += samples;
838         encoder_wrapper->current_frame = current_frame;
839
840         if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
841                 print_stats(encoder_wrapper);
842
843         if(encoder_wrapper->verify) {
844                 encoder_wrapper->verify_fifo.encoded_signal = buffer;
845                 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
846                 if(encoder_wrapper->verify_fifo.into_frames) {
847                         if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
848                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
849                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
850                         }
851                 }
852                 else {
853                         if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
854                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
855                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
856                         }
857                 }
858         }
859
860         if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_wrapper->fout) == bytes)
861                 return FLAC__STREAM_ENCODER_WRITE_OK;
862         else
863                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
864 }
865
866 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
867 {
868         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
869         FLAC__byte b;
870         FILE *f;
871         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
872         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
873         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
874
875         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
876
877         /*
878          * we get called by the encoder when the encoding process has
879          * finished so that we can update the STREAMINFO and SEEKTABLE
880          * blocks.
881          */
882
883         (void)encoder; /* silence compiler warning about unused parameter */
884
885         if(encoder_wrapper->fout == stdout)
886                 return;
887
888         fclose(encoder_wrapper->fout);
889         if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
890                 return;
891
892         /* all this is based on intimate knowledge of the stream header
893          * layout, but a change to the header format that would break this
894          * would also break all streams encoded in the previous format.
895          */
896
897         if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
898         fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
899
900 samples_:
901         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
902         if(fread(&b, 1, 1, f) != 1) goto framesize_;
903         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
904         b = (b & 0xf0) | (FLAC__byte)((samples >> 32) & 0x0F);
905         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
906         b = (FLAC__byte)((samples >> 24) & 0xFF);
907         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
908         b = (FLAC__byte)((samples >> 16) & 0xFF);
909         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
910         b = (FLAC__byte)((samples >> 8) & 0xFF);
911         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
912         b = (FLAC__byte)(samples & 0xFF);
913         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
914
915 framesize_:
916         if(-1 == fseek(f, 12, SEEK_SET)) goto seektable_;
917         b = (FLAC__byte)((min_framesize >> 16) & 0xFF);
918         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
919         b = (FLAC__byte)((min_framesize >> 8) & 0xFF);
920         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
921         b = (FLAC__byte)(min_framesize & 0xFF);
922         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
923         b = (FLAC__byte)((max_framesize >> 16) & 0xFF);
924         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
925         b = (FLAC__byte)((max_framesize >> 8) & 0xFF);
926         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
927         b = (FLAC__byte)(max_framesize & 0xFF);
928         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
929
930 seektable_:
931         if(encoder_wrapper->seek_table.num_points > 0) {
932                 long pos;
933                 unsigned i;
934
935                 /* convert any unused seek points to placeholders */
936                 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
937                         if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
938                                 break;
939                         else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
940                                 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
941                 }
942
943                 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
944                 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
945                 pos += metadata->length;
946                 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
947                 if(-1 == fseek(f, pos, SEEK_SET)) goto end_;
948                 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
949                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
950                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
951                         if(!write_big_endian_uint16(f, encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
952                 }
953         }
954
955 end_:
956         fclose(f);
957         return;
958 }
959
960 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
961 {
962         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
963         const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
964         (void)decoder;
965
966         if(encoded_bytes <= *bytes) {
967                 *bytes = encoded_bytes;
968                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
969         }
970         else {
971                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
972                 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
973                 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
974         }
975
976         return FLAC__STREAM_DECODER_READ_CONTINUE;
977 }
978
979 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
980 {
981         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
982         unsigned channel, l, r;
983         const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
984         const unsigned bytes_per_block = sizeof(FLAC__int32) * FLAC__stream_decoder_get_blocksize(decoder);
985
986         for(channel = 0; channel < channels; channel++) {
987                 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], bytes_per_block)) {
988                         fprintf(stderr, "\n%s: ERROR: mismatch in decoded data, verify FAILED!\n", encoder_wrapper->inbasefilename);
989                         fprintf(stderr, "       Please submit a bug report to\n");
990                         fprintf(stderr, "           http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
991                         fprintf(stderr, "       Make sure to include an email contact in the comment and/or use the\n");
992                         fprintf(stderr, "       \"Monitor\" feature to monitor the bug status.\n");
993                         return FLAC__STREAM_DECODER_WRITE_ABORT;
994                 }
995         }
996         /* dequeue the frame from the fifo */
997         for(channel = 0; channel < channels; channel++) {
998                 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
999                         encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
1000                 }
1001         }
1002         encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
1003         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
1004 }
1005
1006 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
1007 {
1008         (void)decoder;
1009         (void)metadata;
1010         (void)client_data;
1011 }
1012
1013 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1014 {
1015         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1016         (void)decoder;
1017         fprintf(stderr, "\n%s: ERROR: verification decoder returned error %d:%s\n", encoder_wrapper->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1018 }
1019
1020 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1021 {
1022 #ifdef _MSC_VER
1023         /* with VC++ you have to spoon feed it the casting */
1024         const double progress = (double)(FLAC__int64)encoder_wrapper->samples_written / (double)(FLAC__int64)encoder_wrapper->total_samples_to_encode;
1025         const double ratio = (double)(FLAC__int64)encoder_wrapper->bytes_written / ((double)(FLAC__int64)encoder_wrapper->unencoded_size * progress);
1026 #else
1027         const double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1028         const double ratio = (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress);
1029 #endif
1030
1031         if(encoder_wrapper->samples_written == encoder_wrapper->total_samples_to_encode) {
1032                 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1033                         encoder_wrapper->inbasefilename,
1034                         encoder_wrapper->verify? (encoder_wrapper->verify_fifo.result == FLAC__VERIFY_OK? " Verify OK," : " Verify FAILED!") : "",
1035                         (unsigned)encoder_wrapper->bytes_written,
1036                         ratio
1037                 );
1038         }
1039         else {
1040                 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_wrapper->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1041         }
1042 }
1043
1044 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1045 {
1046         size_t bytes_read = fread(val, 1, 2, f);
1047
1048         if(bytes_read == 0) {
1049                 if(!eof_ok) {
1050                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1051                         return false;
1052                 }
1053                 else
1054                         return true;
1055         }
1056         else if(bytes_read < 2) {
1057                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1058                 return false;
1059         }
1060         else {
1061                 if(is_big_endian_host) {
1062                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1063                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1064                 }
1065                 return true;
1066         }
1067 }
1068
1069 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1070 {
1071         size_t bytes_read = fread(val, 1, 4, f);
1072
1073         if(bytes_read == 0) {
1074                 if(!eof_ok) {
1075                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1076                         return false;
1077                 }
1078                 else
1079                         return true;
1080         }
1081         else if(bytes_read < 4) {
1082                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1083                 return false;
1084         }
1085         else {
1086                 if(is_big_endian_host) {
1087                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1088                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1089                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1090                 }
1091                 return true;
1092         }
1093 }
1094
1095 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
1096 {
1097         if(!is_big_endian_host) {
1098                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1099                 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1100         }
1101         return fwrite(&val, 1, 2, f) == 2;
1102 }
1103
1104 FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val)
1105 {
1106         if(!is_big_endian_host) {
1107                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1108                 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1109                 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1110                 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1111                 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1112         }
1113         return fwrite(&val, 1, 8, f) == 8;
1114 }