add MD5 support
[flac.git] / src / flac / encode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000  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 #define CHUNK_OF_SAMPLES 2048
35
36 typedef enum {
37         FLAC__VERIFY_OK,
38         FLAC__VERIFY_FAILED_IN_FRAME,
39         FLAC__VERIFY_FAILED_IN_METADATA
40 } verify_code;
41
42 typedef struct {
43         int32 *original[FLAC__MAX_CHANNELS];
44         unsigned size; /* of each original[] in samples */
45         unsigned tail; /* in wide samples */
46         const byte *encoded_signal;
47         unsigned encoded_bytes;
48         bool into_frames;
49         verify_code result;
50         FLAC__StreamDecoder *decoder;
51 } verify_fifo_struct;
52
53 typedef struct {
54         FILE *fout;
55         const char *outfile;
56         FLAC__Encoder *encoder;
57         bool verify;
58         bool verbose;
59         uint64 unencoded_size;
60         uint64 total_samples_to_encode;
61         uint64 bytes_written;
62         uint64 samples_written;
63         unsigned current_frame;
64         verify_fifo_struct verify_fifo;
65 } encoder_wrapper_struct;
66
67 static bool is_big_endian_host;
68
69 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*(FLAC__MAX_BITS_PER_SAMPLE>>3)];
70 static signed char *scbuffer = (signed char *)ucbuffer;
71 static uint16 *usbuffer = (uint16 *)ucbuffer;
72 static int16 *ssbuffer = (int16 *)ucbuffer;
73
74 static int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
75 static int32 *input[FLAC__MAX_CHANNELS];
76
77 /* local routines */
78 static bool init(encoder_wrapper_struct *encoder_wrapper);
79 static bool init_encoder(bool lax, bool do_mid_side, bool do_exhaustive_model_search, bool do_qlp_coeff_prec_search, unsigned rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper);
80 static void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
81 static FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
82 static void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
83 static FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data);
84 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__FrameHeader *header, const int32 *buffer[], void *client_data);
85 static void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
86 static void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
87 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
88 static bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok);
89 static bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok);
90
91 int encode_wav(const char *infile, const char *outfile, bool verbose, uint64 skip, bool verify, bool lax, bool do_mid_side, bool do_exhaustive_model_search, bool do_qlp_coeff_prec_search, unsigned rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision)
92 {
93         encoder_wrapper_struct encoder_wrapper;
94         FILE *fin;
95         bool is_unsigned_samples;
96         unsigned channels, bps, sample_rate, data_bytes;
97         size_t bytes_per_wide_sample, bytes_read;
98         uint16 x;
99         uint32 xx;
100
101         encoder_wrapper.encoder = 0;
102         encoder_wrapper.verify = verify;
103         encoder_wrapper.verbose = verbose;
104         encoder_wrapper.bytes_written = 0;
105         encoder_wrapper.samples_written = 0;
106         encoder_wrapper.outfile = outfile;
107
108         if(0 == strcmp(infile, "-")) {
109                 fin = stdin;
110         }
111         else {
112                 if(0 == (fin = fopen(infile, "rb"))) {
113                         fprintf(stderr, "ERROR: can't open input file %s\n", infile);
114                         return false;
115                 }
116         }
117         if(0 == strcmp(outfile, "-")) {
118                 encoder_wrapper.fout = stdout;
119         }
120         else {
121                 if(0 == (encoder_wrapper.fout = fopen(outfile, "wb"))) {
122                         fprintf(stderr, "ERROR: can't open output file %s\n", outfile);
123                         fclose(fin);
124                         return false;
125                 }
126         }
127
128         if(!init(&encoder_wrapper))
129                 goto wav_abort_;
130
131         /*
132          * check the RIFF chunk
133          */
134         if(!read_little_endian_uint32(fin, &xx, false))
135                 goto wav_abort_;
136         if(xx != 0x46464952) { /* "RIFF" */
137                 fprintf(stderr, "ERROR: no RIFF header\n");
138                 goto wav_abort_;
139         }
140         if(!read_little_endian_uint32(fin, &xx, false))
141                 goto wav_abort_;
142
143         /*
144          * now process the WAVE chunk
145          */
146         if(!read_little_endian_uint32(fin, &xx, true))
147                 goto wav_end_;
148         if(xx != 0x45564157) { /* "WAVE" */
149                 fprintf(stderr, "ERROR: no WAVE header\n");
150                 goto wav_abort_;
151         }
152
153         /* do the format sub-chunk */
154         if(!read_little_endian_uint32(fin, &xx, false))
155                 goto wav_abort_;
156         if(xx != 0x20746d66) { /* "fmt " */
157                 fprintf(stderr, "ERROR: no format sub-chunk\n");
158                 goto wav_abort_;
159         }
160         /* fmt chunk size */
161         if(!read_little_endian_uint32(fin, &xx, false))
162                 goto wav_abort_;
163         if(xx != 16) {
164                 fprintf(stderr, "ERROR: unsupported chunk\n");
165                 goto wav_abort_;
166         }
167         /* compression code */
168         if(!read_little_endian_uint16(fin, &x, false))
169                 goto wav_abort_;
170         if(x != 1) {
171                 fprintf(stderr, "ERROR: unsupported compression type %u\n", (unsigned)x);
172                 goto wav_abort_;
173         }
174         /* number of channels */
175         if(!read_little_endian_uint16(fin, &x, false))
176                 goto wav_abort_;
177         if(x == 0 || x > FLAC__MAX_CHANNELS) {
178                 fprintf(stderr, "ERROR: unsupported number channels %u\n", (unsigned)x);
179                 goto wav_abort_;
180         }
181         channels = x;
182         /* sample rate */
183         if(!read_little_endian_uint32(fin, &xx, false))
184                 goto wav_abort_;
185         if(xx == 0 || xx > FLAC__MAX_SAMPLE_RATE) {
186                 fprintf(stderr, "ERROR: unsupported sample rate %u\n", (unsigned)xx);
187                 goto wav_abort_;
188         }
189         sample_rate = xx;
190         /* avg bytes per second (ignored) */
191         if(!read_little_endian_uint32(fin, &xx, false))
192                 goto wav_abort_;
193         /* block align (ignored) */
194         if(!read_little_endian_uint16(fin, &x, false))
195                 goto wav_abort_;
196         /* bits per sample */
197         if(!read_little_endian_uint16(fin, &x, false))
198                 goto wav_abort_;
199         if(x != 8 && x != 16) {
200                 fprintf(stderr, "ERROR: unsupported bits per sample %u\n", (unsigned)x);
201                 goto wav_abort_;
202         }
203         bps = x;
204         is_unsigned_samples = (x == 8);
205
206         /* do the data sub-chunk */
207         if(!read_little_endian_uint32(fin, &xx, false))
208                 goto wav_abort_;
209         if(xx != 0x61746164) { /* "data" */
210                 fprintf(stderr, "ERROR: no data sub-chunk\n");
211                 goto wav_abort_;
212         }
213         /* data size */
214         if(!read_little_endian_uint32(fin, &xx, false))
215                 goto wav_abort_;
216         data_bytes = xx;
217
218         if(!init_encoder(lax, do_mid_side, do_exhaustive_model_search, do_qlp_coeff_prec_search, rice_optimization_level, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, &encoder_wrapper))
219                 goto wav_abort_;
220
221         bytes_per_wide_sample = channels * (bps >> 3);
222
223         if(-1 == fseek(fin, bytes_per_wide_sample * (unsigned)skip, SEEK_CUR)) {
224                 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
225                 goto wav_abort_;
226         }
227
228         encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample - skip;
229         encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44; /* 44 for the size of the WAV headers */
230         encoder_wrapper.verify_fifo.into_frames = true;
231
232         while(data_bytes > 0) {
233                 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, fin);
234                 if(bytes_read == 0) {
235                         if(ferror(fin)) {
236                                 fprintf(stderr, "ERROR reading from %s\n", infile);
237                                 goto wav_abort_;
238                         }
239                         else if(feof(fin))
240                                 break;
241                 }
242                 else {
243                         if(bytes_read > data_bytes)
244                                 bytes_read = data_bytes; /* chop off anything after the end of the data chunk */
245                         if(bytes_read % bytes_per_wide_sample != 0) {
246                                 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infile);
247                                 goto wav_abort_;
248                         }
249                         else {
250                                 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
251                                 format_input(wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
252                                 if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
253                                         fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
254                                         goto wav_abort_;
255                                 }
256                                 data_bytes -= bytes_read;
257                         }
258                 }
259         }
260
261 wav_end_:
262         if(encoder_wrapper.encoder) {
263                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
264                         FLAC__encoder_finish(encoder_wrapper.encoder);
265                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
266         }
267         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
268                 print_stats(&encoder_wrapper);
269                 printf("\n");
270         }
271         if(verify) {
272                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
273                         printf("Verify FAILED!  Do not use %s\n", outfile);
274                         return 1;
275                 }
276                 else {
277                         printf("Verify succeeded\n");
278                 }
279         }
280         fclose(fin);
281         return 0;
282 wav_abort_:
283         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
284                 printf("\n");
285         if(encoder_wrapper.encoder) {
286                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
287                         FLAC__encoder_finish(encoder_wrapper.encoder);
288                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
289         }
290         if(verify) {
291                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
292                         printf("Verify FAILED!  Do not use %s\n", outfile);
293                         return 1;
294                 }
295                 else {
296                         printf("Verify succeeded\n");
297                 }
298         }
299         fclose(fin);
300         unlink(outfile);
301         return 1;
302 }
303
304 int encode_raw(const char *infile, const char *outfile, bool verbose, uint64 skip, bool verify, bool lax, bool do_mid_side, bool do_exhaustive_model_search, bool do_qlp_coeff_prec_search, unsigned rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned sample_rate)
305 {
306         encoder_wrapper_struct encoder_wrapper;
307         FILE *fin;
308         size_t bytes_read;
309         const size_t bytes_per_wide_sample = channels * (bps >> 3);
310
311         encoder_wrapper.encoder = 0;
312         encoder_wrapper.verify = verify;
313         encoder_wrapper.verbose = verbose;
314         encoder_wrapper.bytes_written = 0;
315         encoder_wrapper.samples_written = 0;
316         encoder_wrapper.outfile = outfile;
317
318         if(0 == strcmp(infile, "-")) {
319                 fin = stdin;
320         }
321         else {
322                 if(0 == (fin = fopen(infile, "rb"))) {
323                         fprintf(stderr, "ERROR: can't open input file %s\n", infile);
324                         return false;
325                 }
326         }
327         if(0 == strcmp(outfile, "-")) {
328                 encoder_wrapper.fout = stdout;
329         }
330         else {
331                 if(0 == (encoder_wrapper.fout = fopen(outfile, "wb"))) {
332                         fprintf(stderr, "ERROR: can't open output file %s\n", outfile);
333                         fclose(fin);
334                         return false;
335                 }
336         }
337
338         if(!init(&encoder_wrapper))
339                 goto raw_abort_;
340
341         if(!init_encoder(lax, do_mid_side, do_exhaustive_model_search, do_qlp_coeff_prec_search, rice_optimization_level, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, &encoder_wrapper))
342                 goto raw_abort_;
343
344         /* get the file length */
345         if(0 != fseek(fin, 0, SEEK_END)) {
346                 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
347         }
348         else {
349                 long filesize;
350                 fflush(fin);
351                 if(-1 == (filesize = ftell(fin))) {
352                         encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
353                 }
354                 else {
355                         encoder_wrapper.unencoded_size = filesize - skip * bytes_per_wide_sample;
356                         encoder_wrapper.total_samples_to_encode = filesize / bytes_per_wide_sample - skip;
357                 }
358         }
359
360         if(-1 == fseek(fin, bytes_per_wide_sample * (unsigned)skip, SEEK_SET)) {
361                 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
362                 goto raw_abort_;
363         }
364
365         encoder_wrapper.verify_fifo.into_frames = true;
366
367         while(!feof(fin)) {
368                 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, fin);
369                 if(bytes_read == 0) {
370                         if(ferror(fin)) {
371                                 fprintf(stderr, "ERROR reading from %s\n", infile);
372                                 goto raw_abort_;
373                         }
374                 }
375                 else if(bytes_read % bytes_per_wide_sample != 0) {
376                         fprintf(stderr, "ERROR, got partial sample from input file %s\n", infile);
377                         goto raw_abort_;
378                 }
379                 else {
380                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
381                         format_input(wide_samples, is_big_endian, is_unsigned_samples, channels, bps, &encoder_wrapper);
382                         if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
383                                 fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
384                                 goto raw_abort_;
385                         }
386                 }
387         }
388
389         if(encoder_wrapper.encoder) {
390                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
391                         FLAC__encoder_finish(encoder_wrapper.encoder);
392                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
393         }
394         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
395                 print_stats(&encoder_wrapper);
396                 printf("\n");
397         }
398         if(verify) {
399                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
400                         printf("Verify FAILED!  Do not use %s\n", outfile);
401                         return 1;
402                 }
403                 else {
404                         printf("Verify succeeded\n");
405                 }
406         }
407         fclose(fin);
408         return 0;
409 raw_abort_:
410         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
411                 printf("\n");
412         if(encoder_wrapper.encoder) {
413                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
414                         FLAC__encoder_finish(encoder_wrapper.encoder);
415                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
416         }
417         if(verify) {
418                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
419                         printf("Verify FAILED!  Do not use %s\n", outfile);
420                         return 1;
421                 }
422                 else {
423                         printf("Verify succeeded\n");
424                 }
425         }
426         fclose(fin);
427         unlink(outfile);
428         return 1;
429 }
430
431 bool init(encoder_wrapper_struct *encoder_wrapper)
432 {
433         unsigned i;
434         uint32 test = 1;
435
436         is_big_endian_host = (*((byte*)(&test)))? false : true;
437
438         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
439                 input[i] = &(in[i][0]);
440
441         encoder_wrapper->encoder = FLAC__encoder_get_new_instance();
442         if(0 == encoder_wrapper->encoder) {
443                 fprintf(stderr, "ERROR creating the encoder instance\n");
444                 return false;
445         }
446
447         return true;
448 }
449
450 bool init_encoder(bool lax, bool do_mid_side, bool do_exhaustive_model_search, bool do_qlp_coeff_prec_search, unsigned rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper)
451 {
452         if(channels != 2 || bps > 16)
453                 do_mid_side = false;
454
455         if(encoder_wrapper->verify) {
456                 unsigned i;
457
458                 /* set up the fifo which will hold the original signal to compare against */
459                 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
460                 for(i = 0; i < channels; i++) {
461                         if(0 == (encoder_wrapper->verify_fifo.original[i] = (int32*)malloc(sizeof(int32) * encoder_wrapper->verify_fifo.size))) {
462                                 fprintf(stderr, "ERROR allocating verify buffers\n");
463                                 return false;
464                         }
465                 }
466                 encoder_wrapper->verify_fifo.tail = 0;
467                 encoder_wrapper->verify_fifo.into_frames = false;
468                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
469
470                 /* set up a stream decoder for verification */
471                 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_get_new_instance();
472                 if(0 == encoder_wrapper->verify_fifo.decoder) {
473                         fprintf(stderr, "ERROR creating the verify decoder instance\n");
474                         return false;
475                 }
476                 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) {
477                         fprintf(stderr, "ERROR initializing decoder, state = %d:%s\n", encoder_wrapper->verify_fifo.decoder->state, FLAC__StreamDecoderStateString[encoder_wrapper->verify_fifo.decoder->state]);
478                         return false;
479                 }
480         }
481
482         encoder_wrapper->encoder->streamable_subset = !lax;
483         encoder_wrapper->encoder->channels = channels;
484         encoder_wrapper->encoder->bits_per_sample = bps;
485         encoder_wrapper->encoder->sample_rate = sample_rate;
486         encoder_wrapper->encoder->blocksize = blocksize;
487         encoder_wrapper->encoder->qlp_coeff_precision = qlp_coeff_precision;
488         encoder_wrapper->encoder->max_lpc_order = max_lpc_order;
489         encoder_wrapper->encoder->do_mid_side_stereo = do_mid_side;
490         encoder_wrapper->encoder->do_exhaustive_model_search = do_exhaustive_model_search;
491         encoder_wrapper->encoder->do_qlp_coeff_prec_search = do_qlp_coeff_prec_search;
492         encoder_wrapper->encoder->rice_optimization_level = rice_optimization_level;
493
494         if(FLAC__encoder_init(encoder_wrapper->encoder, write_callback, metadata_callback, encoder_wrapper) != FLAC__ENCODER_OK) {
495                 fprintf(stderr, "ERROR initializing encoder, state = %d\n", encoder_wrapper->encoder->state);
496                 return false;
497         }
498
499         return true;
500 }
501
502 void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
503 {
504         unsigned wide_sample, sample, channel, byte;
505
506         if(bps == 8) {
507                 if(is_unsigned_samples) {
508                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
509                                 for(channel = 0; channel < channels; channel++, sample++)
510                                         input[channel][wide_sample] = (int32)ucbuffer[sample] - 128;
511                 }
512                 else {
513                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
514                                 for(channel = 0; channel < channels; channel++, sample++)
515                                         input[channel][wide_sample] = (int32)scbuffer[sample];
516                 }
517         }
518         else {
519                 if(is_big_endian != is_big_endian_host) {
520                         unsigned char tmp;
521                         const unsigned bytes = wide_samples * channels * (bps >> 3);
522                         for(byte = 0; byte < bytes; byte += 2) {
523                                 tmp = ucbuffer[byte];
524                                 ucbuffer[byte] = ucbuffer[byte+1];
525                                 ucbuffer[byte+1] = tmp;
526                         }
527                 }
528                 if(is_unsigned_samples) {
529                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
530                                 for(channel = 0; channel < channels; channel++, sample++)
531                                         input[channel][wide_sample] = (int32)usbuffer[sample] - 32768;
532                 }
533                 else {
534                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
535                                 for(channel = 0; channel < channels; channel++, sample++)
536                                         input[channel][wide_sample] = (int32)ssbuffer[sample];
537                 }
538         }
539
540         if(encoder_wrapper->verify) {
541                 for(channel = 0; channel < channels; channel++)
542                         memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], &input[channel][0], sizeof(int32) * wide_samples);
543                 encoder_wrapper->verify_fifo.tail += wide_samples;
544                 assert(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
545         }
546 }
547
548 FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
549 {
550         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
551         unsigned mask = (encoder->do_exhaustive_model_search || encoder->do_qlp_coeff_prec_search)? 0x07 : 0x1f;
552
553         encoder_wrapper->bytes_written += bytes;
554         encoder_wrapper->samples_written += samples;
555         encoder_wrapper->current_frame = current_frame;
556
557         if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
558                 print_stats(encoder_wrapper);
559
560         if(encoder_wrapper->verify) {
561                 encoder_wrapper->verify_fifo.encoded_signal = buffer;
562                 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
563                 if(encoder_wrapper->verify_fifo.into_frames) {
564                         if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
565                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
566                                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
567                         }
568                 }
569                 else {
570                         if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
571                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
572                                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
573                         }
574                 }
575         }
576
577         if(fwrite(buffer, sizeof(byte), bytes, encoder_wrapper->fout) == bytes)
578                 return FLAC__ENCODER_WRITE_OK;
579         else
580                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
581 }
582
583 void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
584 {
585         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
586         byte b;
587         FILE *f;
588         const uint64 samples = metadata->data.encoding.total_samples;
589         const unsigned min_framesize = metadata->data.encoding.min_framesize;
590         const unsigned max_framesize = metadata->data.encoding.max_framesize;
591
592         (void)encoder; /* silence compiler warning about unused parameter */
593
594         if(encoder_wrapper->fout == stdout)
595                 return;
596
597         fclose(encoder_wrapper->fout);
598         if(0 == (f = fopen(encoder_wrapper->outfile, "r+b")))
599                 return;
600
601         /* all this is based on intimate knowledge of the stream header
602          * layout, but a change to the header format that would break this
603          * would also break all streams encoded in the previous format.
604          */
605
606         if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
607         fwrite(metadata->data.encoding.md5sum, 1, 16, f);
608
609 samples_:
610         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
611         if(fread(&b, 1, 1, f) != 1) goto framesize_;
612         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
613         b = (b & 0xf0) | (byte)((samples >> 32) & 0x0F);
614         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
615         b = (byte)((samples >> 24) & 0xFF);
616         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
617         b = (byte)((samples >> 16) & 0xFF);
618         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
619         b = (byte)((samples >> 8) & 0xFF);
620         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
621         b = (byte)(samples & 0xFF);
622         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
623
624 framesize_:
625         if(-1 == fseek(f, 12, SEEK_SET)) goto end_;
626         b = (byte)((min_framesize >> 16) & 0xFF);
627         if(fwrite(&b, 1, 1, f) != 1) goto end_;
628         b = (byte)((min_framesize >> 8) & 0xFF);
629         if(fwrite(&b, 1, 1, f) != 1) goto end_;
630         b = (byte)(min_framesize & 0xFF);
631         if(fwrite(&b, 1, 1, f) != 1) goto end_;
632         b = (byte)((max_framesize >> 16) & 0xFF);
633         if(fwrite(&b, 1, 1, f) != 1) goto end_;
634         b = (byte)((max_framesize >> 8) & 0xFF);
635         if(fwrite(&b, 1, 1, f) != 1) goto end_;
636         b = (byte)(max_framesize & 0xFF);
637         if(fwrite(&b, 1, 1, f) != 1) goto end_;
638 end_:
639         fclose(encoder_wrapper->fout);
640         return;
641 }
642
643 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
644 {
645         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
646         (void)decoder;
647
648         *bytes = encoder_wrapper->verify_fifo.encoded_bytes;
649         memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
650
651         return FLAC__STREAM_DECODER_READ_CONTINUE;
652 }
653
654 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__FrameHeader *header, const int32 *buffer[], void *client_data)
655 {
656         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
657         unsigned channel, l, r;
658
659         for(channel = 0; channel < decoder->channels; channel++) {
660                 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], sizeof(int32) * decoder->blocksize)) {
661                         fprintf(stderr, "\nERROR: mismatch in decoded data, verify FAILED!\n");
662                         fprintf(stderr, "       Please submit a bug report to http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
663                         return FLAC__STREAM_DECODER_WRITE_ABORT;
664                 }
665         }
666         /* dequeue the frame from the fifo */
667         for(channel = 0; channel < decoder->channels; channel++) {
668                 for(l = 0, r = header->blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
669                         encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
670                 }
671         }
672         encoder_wrapper->verify_fifo.tail -= header->blocksize;
673         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
674 }
675
676 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
677 {
678         (void)decoder;
679         (void)metadata;
680         (void)client_data;
681 }
682
683 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
684 {
685         (void)decoder;
686         (void)client_data;
687         fprintf(stderr, "\nERROR: verification decoder returned error %d:%s\n", status, FLAC__StreamDecoderErrorStatusString[status]);
688 }
689
690 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
691 {
692 #ifdef _MSC_VER
693         /* with VC++ you have to spoon feed it the casting */
694         double progress = (double)(int64)encoder_wrapper->samples_written / (double)(int64)encoder_wrapper->total_samples_to_encode;
695 #else
696         double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
697 #endif
698         printf("\r%0.2f%% complete: frame %u, wrote %u bytes, %u of %u samples, ratio = %5.3f",
699                 progress * 100.0, encoder_wrapper->current_frame,
700                 (unsigned)encoder_wrapper->bytes_written, (unsigned)encoder_wrapper->samples_written, (unsigned)encoder_wrapper->total_samples_to_encode,
701 #ifdef _MSC_VER
702                 /* with VC++ you have to spoon feed it the casting */
703                 (double)(int64)encoder_wrapper->bytes_written / ((double)(int64)encoder_wrapper->unencoded_size * progress)
704 #else
705                 (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress)
706 #endif
707         );
708         fflush(stdout);
709 }
710
711 bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok)
712 {
713         size_t bytes_read = fread(val, 1, 2, f);
714
715         if(bytes_read == 0) {
716                 if(!eof_ok) {
717                         fprintf(stderr, "ERROR: unexpected EOF\n");
718                         return false;
719                 }
720                 else
721                         return true;
722         }
723         else if(bytes_read < 2) {
724                 fprintf(stderr, "ERROR: unexpected EOF\n");
725                 return false;
726         }
727         else {
728                 if(is_big_endian_host) {
729                         byte tmp, *b = (byte*)val;
730                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
731                 }
732                 return true;
733         }
734 }
735
736 bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok)
737 {
738         size_t bytes_read = fread(val, 1, 4, f);
739
740         if(bytes_read == 0) {
741                 if(!eof_ok) {
742                         fprintf(stderr, "ERROR: unexpected EOF\n");
743                         return false;
744                 }
745                 else
746                         return true;
747         }
748         else if(bytes_read < 4) {
749                 fprintf(stderr, "ERROR: unexpected EOF\n");
750                 return false;
751         }
752         else {
753                 if(is_big_endian_host) {
754                         byte tmp, *b = (byte*)val;
755                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
756                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
757                 }
758                 return true;
759         }
760 }