unify the error reporting; make the statistics output more terse
[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         int32 *original[FLAC__MAX_CHANNELS];
54         unsigned size; /* of each original[] in samples */
55         unsigned tail; /* in wide samples */
56         const byte *encoded_signal;
57         unsigned encoded_signal_capacity;
58         unsigned encoded_bytes;
59         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         bool verify;
70         bool verbose;
71         uint64 unencoded_size;
72         uint64 total_samples_to_encode;
73         uint64 bytes_written;
74         uint64 samples_written;
75         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 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 uint16 *usbuffer = (uint16 *)ucbuffer;
87 static int16 *ssbuffer = (int16 *)ucbuffer;
88
89 static int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
90 static int32 *input[FLAC__MAX_CHANNELS];
91
92 /* local routines */
93 static bool init(encoder_wrapper_struct *encoder_wrapper);
94 static bool init_encoder(bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, 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 bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table);
96 static void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, 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, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
99 static FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const 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, byte buffer[], unsigned *bytes, void *client_data);
102 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const 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 bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok, const char *fn);
107 static bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok, const char *fn);
108 static bool write_big_endian_uint16(FILE *f, uint16 val);
109 static bool write_big_endian_uint64(FILE *f, uint64 val);
110
111 int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const byte *lookahead, unsigned lookahead_length, bool verbose, uint64 skip, bool verify, bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, 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         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         uint16 x;
118         uint32 xx;
119         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_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_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_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_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 byte *lookahead, unsigned lookahead_length, bool verbose, uint64 skip, bool verify, bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, 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, bool is_big_endian, 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_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_state(encoder_wrapper.encoder)]);
473                                 goto raw_abort_;
474                         }
475                 }
476         }
477
478         if(encoder_wrapper.encoder) {
479                 if(FLAC__stream_encoder_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_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 bool init(encoder_wrapper_struct *encoder_wrapper)
525 {
526         unsigned i;
527         uint32 test = 1;
528
529         is_big_endian_host = (*((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 bool init_encoder(bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, 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] = (int32*)malloc(sizeof(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                 if(FLAC__stream_decoder_init(encoder_wrapper->verify_fifo.decoder, verify_read_callback, verify_write_callback, verify_metadata_callback, verify_error_callback, encoder_wrapper) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
570                         fprintf(stderr, "%s: ERROR initializing decoder, state = %d:%s\n", encoder_wrapper->inbasefilename, FLAC__stream_decoder_state(encoder_wrapper->verify_fifo.decoder), FLAC__StreamDecoderStateString[FLAC__stream_decoder_state(encoder_wrapper->verify_fifo.decoder)]);
571                         return false;
572                 }
573         }
574
575         if(!convert_to_seek_table(requested_seek_points, num_requested_seek_points, encoder_wrapper->total_samples_to_encode, blocksize, &encoder_wrapper->seek_table)) {
576                 fprintf(stderr, "%s: ERROR allocating seek table\n", encoder_wrapper->inbasefilename);
577                 return false;
578         }
579
580         if(FLAC__stream_encoder_init(encoder_wrapper->encoder, !lax, do_mid_side, loose_mid_side, channels, bps, sample_rate, blocksize, max_lpc_order, qlp_coeff_precision, do_qlp_coeff_prec_search, do_exhaustive_model_search, min_residual_partition_order, max_residual_partition_order, rice_parameter_search_dist, encoder_wrapper->total_samples_to_encode, (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0, padding, true /*last_metadata_is_last*/, write_callback, metadata_callback, encoder_wrapper) != FLAC__STREAM_ENCODER_OK) {
581                 fprintf(stderr, "%s: ERROR initializing encoder, state = %d:%s\n", encoder_wrapper->inbasefilename, FLAC__stream_encoder_state(encoder_wrapper->encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_state(encoder_wrapper->encoder)]);
582                 return false;
583         }
584
585         /* the above call writes all the metadata, so we save the stream offset now */
586         encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
587
588         return true;
589 }
590
591 bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table)
592 {
593         unsigned i, j, real_points, placeholders;
594         char *pt = requested_seek_points, *q;
595         bool first;
596
597         seek_table->num_points = 0;
598
599         if(num_requested_seek_points == 0)
600                 return true;
601
602         if(num_requested_seek_points < 0) {
603                 strcpy(requested_seek_points, "100x<");
604                 num_requested_seek_points = 1;
605         }
606
607         /* first count how many individual seek point we may need */
608         real_points = placeholders = 0;
609         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
610                 q = strchr(pt, '<');
611                 FLAC__ASSERT(0 != q);
612                 *q = '\0';
613
614                 if(0 == strcmp(pt, "X")) { /* -S X */
615                         placeholders++;
616                 }
617                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
618                         if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
619                                 real_points += (unsigned)atoi(pt);
620                 }
621                 else { /* -S # */
622                         real_points++;
623                 }
624                 *q++ = '<';
625
626                 pt = q;
627         }
628         pt = requested_seek_points;
629
630         /* make some space */
631         if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
632                 return false;
633
634         /* initialize the seek_table.  we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
635         for(i = 0; i < real_points+placeholders; i++) {
636                 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
637                 seek_table->points[i].stream_offset = 0;
638                 seek_table->points[i].frame_samples = 0;
639         }
640
641         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
642                 q = strchr(pt, '<');
643                 FLAC__ASSERT(0 != q);
644                 *q++ = '\0';
645
646                 if(0 == strcmp(pt, "X")) { /* -S X */
647                         ; /* we append placeholders later */
648                 }
649                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
650                         if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
651                                 unsigned j, n;
652                                 n = (unsigned)atoi(pt);
653                                 for(j = 0; j < n; j++)
654                                         append_point_to_seek_table(seek_table, stream_samples * (uint64)j / (uint64)n, stream_samples, blocksize);
655                         }
656                 }
657                 else { /* -S # */
658                         append_point_to_seek_table(seek_table, (uint64)atoi(pt), stream_samples, blocksize);
659                 }
660
661                 pt = q;
662         }
663
664         /* sort the seekpoints */
665         qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
666
667         /* uniqify the seekpoints */
668         first = true;
669         for(i = j = 0; i < seek_table->num_points; i++) {
670                 if(!first) {
671                         if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
672                                 continue;
673                 }
674                 first = false;
675                 seek_table->points[j++] = seek_table->points[i];
676         }
677         seek_table->num_points = j;
678
679         /* append placeholders */
680         for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
681                 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
682         seek_table->num_points += placeholders;
683
684         return true;
685 }
686
687 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize)
688 {
689         const uint64 target_sample = (sample / blocksize) * blocksize;
690
691         if(stream_samples == 0 || target_sample < stream_samples)
692                 seek_table->points[seek_table->num_points++].sample_number = target_sample;
693 }
694
695 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
696 {
697         /* we don't just 'return l->sample_number - r->sample_number' since the result (int64) might overflow an 'int' */
698         if(l->sample_number == r->sample_number)
699                 return 0;
700         else if(l->sample_number < r->sample_number)
701                 return -1;
702         else
703                 return 1;
704 }
705
706 void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
707 {
708         unsigned wide_sample, sample, channel, byte;
709
710         if(bps == 8) {
711                 if(is_unsigned_samples) {
712                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
713                                 for(channel = 0; channel < channels; channel++, sample++)
714                                         input[channel][wide_sample] = (int32)ucbuffer[sample] - 0x80;
715                 }
716                 else {
717                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
718                                 for(channel = 0; channel < channels; channel++, sample++)
719                                         input[channel][wide_sample] = (int32)scbuffer[sample];
720                 }
721         }
722         else if(bps == 16) {
723                 if(is_big_endian != is_big_endian_host) {
724                         unsigned char tmp;
725                         const unsigned bytes = wide_samples * channels * (bps >> 3);
726                         for(byte = 0; byte < bytes; byte += 2) {
727                                 tmp = ucbuffer[byte];
728                                 ucbuffer[byte] = ucbuffer[byte+1];
729                                 ucbuffer[byte+1] = tmp;
730                         }
731                 }
732                 if(is_unsigned_samples) {
733                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
734                                 for(channel = 0; channel < channels; channel++, sample++)
735                                         input[channel][wide_sample] = (int32)usbuffer[sample] - 0x8000;
736                 }
737                 else {
738                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
739                                 for(channel = 0; channel < channels; channel++, sample++)
740                                         input[channel][wide_sample] = (int32)ssbuffer[sample];
741                 }
742         }
743         else if(bps == 24) {
744                 if(!is_big_endian) {
745                         unsigned char tmp;
746                         const unsigned bytes = wide_samples * channels * (bps >> 3);
747                         for(byte = 0; byte < bytes; byte += 3) {
748                                 tmp = ucbuffer[byte];
749                                 ucbuffer[byte] = ucbuffer[byte+2];
750                                 ucbuffer[byte+2] = tmp;
751                         }
752                 }
753                 if(is_unsigned_samples) {
754                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
755                                 for(channel = 0; channel < channels; channel++, sample++) {
756                                         input[channel][wide_sample]  = ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
757                                         input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
758                                         input[channel][wide_sample] |= ucbuffer[byte++];
759                                         input[channel][wide_sample] -= 0x800000;
760                                 }
761                 }
762                 else {
763                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
764                                 for(channel = 0; channel < channels; channel++, sample++) {
765                                         input[channel][wide_sample]  = scbuffer[byte++]; input[channel][wide_sample] <<= 8;
766                                         input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
767                                         input[channel][wide_sample] |= ucbuffer[byte++];
768                                 }
769                 }
770         }
771         else {
772                 FLAC__ASSERT(0);
773         }
774
775         if(encoder_wrapper->verify) {
776                 for(channel = 0; channel < channels; channel++)
777                         memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], &input[channel][0], sizeof(int32) * wide_samples);
778                 encoder_wrapper->verify_fifo.tail += wide_samples;
779                 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
780         }
781 }
782
783 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
784 {
785         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
786         const unsigned mask = (FLAC__stream_encoder_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
787
788         /* 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) */
789         if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
790                 uint64 current_sample = (uint64)current_frame * (uint64)FLAC__stream_encoder_blocksize(encoder), test_sample;
791                 unsigned i;
792                 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
793                         test_sample = encoder_wrapper->seek_table.points[i].sample_number;
794                         if(test_sample > current_sample) {
795                                 break;
796                         }
797                         else if(test_sample == current_sample) {
798                                 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
799                                 encoder_wrapper->seek_table.points[i].frame_samples = FLAC__stream_encoder_blocksize(encoder);
800                                 encoder_wrapper->first_seek_point_to_check++;
801                                 break;
802                         }
803                         else {
804                                 encoder_wrapper->first_seek_point_to_check++;
805                         }
806                 }
807         }
808
809         encoder_wrapper->bytes_written += bytes;
810         encoder_wrapper->samples_written += samples;
811         encoder_wrapper->current_frame = current_frame;
812
813         if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
814                 print_stats(encoder_wrapper);
815
816         if(encoder_wrapper->verify) {
817                 encoder_wrapper->verify_fifo.encoded_signal = buffer;
818                 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
819                 if(encoder_wrapper->verify_fifo.into_frames) {
820                         if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
821                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
822                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
823                         }
824                 }
825                 else {
826                         if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
827                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
828                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
829                         }
830                 }
831         }
832
833         if(fwrite(buffer, sizeof(byte), bytes, encoder_wrapper->fout) == bytes)
834                 return FLAC__STREAM_ENCODER_WRITE_OK;
835         else
836                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
837 }
838
839 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
840 {
841         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
842         byte b;
843         FILE *f;
844         const uint64 samples = metadata->data.stream_info.total_samples;
845         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
846         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
847
848         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
849
850         /*
851          * we get called by the encoder when the encoding process has
852          * finished so that we can update the STREAMINFO and SEEKTABLE
853          * blocks.
854          */
855
856         (void)encoder; /* silence compiler warning about unused parameter */
857
858         if(encoder_wrapper->fout == stdout)
859                 return;
860
861         fclose(encoder_wrapper->fout);
862         if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
863                 return;
864
865         /* all this is based on intimate knowledge of the stream header
866          * layout, but a change to the header format that would break this
867          * would also break all streams encoded in the previous format.
868          */
869
870         if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
871         fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
872
873 samples_:
874         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
875         if(fread(&b, 1, 1, f) != 1) goto framesize_;
876         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
877         b = (b & 0xf0) | (byte)((samples >> 32) & 0x0F);
878         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
879         b = (byte)((samples >> 24) & 0xFF);
880         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
881         b = (byte)((samples >> 16) & 0xFF);
882         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
883         b = (byte)((samples >> 8) & 0xFF);
884         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
885         b = (byte)(samples & 0xFF);
886         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
887
888 framesize_:
889         if(-1 == fseek(f, 12, SEEK_SET)) goto seektable_;
890         b = (byte)((min_framesize >> 16) & 0xFF);
891         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
892         b = (byte)((min_framesize >> 8) & 0xFF);
893         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
894         b = (byte)(min_framesize & 0xFF);
895         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
896         b = (byte)((max_framesize >> 16) & 0xFF);
897         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
898         b = (byte)((max_framesize >> 8) & 0xFF);
899         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
900         b = (byte)(max_framesize & 0xFF);
901         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
902
903 seektable_:
904         if(encoder_wrapper->seek_table.num_points > 0) {
905                 long pos;
906                 unsigned i;
907
908                 /* convert any unused seek points to placeholders */
909                 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
910                         if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
911                                 break;
912                         else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
913                                 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
914                 }
915
916                 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
917                 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
918                 pos += metadata->length;
919                 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
920                 if(-1 == fseek(f, pos, SEEK_SET)) goto end_;
921                 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
922                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
923                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
924                         if(!write_big_endian_uint16(f, encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
925                 }
926         }
927
928 end_:
929         fclose(f);
930         return;
931 }
932
933 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
934 {
935         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
936         const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
937         (void)decoder;
938
939         if(encoded_bytes <= *bytes) {
940                 *bytes = encoded_bytes;
941                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
942         }
943         else {
944                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
945                 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
946                 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
947         }
948
949         return FLAC__STREAM_DECODER_READ_CONTINUE;
950 }
951
952 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
953 {
954         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
955         unsigned channel, l, r;
956         const unsigned channels = FLAC__stream_decoder_channels(decoder);
957         const unsigned bytes_per_block = sizeof(int32) * FLAC__stream_decoder_blocksize(decoder);
958
959         for(channel = 0; channel < channels; channel++) {
960                 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], bytes_per_block)) {
961                         fprintf(stderr, "\n%s: ERROR: mismatch in decoded data, verify FAILED!\n", encoder_wrapper->inbasefilename);
962                         fprintf(stderr, "       Please submit a bug report to\n");
963                         fprintf(stderr, "           http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
964                         fprintf(stderr, "       Make sure to include an email contact in the comment and/or use the\n");
965                         fprintf(stderr, "       \"Monitor\" feature to monitor the bug status.\n");
966                         return FLAC__STREAM_DECODER_WRITE_ABORT;
967                 }
968         }
969         /* dequeue the frame from the fifo */
970         for(channel = 0; channel < channels; channel++) {
971                 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
972                         encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
973                 }
974         }
975         encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
976         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
977 }
978
979 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
980 {
981         (void)decoder;
982         (void)metadata;
983         (void)client_data;
984 }
985
986 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
987 {
988         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
989         (void)decoder;
990         fprintf(stderr, "\n%s: ERROR: verification decoder returned error %d:%s\n", encoder_wrapper->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
991 }
992
993 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
994 {
995 #ifdef _MSC_VER
996         /* with VC++ you have to spoon feed it the casting */
997         const double progress = (double)(int64)encoder_wrapper->samples_written / (double)(int64)encoder_wrapper->total_samples_to_encode;
998         const double ratio = (double)(int64)encoder_wrapper->bytes_written / ((double)(int64)encoder_wrapper->unencoded_size * progress);
999 #else
1000         const double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1001         const double ratio = (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress);
1002 #endif
1003
1004         if(encoder_wrapper->samples_written == encoder_wrapper->total_samples_to_encode) {
1005                 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1006                         encoder_wrapper->inbasefilename,
1007                         encoder_wrapper->verify? (encoder_wrapper->verify_fifo.result == FLAC__VERIFY_OK? " Verify OK," : " Verify FAILED!") : "",
1008                         (unsigned)encoder_wrapper->bytes_written,
1009                         ratio
1010                 );
1011         }
1012         else {
1013                 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_wrapper->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1014         }
1015 }
1016
1017 bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok, const char *fn)
1018 {
1019         size_t bytes_read = fread(val, 1, 2, f);
1020
1021         if(bytes_read == 0) {
1022                 if(!eof_ok) {
1023                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1024                         return false;
1025                 }
1026                 else
1027                         return true;
1028         }
1029         else if(bytes_read < 2) {
1030                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1031                 return false;
1032         }
1033         else {
1034                 if(is_big_endian_host) {
1035                         byte tmp, *b = (byte*)val;
1036                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1037                 }
1038                 return true;
1039         }
1040 }
1041
1042 bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok, const char *fn)
1043 {
1044         size_t bytes_read = fread(val, 1, 4, f);
1045
1046         if(bytes_read == 0) {
1047                 if(!eof_ok) {
1048                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1049                         return false;
1050                 }
1051                 else
1052                         return true;
1053         }
1054         else if(bytes_read < 4) {
1055                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1056                 return false;
1057         }
1058         else {
1059                 if(is_big_endian_host) {
1060                         byte tmp, *b = (byte*)val;
1061                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1062                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1063                 }
1064                 return true;
1065         }
1066 }
1067
1068 bool write_big_endian_uint16(FILE *f, uint16 val)
1069 {
1070         if(!is_big_endian_host) {
1071                 byte *b = (byte *)&val, tmp;
1072                 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1073         }
1074         return fwrite(&val, 1, 2, f) == 2;
1075 }
1076
1077 bool write_big_endian_uint64(FILE *f, uint64 val)
1078 {
1079         if(!is_big_endian_host) {
1080                 byte *b = (byte *)&val, tmp;
1081                 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1082                 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1083                 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1084                 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1085         }
1086         return fwrite(&val, 1, 8, f) == 8;
1087 }