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