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