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