add more verbose status reporting
[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 *outfile;
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         unsigned current_frame;
76         verify_fifo_struct verify_fifo;
77 } encoder_wrapper_struct;
78
79 static bool is_big_endian_host;
80
81 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__MAX_BITS_PER_SAMPLE+7)/8)];
82 static signed char *scbuffer = (signed char *)ucbuffer;
83 static uint16 *usbuffer = (uint16 *)ucbuffer;
84 static int16 *ssbuffer = (int16 *)ucbuffer;
85
86 static int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
87 static int32 *input[FLAC__MAX_CHANNELS];
88
89 /* local routines */
90 static bool init(encoder_wrapper_struct *encoder_wrapper);
91 static bool init_encoder(bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, bool do_qlp_coeff_prec_search, unsigned rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, unsigned padding, encoder_wrapper_struct *encoder_wrapper);
92 static void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
93 static FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
94 static void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
95 static FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data);
96 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data);
97 static void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
98 static void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
99 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
100 static bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok);
101 static bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok);
102
103 int encode_wav(const char *infile, const char *outfile, 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 rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned padding)
104 {
105         encoder_wrapper_struct encoder_wrapper;
106         FILE *fin;
107         bool is_unsigned_samples;
108         unsigned channels, bps, sample_rate, data_bytes;
109         size_t bytes_per_wide_sample, bytes_read;
110         uint16 x;
111         uint32 xx;
112
113         encoder_wrapper.encoder = 0;
114         encoder_wrapper.verify = verify;
115         encoder_wrapper.verbose = verbose;
116         encoder_wrapper.bytes_written = 0;
117         encoder_wrapper.samples_written = 0;
118         encoder_wrapper.outfile = outfile;
119
120         if(0 == strcmp(infile, "-")) {
121                 fin = stdin;
122         }
123         else {
124                 if(0 == (fin = fopen(infile, "rb"))) {
125                         fprintf(stderr, "ERROR: can't open input file %s\n", infile);
126                         return false;
127                 }
128         }
129         if(0 == strcmp(outfile, "-")) {
130                 encoder_wrapper.fout = stdout;
131         }
132         else {
133                 if(0 == (encoder_wrapper.fout = fopen(outfile, "wb"))) {
134                         fprintf(stderr, "ERROR: can't open output file %s\n", outfile);
135                         fclose(fin);
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(fin, &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(fin, &xx, false))
153                 goto wav_abort_;
154
155         /*
156          * now process the WAVE chunk
157          */
158         if(!read_little_endian_uint32(fin, &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(fin, &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(fin, &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(fin, &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(fin, &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(fin, &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(fin, &xx, false))
204                 goto wav_abort_;
205         /* block align (ignored) */
206         if(!read_little_endian_uint16(fin, &x, false))
207                 goto wav_abort_;
208         /* bits per sample */
209         if(!read_little_endian_uint16(fin, &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(fin, &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(fin, &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(fin != stdin) {
234                         if(-1 == fseek(fin, bytes_per_wide_sample * (unsigned)skip, SEEK_CUR)) {
235                                 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
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, fin) < need) {
245                                         fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
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, rice_optimization_level, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, &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, fin);
262                 if(bytes_read == 0) {
263                         if(ferror(fin)) {
264                                 fprintf(stderr, "ERROR reading from %s\n", infile);
265                                 goto wav_abort_;
266                         }
267                         else if(feof(fin))
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", infile);
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                                 if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
281                                         fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
282                                         goto wav_abort_;
283                                 }
284                                 data_bytes -= bytes_read;
285                         }
286                 }
287         }
288
289 wav_end_:
290         if(encoder_wrapper.encoder) {
291                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
292                         FLAC__encoder_finish(encoder_wrapper.encoder);
293                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
294         }
295         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
296                 print_stats(&encoder_wrapper);
297                 printf("\n");
298         }
299         if(verify) {
300                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
301                         printf("Verify FAILED! (%s)  Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
302                         return 1;
303                 }
304                 else {
305                         printf("Verify succeeded\n");
306                 }
307         }
308         fclose(fin);
309         return 0;
310 wav_abort_:
311         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
312                 printf("\n");
313         if(encoder_wrapper.encoder) {
314                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
315                         FLAC__encoder_finish(encoder_wrapper.encoder);
316                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
317         }
318         if(verify) {
319                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
320                         printf("Verify FAILED! (%s)  Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
321                         return 1;
322                 }
323                 else {
324                         printf("Verify succeeded\n");
325                 }
326         }
327         fclose(fin);
328         unlink(outfile);
329         return 1;
330 }
331
332 int encode_raw(const char *infile, const char *outfile, 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 rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned padding, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned sample_rate)
333 {
334         encoder_wrapper_struct encoder_wrapper;
335         FILE *fin;
336         size_t bytes_read;
337         const size_t bytes_per_wide_sample = channels * (bps >> 3);
338
339         encoder_wrapper.encoder = 0;
340         encoder_wrapper.verify = verify;
341         encoder_wrapper.verbose = verbose;
342         encoder_wrapper.bytes_written = 0;
343         encoder_wrapper.samples_written = 0;
344         encoder_wrapper.outfile = outfile;
345
346         if(0 == strcmp(infile, "-")) {
347                 fin = stdin;
348         }
349         else {
350                 if(0 == (fin = fopen(infile, "rb"))) {
351                         fprintf(stderr, "ERROR: can't open input file %s\n", infile);
352                         return false;
353                 }
354         }
355         if(0 == strcmp(outfile, "-")) {
356                 encoder_wrapper.fout = stdout;
357         }
358         else {
359                 if(0 == (encoder_wrapper.fout = fopen(outfile, "wb"))) {
360                         fprintf(stderr, "ERROR: can't open output file %s\n", outfile);
361                         fclose(fin);
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(fin, 0, SEEK_END)) {
371                 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
372         }
373         else {
374                 long filesize;
375                 fflush(fin);
376                 if(-1 == (filesize = ftell(fin))) {
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(fin != stdin) {
387                         if(-1 == fseek(fin, bytes_per_wide_sample * (unsigned)skip, SEEK_SET)) {
388                                 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
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, fin) < need) {
398                                         fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
399                                         goto raw_abort_;
400                                 }
401                         }
402                 }
403         }
404         else {
405                 fseek(fin, 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, rice_optimization_level, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, &encoder_wrapper))
409                 goto raw_abort_;
410
411         encoder_wrapper.verify_fifo.into_frames = true;
412
413         while(!feof(fin)) {
414                 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, fin);
415                 if(bytes_read == 0) {
416                         if(ferror(fin)) {
417                                 fprintf(stderr, "ERROR reading from %s\n", infile);
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", infile);
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                         if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
429                                 fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
430                                 goto raw_abort_;
431                         }
432                 }
433         }
434
435         if(encoder_wrapper.encoder) {
436                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
437                         FLAC__encoder_finish(encoder_wrapper.encoder);
438                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
439         }
440         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
441                 print_stats(&encoder_wrapper);
442                 printf("\n");
443         }
444         if(verify) {
445                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
446                         printf("Verify FAILED! (%s)  Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
447                         return 1;
448                 }
449                 else {
450                         printf("Verify succeeded\n");
451                 }
452         }
453         fclose(fin);
454         return 0;
455 raw_abort_:
456         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
457                 printf("\n");
458         if(encoder_wrapper.encoder) {
459                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
460                         FLAC__encoder_finish(encoder_wrapper.encoder);
461                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
462         }
463         if(verify) {
464                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
465                         printf("Verify FAILED! (%s)  Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
466                         return 1;
467                 }
468                 else {
469                         printf("Verify succeeded\n");
470                 }
471         }
472         fclose(fin);
473         unlink(outfile);
474         return 1;
475 }
476
477 bool init(encoder_wrapper_struct *encoder_wrapper)
478 {
479         unsigned i;
480         uint32 test = 1;
481
482         is_big_endian_host = (*((byte*)(&test)))? false : true;
483
484         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
485                 input[i] = &(in[i][0]);
486
487         encoder_wrapper->encoder = FLAC__encoder_get_new_instance();
488         if(0 == encoder_wrapper->encoder) {
489                 fprintf(stderr, "ERROR creating the encoder instance\n");
490                 return false;
491         }
492
493         return true;
494 }
495
496 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 rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, unsigned padding, encoder_wrapper_struct *encoder_wrapper)
497 {
498         if(channels != 2)
499                 do_mid_side = loose_mid_side = false;
500
501         if(encoder_wrapper->verify) {
502                 unsigned i;
503
504                 /* set up the fifo which will hold the original signal to compare against */
505                 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
506                 for(i = 0; i < channels; i++) {
507                         if(0 == (encoder_wrapper->verify_fifo.original[i] = (int32*)malloc(sizeof(int32) * encoder_wrapper->verify_fifo.size))) {
508                                 fprintf(stderr, "ERROR allocating verify buffers\n");
509                                 return false;
510                         }
511                 }
512                 encoder_wrapper->verify_fifo.tail = 0;
513                 encoder_wrapper->verify_fifo.into_frames = false;
514                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
515
516                 /* set up a stream decoder for verification */
517                 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_get_new_instance();
518                 if(0 == encoder_wrapper->verify_fifo.decoder) {
519                         fprintf(stderr, "ERROR creating the verify decoder instance\n");
520                         return false;
521                 }
522                 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) {
523                         fprintf(stderr, "ERROR initializing decoder, state = %d:%s\n", encoder_wrapper->verify_fifo.decoder->state, FLAC__StreamDecoderStateString[encoder_wrapper->verify_fifo.decoder->state]);
524                         return false;
525                 }
526         }
527
528         encoder_wrapper->encoder->streamable_subset = !lax;
529         encoder_wrapper->encoder->channels = channels;
530         encoder_wrapper->encoder->bits_per_sample = bps;
531         encoder_wrapper->encoder->sample_rate = sample_rate;
532         encoder_wrapper->encoder->blocksize = blocksize;
533         encoder_wrapper->encoder->qlp_coeff_precision = qlp_coeff_precision;
534         encoder_wrapper->encoder->max_lpc_order = max_lpc_order;
535         encoder_wrapper->encoder->do_mid_side_stereo = do_mid_side;
536         encoder_wrapper->encoder->loose_mid_side_stereo = loose_mid_side;
537         encoder_wrapper->encoder->do_exhaustive_model_search = do_exhaustive_model_search;
538         encoder_wrapper->encoder->do_qlp_coeff_prec_search = do_qlp_coeff_prec_search;
539         encoder_wrapper->encoder->rice_optimization_level = rice_optimization_level;
540         encoder_wrapper->encoder->total_samples_estimate = encoder_wrapper->total_samples_to_encode;
541         encoder_wrapper->encoder->padding = padding;
542
543         if(FLAC__encoder_init(encoder_wrapper->encoder, write_callback, metadata_callback, encoder_wrapper) != FLAC__ENCODER_OK) {
544                 fprintf(stderr, "ERROR initializing encoder, state = %d:%s\n", encoder_wrapper->encoder->state, FLAC__EncoderStateString[encoder_wrapper->encoder->state]);
545                 return false;
546         }
547
548         return true;
549 }
550
551 void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
552 {
553         unsigned wide_sample, sample, channel, byte;
554
555         if(bps == 8) {
556                 if(is_unsigned_samples) {
557                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
558                                 for(channel = 0; channel < channels; channel++, sample++)
559                                         input[channel][wide_sample] = (int32)ucbuffer[sample] - 0x80;
560                 }
561                 else {
562                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
563                                 for(channel = 0; channel < channels; channel++, sample++)
564                                         input[channel][wide_sample] = (int32)scbuffer[sample];
565                 }
566         }
567         else if(bps == 16) {
568                 if(is_big_endian != is_big_endian_host) {
569                         unsigned char tmp;
570                         const unsigned bytes = wide_samples * channels * (bps >> 3);
571                         for(byte = 0; byte < bytes; byte += 2) {
572                                 tmp = ucbuffer[byte];
573                                 ucbuffer[byte] = ucbuffer[byte+1];
574                                 ucbuffer[byte+1] = tmp;
575                         }
576                 }
577                 if(is_unsigned_samples) {
578                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
579                                 for(channel = 0; channel < channels; channel++, sample++)
580                                         input[channel][wide_sample] = (int32)usbuffer[sample] - 0x8000;
581                 }
582                 else {
583                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
584                                 for(channel = 0; channel < channels; channel++, sample++)
585                                         input[channel][wide_sample] = (int32)ssbuffer[sample];
586                 }
587         }
588         else if(bps == 24) {
589                 if(!is_big_endian) {
590                         unsigned char tmp;
591                         const unsigned bytes = wide_samples * channels * (bps >> 3);
592                         for(byte = 0; byte < bytes; byte += 3) {
593                                 tmp = ucbuffer[byte];
594                                 ucbuffer[byte] = ucbuffer[byte+2];
595                                 ucbuffer[byte+2] = tmp;
596                         }
597                 }
598                 if(is_unsigned_samples) {
599                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
600                                 for(channel = 0; channel < channels; channel++, sample++) {
601                                         input[channel][wide_sample]  = ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
602                                         input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
603                                         input[channel][wide_sample] |= ucbuffer[byte++];
604                                         input[channel][wide_sample] -= 0x800000;
605                                 }
606                 }
607                 else {
608                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
609                                 for(channel = 0; channel < channels; channel++, sample++) {
610                                         input[channel][wide_sample]  = scbuffer[byte++]; input[channel][wide_sample] <<= 8;
611                                         input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
612                                         input[channel][wide_sample] |= ucbuffer[byte++];
613                                 }
614                 }
615         }
616         else {
617                 assert(0);
618         }
619
620         if(encoder_wrapper->verify) {
621                 for(channel = 0; channel < channels; channel++)
622                         memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], &input[channel][0], sizeof(int32) * wide_samples);
623                 encoder_wrapper->verify_fifo.tail += wide_samples;
624                 assert(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
625         }
626 }
627
628 FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
629 {
630         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
631         unsigned mask = (encoder->do_exhaustive_model_search || encoder->do_qlp_coeff_prec_search)? 0x07 : 0x1f;
632
633         encoder_wrapper->bytes_written += bytes;
634         encoder_wrapper->samples_written += samples;
635         encoder_wrapper->current_frame = current_frame;
636
637         if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
638                 print_stats(encoder_wrapper);
639
640         if(encoder_wrapper->verify) {
641                 encoder_wrapper->verify_fifo.encoded_signal = buffer;
642                 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
643                 if(encoder_wrapper->verify_fifo.into_frames) {
644                         if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
645                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
646                                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
647                         }
648                 }
649                 else {
650                         if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
651                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
652                                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
653                         }
654                 }
655         }
656
657         if(fwrite(buffer, sizeof(byte), bytes, encoder_wrapper->fout) == bytes)
658                 return FLAC__ENCODER_WRITE_OK;
659         else
660                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
661 }
662
663 void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
664 {
665         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
666         byte b;
667         FILE *f;
668         const uint64 samples = metadata->data.stream_info.total_samples;
669         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
670         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
671
672         (void)encoder; /* silence compiler warning about unused parameter */
673
674         if(encoder_wrapper->fout == stdout)
675                 return;
676
677         fclose(encoder_wrapper->fout);
678         if(0 == (f = fopen(encoder_wrapper->outfile, "r+b")))
679                 return;
680
681         /* all this is based on intimate knowledge of the stream header
682          * layout, but a change to the header format that would break this
683          * would also break all streams encoded in the previous format.
684          */
685
686         if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
687         fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
688
689 samples_:
690         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
691         if(fread(&b, 1, 1, f) != 1) goto framesize_;
692         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
693         b = (b & 0xf0) | (byte)((samples >> 32) & 0x0F);
694         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
695         b = (byte)((samples >> 24) & 0xFF);
696         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
697         b = (byte)((samples >> 16) & 0xFF);
698         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
699         b = (byte)((samples >> 8) & 0xFF);
700         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
701         b = (byte)(samples & 0xFF);
702         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
703
704 framesize_:
705         if(-1 == fseek(f, 12, SEEK_SET)) goto end_;
706         b = (byte)((min_framesize >> 16) & 0xFF);
707         if(fwrite(&b, 1, 1, f) != 1) goto end_;
708         b = (byte)((min_framesize >> 8) & 0xFF);
709         if(fwrite(&b, 1, 1, f) != 1) goto end_;
710         b = (byte)(min_framesize & 0xFF);
711         if(fwrite(&b, 1, 1, f) != 1) goto end_;
712         b = (byte)((max_framesize >> 16) & 0xFF);
713         if(fwrite(&b, 1, 1, f) != 1) goto end_;
714         b = (byte)((max_framesize >> 8) & 0xFF);
715         if(fwrite(&b, 1, 1, f) != 1) goto end_;
716         b = (byte)(max_framesize & 0xFF);
717         if(fwrite(&b, 1, 1, f) != 1) goto end_;
718 end_:
719         fclose(f);
720         return;
721 }
722
723 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
724 {
725         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
726         const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
727         (void)decoder;
728
729         if(encoded_bytes <= *bytes) {
730                 *bytes = encoded_bytes;
731                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
732         }
733         else {
734                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
735                 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
736                 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
737         }
738
739         return FLAC__STREAM_DECODER_READ_CONTINUE;
740 }
741
742 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
743 {
744         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
745         unsigned channel, l, r;
746
747         for(channel = 0; channel < decoder->channels; channel++) {
748                 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], sizeof(int32) * decoder->blocksize)) {
749                         fprintf(stderr, "\nERROR: mismatch in decoded data, verify FAILED!\n");
750                         fprintf(stderr, "       Please submit a bug report to http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
751                         return FLAC__STREAM_DECODER_WRITE_ABORT;
752                 }
753         }
754         /* dequeue the frame from the fifo */
755         for(channel = 0; channel < decoder->channels; channel++) {
756                 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
757                         encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
758                 }
759         }
760         encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
761         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
762 }
763
764 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
765 {
766         (void)decoder;
767         (void)metadata;
768         (void)client_data;
769 }
770
771 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
772 {
773         (void)decoder;
774         (void)client_data;
775         fprintf(stderr, "\nERROR: verification decoder returned error %d:%s\n", status, FLAC__StreamDecoderErrorStatusString[status]);
776 }
777
778 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
779 {
780 #ifdef _MSC_VER
781         /* with VC++ you have to spoon feed it the casting */
782         double progress = (double)(int64)encoder_wrapper->samples_written / (double)(int64)encoder_wrapper->total_samples_to_encode;
783 #else
784         double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
785 #endif
786         printf("\r%0.2f%% complete: frame %u, wrote %u bytes, %u of %u samples, ratio = %5.3f",
787                 progress * 100.0, encoder_wrapper->current_frame,
788                 (unsigned)encoder_wrapper->bytes_written, (unsigned)encoder_wrapper->samples_written, (unsigned)encoder_wrapper->total_samples_to_encode,
789 #ifdef _MSC_VER
790                 /* with VC++ you have to spoon feed it the casting */
791                 (double)(int64)encoder_wrapper->bytes_written / ((double)(int64)encoder_wrapper->unencoded_size * progress)
792 #else
793                 (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress)
794 #endif
795         );
796         fflush(stdout);
797 }
798
799 bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok)
800 {
801         size_t bytes_read = fread(val, 1, 2, f);
802
803         if(bytes_read == 0) {
804                 if(!eof_ok) {
805                         fprintf(stderr, "ERROR: unexpected EOF\n");
806                         return false;
807                 }
808                 else
809                         return true;
810         }
811         else if(bytes_read < 2) {
812                 fprintf(stderr, "ERROR: unexpected EOF\n");
813                 return false;
814         }
815         else {
816                 if(is_big_endian_host) {
817                         byte tmp, *b = (byte*)val;
818                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
819                 }
820                 return true;
821         }
822 }
823
824 bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok)
825 {
826         size_t bytes_read = fread(val, 1, 4, f);
827
828         if(bytes_read == 0) {
829                 if(!eof_ok) {
830                         fprintf(stderr, "ERROR: unexpected EOF\n");
831                         return false;
832                 }
833                 else
834                         return true;
835         }
836         else if(bytes_read < 4) {
837                 fprintf(stderr, "ERROR: unexpected EOF\n");
838                 return false;
839         }
840         else {
841                 if(is_big_endian_host) {
842                         byte tmp, *b = (byte*)val;
843                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
844                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
845                 }
846                 return true;
847         }
848 }