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