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