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