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