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