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