fix bug where raw encoder rewinds to beginning of file when it shouldn't
[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 #if defined _WIN32 && !defined __CYGWIN__
20 /* where MSVC puts unlink() */
21 # include <io.h>
22 #else
23 # include <unistd.h>
24 #endif
25 #include <math.h> /* for floor() */
26 #include <stdio.h> /* for FILE et al. */
27 #include <stdlib.h> /* for malloc */
28 #include <string.h> /* for strcmp() */
29 #include "FLAC/all.h"
30 #include "encode.h"
31 #include "file.h"
32
33 #ifdef min
34 #undef min
35 #endif
36 #define min(x,y) ((x)<(y)?(x):(y))
37
38 /* this MUST be >= 588 so that sector aligning can take place with one read */
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         FLAC__int32 *original[FLAC__MAX_CHANNELS];
55         unsigned size; /* of each original[] in samples */
56         unsigned tail; /* in wide samples */
57         const FLAC__byte *encoded_signal;
58         unsigned encoded_signal_capacity;
59         unsigned encoded_bytes;
60         FLAC__bool into_frames;
61         verify_code result;
62         FLAC__StreamDecoder *decoder;
63 } verify_fifo_struct;
64
65 typedef struct {
66         const char *inbasefilename;
67         FILE *fout;
68         const char *outfilename;
69         FLAC__StreamEncoder *encoder;
70         FLAC__bool verify;
71         FLAC__bool verbose;
72         FLAC__uint64 unencoded_size;
73         FLAC__uint64 total_samples_to_encode;
74         FLAC__uint64 bytes_written;
75         FLAC__uint64 samples_written;
76         FLAC__uint64 stream_offset; /* i.e. number of bytes before the first byte of the the first frame's header */
77         unsigned current_frame;
78         verify_fifo_struct verify_fifo;
79         FLAC__StreamMetaData_SeekTable seek_table;
80         unsigned first_seek_point_to_check;
81 } encoder_wrapper_struct;
82
83 static FLAC__bool is_big_endian_host;
84
85 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__MAX_BITS_PER_SAMPLE+7)/8)];
86 static signed char *scbuffer = (signed char *)ucbuffer;
87 static FLAC__uint16 *usbuffer = (FLAC__uint16 *)ucbuffer;
88 static FLAC__int16 *ssbuffer = (FLAC__int16 *)ucbuffer;
89
90 static FLAC__int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
91 static FLAC__int32 *input[FLAC__MAX_CHANNELS];
92
93 /* local routines */
94 static FLAC__bool init(encoder_wrapper_struct *encoder_wrapper);
95 static FLAC__bool init_encoder(FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_escape_coding, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, unsigned padding, char *requested_seek_points, int num_requested_seek_points, encoder_wrapper_struct *encoder_wrapper);
96 static FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table);
97 static void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, FLAC__uint64 sample, FLAC__uint64 stream_samples, FLAC__uint64 blocksize);
98 static int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r);
99 static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
100 static void append_to_verify_fifo(encoder_wrapper_struct *encoder_wrapper, const FLAC__int32 *input[], unsigned channels, unsigned wide_samples);
101 static FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
102 static void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
103 static FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
104 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data);
105 static void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
106 static void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
107 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
108 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
109 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
110 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
111 static FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val);
112
113 int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, FLAC__int32 *align_reservoir[], unsigned *align_reservoir_samples, FLAC__bool sector_align, FLAC__bool is_last_file, FLAC__bool verbose, FLAC__uint64 skip, FLAC__bool verify, FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_escape_coding, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned padding, char *requested_seek_points, int num_requested_seek_points)
114 {
115         encoder_wrapper_struct encoder_wrapper;
116         FLAC__bool is_unsigned_samples = false;
117         unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
118         size_t bytes_per_wide_sample, bytes_read;
119         FLAC__uint16 x;
120         FLAC__uint32 xx;
121         FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
122         unsigned align_remainder = 0;
123         int info_align_carry = -1, info_align_zero = -1;
124
125         FLAC__ASSERT(!sector_align || skip == 0);
126
127         encoder_wrapper.encoder = 0;
128         encoder_wrapper.verify = verify;
129         encoder_wrapper.verbose = verbose;
130         encoder_wrapper.bytes_written = 0;
131         encoder_wrapper.samples_written = 0;
132         encoder_wrapper.stream_offset = 0;
133         encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
134         encoder_wrapper.outfilename = outfilename;
135         encoder_wrapper.seek_table.points = 0;
136         encoder_wrapper.first_seek_point_to_check = 0;
137         (void)infilesize;
138         (void)lookahead;
139         (void)lookahead_length;
140
141         if(0 == strcmp(outfilename, "-")) {
142                 encoder_wrapper.fout = stdout;
143         }
144         else {
145                 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
146                         fprintf(stderr, "%s: ERROR: can't open output file %s\n", encoder_wrapper.inbasefilename, outfilename);
147                         fclose(infile);
148                         return 1;
149                 }
150         }
151
152         if(!init(&encoder_wrapper))
153                 goto wav_abort_;
154
155         /*
156          * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
157          */
158         while(!feof(infile)) {
159                 if(!read_little_endian_uint32(infile, &xx, true, encoder_wrapper.inbasefilename))
160                         goto wav_abort_;
161                 if(feof(infile))
162                         break;
163                 if(xx == 0x20746d66) { /* "fmt " */
164                         if(got_fmt_chunk) {
165                                 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_wrapper.inbasefilename);
166                         }
167                         else {
168                                 /* fmt sub-chunk size */
169                                 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
170                                         goto wav_abort_;
171                                 if(xx < 16) {
172                                         fprintf(stderr, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
173                                         goto wav_abort_;
174                                 }
175                                 else if(xx != 16 && xx != 18) {
176                                         fprintf(stderr, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
177                                 }
178                                 data_bytes = xx;
179                                 /* compression code */
180                                 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
181                                         goto wav_abort_;
182                                 if(x != 1) {
183                                         fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
184                                         goto wav_abort_;
185                                 }
186                                 /* number of channels */
187                                 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
188                                         goto wav_abort_;
189                                 if(x == 0 || x > FLAC__MAX_CHANNELS) {
190                                         fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
191                                         goto wav_abort_;
192                                 }
193                                 else if(sector_align && x != 2) {
194                                         fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)x);
195                                         goto wav_abort_;
196                                 }
197                                 channels = x;
198                                 /* sample rate */
199                                 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
200                                         goto wav_abort_;
201                                 if(xx == 0 || xx > FLAC__MAX_SAMPLE_RATE) {
202                                         fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
203                                         goto wav_abort_;
204                                 }
205                                 else if(sector_align && xx != 44100) {
206                                         fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)xx);
207                                         goto wav_abort_;
208                                 }
209                                 sample_rate = xx;
210                                 /* avg bytes per second (ignored) */
211                                 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
212                                         goto wav_abort_;
213                                 /* block align (ignored) */
214                                 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
215                                         goto wav_abort_;
216                                 /* bits per sample */
217                                 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
218                                         goto wav_abort_;
219                                 if(x != 8 && x != 16) {
220                                         fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
221                                         goto wav_abort_;
222                                 }
223                                 bps = x;
224                                 is_unsigned_samples = (x == 8);
225
226                                 /* skip any extra data in the fmt sub-chunk */
227                                 data_bytes -= 16;
228                                 if(data_bytes > 0) {
229                                         unsigned left, need;
230                                         for(left = data_bytes; left > 0; ) {
231                                                 need = min(left, CHUNK_OF_SAMPLES);
232                                                 if(fread(ucbuffer, 1, need, infile) < need) {
233                                                         fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
234                                                         goto wav_abort_;
235                                                 }
236                                                 left -= need;
237                                         }
238                                 }
239
240                                 got_fmt_chunk = true;
241                         }
242                 }
243                 else if(xx == 0x61746164) { /* "data" */
244                         if(got_data_chunk) {
245                                 fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_wrapper.inbasefilename);
246                         }
247                         else if(!got_fmt_chunk) {
248                                 fprintf(stderr, "%s: ERROR: got data sub-chunk before fmt sub-chunk\n", encoder_wrapper.inbasefilename);
249                                 goto wav_abort_;
250                         }
251                         else {
252                                 /* data size */
253                                 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
254                                         goto wav_abort_;
255                                 data_bytes = xx;
256
257                                 bytes_per_wide_sample = channels * (bps >> 3);
258
259                                 if(skip > 0) {
260                                         if(infile != stdin) {
261                                                 if(-1 == fseek(infile, bytes_per_wide_sample * (unsigned)skip, SEEK_CUR)) {
262                                                         fprintf(stderr, "%s: ERROR during seek while skipping samples\n", encoder_wrapper.inbasefilename);
263                                                         goto wav_abort_;
264                                                 }
265                                         }
266                                         else {
267                                                 unsigned left, need;
268                                                 for(left = (unsigned)skip; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
269                                                         need = min(left, CHUNK_OF_SAMPLES);
270                                                         if(fread(ucbuffer, bytes_per_wide_sample, need, infile) < need) {
271                                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
272                                                                 goto wav_abort_;
273                                                         }
274                                                         left -= need;
275                                                 }
276                                         }
277                                 }
278
279                                 data_bytes -= (unsigned)skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
280                                 encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample + *align_reservoir_samples;
281                                 if(sector_align) {
282                                         align_remainder = (unsigned)(encoder_wrapper.total_samples_to_encode % 588);
283                                         if(is_last_file)
284                                                 encoder_wrapper.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
285                                         else
286                                                 encoder_wrapper.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
287                                 }
288
289                                 /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
290                                 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44;
291
292                                 if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, do_escape_coding, do_qlp_coeff_prec_search, min_residual_partition_order, max_residual_partition_order, rice_parameter_search_dist, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, requested_seek_points, num_requested_seek_points, &encoder_wrapper))
293                                         goto wav_abort_;
294
295                                 encoder_wrapper.verify_fifo.into_frames = true;
296
297                                 /*
298                                  * first do any samples in the reservoir
299                                  */
300                                 if(sector_align && *align_reservoir_samples > 0) {
301                                         /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
302                                         append_to_verify_fifo(&encoder_wrapper, align_reservoir, channels, *align_reservoir_samples);
303
304                                         /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
305                                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, align_reservoir, *align_reservoir_samples)) {
306                                                 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
307                                                 goto wav_abort_;
308                                         }
309                                 }
310
311                                 /*
312                                  * decrement the data_bytes counter if we need to align the file
313                                  */
314                                 if(sector_align) {
315                                         if(is_last_file) {
316                                                 *align_reservoir_samples = 0;
317                                         }
318                                         else {
319                                                 *align_reservoir_samples = align_remainder;
320                                                 data_bytes -= (*align_reservoir_samples) * bytes_per_wide_sample;
321                                         }
322                                 }
323
324                                 /*
325                                  * now do from the file
326                                  */
327                                 while(data_bytes > 0) {
328                                         bytes_read = fread(ucbuffer, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
329                                         if(bytes_read == 0) {
330                                                 if(ferror(infile)) {
331                                                         fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
332                                                         goto wav_abort_;
333                                                 }
334                                                 else if(feof(infile)) {
335                                                         fprintf(stderr, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
336                                                         data_bytes = 0;
337                                                 }
338                                         }
339                                         else {
340                                                 if(bytes_read % bytes_per_wide_sample != 0) {
341                                                         fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
342                                                         goto wav_abort_;
343                                                 }
344                                                 else {
345                                                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
346                                                         format_input(input, wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
347
348                                                         /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
349                                                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
350                                                                 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
351                                                                 goto wav_abort_;
352                                                         }
353                                                         data_bytes -= bytes_read;
354                                                 }
355                                         }
356                                 }
357
358                                 /*
359                                  * now read unaligned samples into reservoir or pad with zeroes if necessary
360                                  */
361                                 if(sector_align) {
362                                         if(is_last_file) {
363                                                 unsigned wide_samples = 588 - align_remainder;
364                                                 if(wide_samples < 588) {
365                                                         unsigned channel;
366
367                                                         info_align_zero = wide_samples;
368                                                         data_bytes = wide_samples * bytes_per_wide_sample;
369                                                         for(channel = 0; channel < channels; channel++)
370                                                                 memset(input[channel], 0, data_bytes);
371                                                         /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
372                                                         append_to_verify_fifo(&encoder_wrapper, input, channels, wide_samples);
373
374                                                         /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
375                                                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
376                                                                 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
377                                                                 goto wav_abort_;
378                                                         }
379                                                 }
380                                         }
381                                         else {
382                                                 if(*align_reservoir_samples > 0) {
383                                                         FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
384                                                         bytes_read = fread(ucbuffer, sizeof(unsigned char), (*align_reservoir_samples) * bytes_per_wide_sample, infile);
385                                                         if(bytes_read == 0 && ferror(infile)) {
386                                                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
387                                                                 goto wav_abort_;
388                                                         }
389                                                         else if(bytes_read != (*align_reservoir_samples) * bytes_per_wide_sample) {
390                                                                 fprintf(stderr, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
391                                                                 data_bytes = 0;
392                                                         }
393                                                         else {
394                                                                 info_align_carry = *align_reservoir_samples;
395                                                                 format_input(align_reservoir, *align_reservoir_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
396                                                         }
397                                                 }
398                                         }
399                                 }
400
401                                 got_data_chunk = true;
402                         }
403                 }
404                 else {
405                         fprintf(stderr, "%s: WARNING: skipping unknown sub-chunk '%c%c%c%c'\n", encoder_wrapper.inbasefilename, (char)(xx&255), (char)((xx>>8)&255), (char)((xx>>16)&255), (char)(xx>>24));
406                         /* sub-chunk size */
407                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
408                                 goto wav_abort_;
409                         if(infile != stdin) {
410                                 if(-1 == fseek(infile, xx, SEEK_CUR)) {
411                                         fprintf(stderr, "%s: ERROR during seek while skipping unsupported sub-chunk\n", encoder_wrapper.inbasefilename);
412                                         goto wav_abort_;
413                                 }
414                         }
415                         else {
416                                 unsigned left, need;
417                                 const unsigned chunk = sizeof(ucbuffer);
418                                 for(left = xx; left > 0; ) {
419                                         need = min(left, chunk);
420                                         if(fread(ucbuffer, 1, need, infile) < need) {
421                                                 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_wrapper.inbasefilename);
422                                                 goto wav_abort_;
423                                         }
424                                         left -= need;
425                                 }
426                         }
427                 }
428         }
429
430         if(encoder_wrapper.encoder) {
431                 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
432                         FLAC__stream_encoder_finish(encoder_wrapper.encoder);
433                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
434         }
435         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
436                 print_stats(&encoder_wrapper);
437                 fprintf(stderr, "\n");
438         }
439         if(0 != encoder_wrapper.seek_table.points)
440                 free(encoder_wrapper.seek_table.points);
441         if(verify) {
442                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
443                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
444                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
445                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
446                         return 1;
447                 }
448         }
449         if(info_align_carry >= 0)
450                 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
451         if(info_align_zero >= 0)
452                 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
453         if(infile != stdin)
454                 fclose(infile);
455         return 0;
456 wav_abort_:
457         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
458                 fprintf(stderr, "\n");
459         if(encoder_wrapper.encoder) {
460                 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
461                         FLAC__stream_encoder_finish(encoder_wrapper.encoder);
462                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
463         }
464         if(0 != encoder_wrapper.seek_table.points)
465                 free(encoder_wrapper.seek_table.points);
466         if(verify) {
467                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
468                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
469                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
470                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
471                         return 1;
472                 }
473         }
474         if(infile != stdin)
475                 fclose(infile);
476         unlink(outfilename);
477         return 1;
478 }
479
480 int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, FLAC__bool is_last_file, FLAC__bool verbose, FLAC__uint64 skip, FLAC__bool verify, FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_escape_coding, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned padding, char *requested_seek_points, int num_requested_seek_points, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned sample_rate)
481 {
482         encoder_wrapper_struct encoder_wrapper;
483         size_t bytes_read;
484         const size_t bytes_per_wide_sample = channels * (bps >> 3);
485
486         (void)is_last_file;
487
488         encoder_wrapper.encoder = 0;
489         encoder_wrapper.verify = verify;
490         encoder_wrapper.verbose = verbose;
491         encoder_wrapper.bytes_written = 0;
492         encoder_wrapper.samples_written = 0;
493         encoder_wrapper.stream_offset = 0;
494         encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
495         encoder_wrapper.outfilename = outfilename;
496         encoder_wrapper.seek_table.points = 0;
497         encoder_wrapper.first_seek_point_to_check = 0;
498
499         if(0 == strcmp(outfilename, "-")) {
500                 encoder_wrapper.fout = stdout;
501         }
502         else {
503                 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
504                         fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
505                         fclose(infile);
506                         return 1;
507                 }
508         }
509
510         if(!init(&encoder_wrapper))
511                 goto raw_abort_;
512
513         /* get the file length */
514         if(infilesize < 0) {
515                 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
516         }
517         else {
518                 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - skip;
519                 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample;
520         }
521
522         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
523                 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
524
525         if(skip > 0) {
526                 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)skip;
527                 if(skip_bytes > lookahead_length) {
528                         skip_bytes -= lookahead_length;
529                         lookahead_length = 0;
530                         if(infile != stdin) {
531                                 if(-1 == fseek(infile, (long)skip_bytes, SEEK_CUR)) {
532                                         fprintf(stderr, "%s: ERROR during seek while skipping samples\n", encoder_wrapper.inbasefilename);
533                                         goto raw_abort_;
534                                 }
535                         }
536                         else {
537                                 unsigned left, need;
538                                 const unsigned chunk = sizeof(ucbuffer);
539                                 for(left = skip_bytes; left > 0; ) {
540                                         need = min(left, chunk);
541                                         if(fread(ucbuffer, 1, need, infile) < need) {
542                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
543                                                 goto raw_abort_;
544                                         }
545                                         left -= need;
546                                 }
547                         }
548                 }
549                 else {
550                         lookahead += skip_bytes;
551                         lookahead_length -= skip_bytes;
552                 }
553         }
554
555         if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, do_escape_coding, do_qlp_coeff_prec_search, min_residual_partition_order, max_residual_partition_order, rice_parameter_search_dist, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, requested_seek_points, num_requested_seek_points, &encoder_wrapper))
556                 goto raw_abort_;
557
558         encoder_wrapper.verify_fifo.into_frames = true;
559
560         while(!feof(infile)) {
561                 if(lookahead_length > 0) {
562                         FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
563                         memcpy(ucbuffer, lookahead, lookahead_length);
564                         bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
565                         if(ferror(infile)) {
566                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
567                                 goto raw_abort_;
568                         }
569                         lookahead_length = 0;
570                 }
571                 else
572                         bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
573
574                 if(bytes_read == 0) {
575                         if(ferror(infile)) {
576                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
577                                 goto raw_abort_;
578                         }
579                 }
580                 else if(bytes_read % bytes_per_wide_sample != 0) {
581                         fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
582                         goto raw_abort_;
583                 }
584                 else {
585                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
586                         format_input(input, wide_samples, is_big_endian, is_unsigned_samples, channels, bps, &encoder_wrapper);
587
588                         /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
589                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
590                                 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
591                                 goto raw_abort_;
592                         }
593                 }
594         }
595
596         if(encoder_wrapper.encoder) {
597                 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
598                         FLAC__stream_encoder_finish(encoder_wrapper.encoder);
599                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
600         }
601         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
602                 print_stats(&encoder_wrapper);
603                 fprintf(stderr, "\n");
604         }
605         if(0 != encoder_wrapper.seek_table.points)
606                 free(encoder_wrapper.seek_table.points);
607         if(verify) {
608                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
609                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
610                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
611                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
612                         return 1;
613                 }
614         }
615         if(infile != stdin)
616                 fclose(infile);
617         return 0;
618 raw_abort_:
619         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
620                 fprintf(stderr, "\n");
621         if(encoder_wrapper.encoder) {
622                 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
623                         FLAC__stream_encoder_finish(encoder_wrapper.encoder);
624                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
625         }
626         if(0 != encoder_wrapper.seek_table.points)
627                 free(encoder_wrapper.seek_table.points);
628         if(verify) {
629                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
630                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
631                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
632                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
633                         return 1;
634                 }
635         }
636         if(infile != stdin)
637                 fclose(infile);
638         unlink(outfilename);
639         return 1;
640 }
641
642 FLAC__bool init(encoder_wrapper_struct *encoder_wrapper)
643 {
644         unsigned i;
645         FLAC__uint32 test = 1;
646
647         is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
648
649         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
650                 input[i] = &(in[i][0]);
651
652         encoder_wrapper->encoder = FLAC__stream_encoder_new();
653         if(0 == encoder_wrapper->encoder) {
654                 fprintf(stderr, "%s: ERROR creating the encoder instance\n", encoder_wrapper->inbasefilename);
655                 return false;
656         }
657
658         return true;
659 }
660
661 FLAC__bool init_encoder(FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_escape_coding, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, unsigned padding, char *requested_seek_points, int num_requested_seek_points, encoder_wrapper_struct *encoder_wrapper)
662 {
663         unsigned i;
664
665         if(channels != 2)
666                 do_mid_side = loose_mid_side = false;
667
668         if(encoder_wrapper->verify) {
669                 /* set up the fifo which will hold the original signal to compare against */
670                 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
671                 for(i = 0; i < channels; i++) {
672                         if(0 == (encoder_wrapper->verify_fifo.original[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder_wrapper->verify_fifo.size))) {
673                                 fprintf(stderr, "%s: ERROR allocating verify buffers\n", encoder_wrapper->inbasefilename);
674                                 return false;
675                         }
676                 }
677                 encoder_wrapper->verify_fifo.tail = 0;
678                 encoder_wrapper->verify_fifo.into_frames = false;
679                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
680
681                 /* set up a stream decoder for verification */
682                 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_new();
683                 if(0 == encoder_wrapper->verify_fifo.decoder) {
684                         fprintf(stderr, "%s: ERROR creating the verify decoder instance\n", encoder_wrapper->inbasefilename);
685                         return false;
686                 }
687                 FLAC__stream_decoder_set_read_callback(encoder_wrapper->verify_fifo.decoder, verify_read_callback);
688                 FLAC__stream_decoder_set_write_callback(encoder_wrapper->verify_fifo.decoder, verify_write_callback);
689                 FLAC__stream_decoder_set_metadata_callback(encoder_wrapper->verify_fifo.decoder, verify_metadata_callback);
690                 FLAC__stream_decoder_set_error_callback(encoder_wrapper->verify_fifo.decoder, verify_error_callback);
691                 FLAC__stream_decoder_set_client_data(encoder_wrapper->verify_fifo.decoder, encoder_wrapper);
692                 if(FLAC__stream_decoder_init(encoder_wrapper->verify_fifo.decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
693                         fprintf(stderr, "%s: ERROR initializing decoder, state = %d:%s\n", encoder_wrapper->inbasefilename, FLAC__stream_decoder_get_state(encoder_wrapper->verify_fifo.decoder), FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(encoder_wrapper->verify_fifo.decoder)]);
694                         return false;
695                 }
696         }
697
698         if(!convert_to_seek_table(requested_seek_points, num_requested_seek_points, encoder_wrapper->total_samples_to_encode, blocksize, &encoder_wrapper->seek_table)) {
699                 fprintf(stderr, "%s: ERROR allocating seek table\n", encoder_wrapper->inbasefilename);
700                 return false;
701         }
702
703         FLAC__stream_encoder_set_streamable_subset(encoder_wrapper->encoder, !lax);
704         FLAC__stream_encoder_set_do_mid_side_stereo(encoder_wrapper->encoder, do_mid_side);
705         FLAC__stream_encoder_set_loose_mid_side_stereo(encoder_wrapper->encoder, loose_mid_side);
706         FLAC__stream_encoder_set_channels(encoder_wrapper->encoder, channels);
707         FLAC__stream_encoder_set_bits_per_sample(encoder_wrapper->encoder, bps);
708         FLAC__stream_encoder_set_sample_rate(encoder_wrapper->encoder, sample_rate);
709         FLAC__stream_encoder_set_blocksize(encoder_wrapper->encoder, blocksize);
710         FLAC__stream_encoder_set_max_lpc_order(encoder_wrapper->encoder, max_lpc_order);
711         FLAC__stream_encoder_set_qlp_coeff_precision(encoder_wrapper->encoder, qlp_coeff_precision);
712         FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder_wrapper->encoder, do_qlp_coeff_prec_search);
713         FLAC__stream_encoder_set_do_escape_coding(encoder_wrapper->encoder, do_escape_coding);
714         FLAC__stream_encoder_set_do_exhaustive_model_search(encoder_wrapper->encoder, do_exhaustive_model_search);
715         FLAC__stream_encoder_set_min_residual_partition_order(encoder_wrapper->encoder, min_residual_partition_order);
716         FLAC__stream_encoder_set_max_residual_partition_order(encoder_wrapper->encoder, max_residual_partition_order);
717         FLAC__stream_encoder_set_rice_parameter_search_dist(encoder_wrapper->encoder, rice_parameter_search_dist);
718         FLAC__stream_encoder_set_total_samples_estimate(encoder_wrapper->encoder, encoder_wrapper->total_samples_to_encode);
719         FLAC__stream_encoder_set_seek_table(encoder_wrapper->encoder, (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0);
720         FLAC__stream_encoder_set_padding(encoder_wrapper->encoder, padding);
721         FLAC__stream_encoder_set_last_metadata_is_last(encoder_wrapper->encoder, true);
722         FLAC__stream_encoder_set_write_callback(encoder_wrapper->encoder, write_callback);
723         FLAC__stream_encoder_set_metadata_callback(encoder_wrapper->encoder, metadata_callback);
724         FLAC__stream_encoder_set_client_data(encoder_wrapper->encoder, encoder_wrapper);
725
726         if(FLAC__stream_encoder_init(encoder_wrapper->encoder) != FLAC__STREAM_ENCODER_OK) {
727                 fprintf(stderr, "%s: ERROR initializing encoder, state = %d:%s\n", encoder_wrapper->inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper->encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper->encoder)]);
728                 return false;
729         }
730
731         /* the above call writes all the metadata, so we save the stream offset now */
732         encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
733
734         return true;
735 }
736
737 FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table)
738 {
739         unsigned i, j, real_points, placeholders;
740         char *pt = requested_seek_points, *q;
741         FLAC__bool first;
742
743         seek_table->num_points = 0;
744
745         if(num_requested_seek_points == 0)
746                 return true;
747
748         if(num_requested_seek_points < 0) {
749                 strcpy(requested_seek_points, "100x<");
750                 num_requested_seek_points = 1;
751         }
752
753         /* first count how many individual seek point we may need */
754         real_points = placeholders = 0;
755         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
756                 q = strchr(pt, '<');
757                 FLAC__ASSERT(0 != q);
758                 *q = '\0';
759
760                 if(0 == strcmp(pt, "X")) { /* -S X */
761                         placeholders++;
762                 }
763                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
764                         if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
765                                 real_points += (unsigned)atoi(pt);
766                 }
767                 else { /* -S # */
768                         real_points++;
769                 }
770                 *q++ = '<';
771
772                 pt = q;
773         }
774         pt = requested_seek_points;
775
776         /* make some space */
777         if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
778                 return false;
779
780         /* initialize the seek_table.  we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
781         for(i = 0; i < real_points+placeholders; i++) {
782                 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
783                 seek_table->points[i].stream_offset = 0;
784                 seek_table->points[i].frame_samples = 0;
785         }
786
787         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
788                 q = strchr(pt, '<');
789                 FLAC__ASSERT(0 != q);
790                 *q++ = '\0';
791
792                 if(0 == strcmp(pt, "X")) { /* -S X */
793                         ; /* we append placeholders later */
794                 }
795                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
796                         if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
797                                 unsigned j, n;
798                                 n = (unsigned)atoi(pt);
799                                 for(j = 0; j < n; j++)
800                                         append_point_to_seek_table(seek_table, stream_samples * (FLAC__uint64)j / (FLAC__uint64)n, stream_samples, blocksize);
801                         }
802                 }
803                 else { /* -S # */
804                         append_point_to_seek_table(seek_table, (FLAC__uint64)atoi(pt), stream_samples, blocksize);
805                 }
806
807                 pt = q;
808         }
809
810         /* sort the seekpoints */
811         qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
812
813         /* uniqify the seekpoints */
814         first = true;
815         for(i = j = 0; i < seek_table->num_points; i++) {
816                 if(!first) {
817                         if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
818                                 continue;
819                 }
820                 first = false;
821                 seek_table->points[j++] = seek_table->points[i];
822         }
823         seek_table->num_points = j;
824
825         /* append placeholders */
826         for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
827                 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
828         seek_table->num_points += placeholders;
829
830         return true;
831 }
832
833 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, FLAC__uint64 sample, FLAC__uint64 stream_samples, FLAC__uint64 blocksize)
834 {
835         const FLAC__uint64 target_sample = (sample / blocksize) * blocksize;
836
837         if(stream_samples == 0 || target_sample < stream_samples)
838                 seek_table->points[seek_table->num_points++].sample_number = target_sample;
839 }
840
841 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
842 {
843         /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
844         if(l->sample_number == r->sample_number)
845                 return 0;
846         else if(l->sample_number < r->sample_number)
847                 return -1;
848         else
849                 return 1;
850 }
851
852 void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
853 {
854         unsigned wide_sample, sample, channel, byte;
855
856         if(bps == 8) {
857                 if(is_unsigned_samples) {
858                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
859                                 for(channel = 0; channel < channels; channel++, sample++)
860                                         dest[channel][wide_sample] = (FLAC__int32)ucbuffer[sample] - 0x80;
861                 }
862                 else {
863                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
864                                 for(channel = 0; channel < channels; channel++, sample++)
865                                         dest[channel][wide_sample] = (FLAC__int32)scbuffer[sample];
866                 }
867         }
868         else if(bps == 16) {
869                 if(is_big_endian != is_big_endian_host) {
870                         unsigned char tmp;
871                         const unsigned bytes = wide_samples * channels * (bps >> 3);
872                         for(byte = 0; byte < bytes; byte += 2) {
873                                 tmp = ucbuffer[byte];
874                                 ucbuffer[byte] = ucbuffer[byte+1];
875                                 ucbuffer[byte+1] = tmp;
876                         }
877                 }
878                 if(is_unsigned_samples) {
879                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
880                                 for(channel = 0; channel < channels; channel++, sample++)
881                                         dest[channel][wide_sample] = (FLAC__int32)usbuffer[sample] - 0x8000;
882                 }
883                 else {
884                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
885                                 for(channel = 0; channel < channels; channel++, sample++)
886                                         dest[channel][wide_sample] = (FLAC__int32)ssbuffer[sample];
887                 }
888         }
889         else if(bps == 24) {
890                 if(!is_big_endian) {
891                         unsigned char tmp;
892                         const unsigned bytes = wide_samples * channels * (bps >> 3);
893                         for(byte = 0; byte < bytes; byte += 3) {
894                                 tmp = ucbuffer[byte];
895                                 ucbuffer[byte] = ucbuffer[byte+2];
896                                 ucbuffer[byte+2] = tmp;
897                         }
898                 }
899                 if(is_unsigned_samples) {
900                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
901                                 for(channel = 0; channel < channels; channel++, sample++) {
902                                         dest[channel][wide_sample]  = ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
903                                         dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
904                                         dest[channel][wide_sample] |= ucbuffer[byte++];
905                                         dest[channel][wide_sample] -= 0x800000;
906                                 }
907                 }
908                 else {
909                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
910                                 for(channel = 0; channel < channels; channel++, sample++) {
911                                         dest[channel][wide_sample]  = scbuffer[byte++]; dest[channel][wide_sample] <<= 8;
912                                         dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
913                                         dest[channel][wide_sample] |= ucbuffer[byte++];
914                                 }
915                 }
916         }
917         else {
918                 FLAC__ASSERT(0);
919         }
920
921         /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
922         append_to_verify_fifo(encoder_wrapper, dest, channels, wide_samples);
923 }
924
925 void append_to_verify_fifo(encoder_wrapper_struct *encoder_wrapper, const FLAC__int32 *src[], unsigned channels, unsigned wide_samples)
926 {
927         if(encoder_wrapper->verify) {
928                 unsigned channel;
929                 for(channel = 0; channel < channels; channel++)
930                         memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], src[channel], sizeof(FLAC__int32) * wide_samples);
931                 encoder_wrapper->verify_fifo.tail += wide_samples;
932                 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
933         }
934 }
935
936 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
937 {
938         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
939         const unsigned mask = (FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
940
941         /* mark the current seek point if hit (if stream_offset == 0 that means we're still writing metadata and haven't hit the first frame yet) */
942         if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
943                 FLAC__uint64 current_sample = (FLAC__uint64)current_frame * (FLAC__uint64)FLAC__stream_encoder_get_blocksize(encoder), test_sample;
944                 unsigned i;
945                 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
946                         test_sample = encoder_wrapper->seek_table.points[i].sample_number;
947                         if(test_sample > current_sample) {
948                                 break;
949                         }
950                         else if(test_sample == current_sample) {
951                                 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
952                                 encoder_wrapper->seek_table.points[i].frame_samples = FLAC__stream_encoder_get_blocksize(encoder);
953                                 encoder_wrapper->first_seek_point_to_check++;
954                                 break;
955                         }
956                         else {
957                                 encoder_wrapper->first_seek_point_to_check++;
958                         }
959                 }
960         }
961
962         encoder_wrapper->bytes_written += bytes;
963         encoder_wrapper->samples_written += samples;
964         encoder_wrapper->current_frame = current_frame;
965
966         if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
967                 print_stats(encoder_wrapper);
968
969         if(encoder_wrapper->verify) {
970                 encoder_wrapper->verify_fifo.encoded_signal = buffer;
971                 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
972                 if(encoder_wrapper->verify_fifo.into_frames) {
973                         if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
974                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
975                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
976                         }
977                 }
978                 else {
979                         if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
980                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
981                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
982                         }
983                 }
984         }
985
986         if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_wrapper->fout) == bytes)
987                 return FLAC__STREAM_ENCODER_WRITE_OK;
988         else
989                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
990 }
991
992 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
993 {
994         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
995         FLAC__byte b;
996         FILE *f;
997         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
998         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
999         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
1000
1001         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
1002
1003         /*
1004          * we get called by the encoder when the encoding process has
1005          * finished so that we can update the STREAMINFO and SEEKTABLE
1006          * blocks.
1007          */
1008
1009         (void)encoder; /* silence compiler warning about unused parameter */
1010
1011         if(encoder_wrapper->fout == stdout)
1012                 return;
1013
1014         fclose(encoder_wrapper->fout);
1015         if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
1016                 return;
1017
1018         /* all this is based on intimate knowledge of the stream header
1019          * layout, but a change to the header format that would break this
1020          * would also break all streams encoded in the previous format.
1021          */
1022
1023         if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
1024         fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
1025
1026 samples_:
1027         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
1028         if(fread(&b, 1, 1, f) != 1) goto framesize_;
1029         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
1030         b = (b & 0xf0) | (FLAC__byte)((samples >> 32) & 0x0F);
1031         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1032         b = (FLAC__byte)((samples >> 24) & 0xFF);
1033         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1034         b = (FLAC__byte)((samples >> 16) & 0xFF);
1035         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1036         b = (FLAC__byte)((samples >> 8) & 0xFF);
1037         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1038         b = (FLAC__byte)(samples & 0xFF);
1039         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1040
1041 framesize_:
1042         if(-1 == fseek(f, 12, SEEK_SET)) goto seektable_;
1043         b = (FLAC__byte)((min_framesize >> 16) & 0xFF);
1044         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1045         b = (FLAC__byte)((min_framesize >> 8) & 0xFF);
1046         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1047         b = (FLAC__byte)(min_framesize & 0xFF);
1048         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1049         b = (FLAC__byte)((max_framesize >> 16) & 0xFF);
1050         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1051         b = (FLAC__byte)((max_framesize >> 8) & 0xFF);
1052         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1053         b = (FLAC__byte)(max_framesize & 0xFF);
1054         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1055
1056 seektable_:
1057         if(encoder_wrapper->seek_table.num_points > 0) {
1058                 long pos;
1059                 unsigned i;
1060
1061                 /* convert any unused seek points to placeholders */
1062                 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
1063                         if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
1064                                 break;
1065                         else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
1066                                 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
1067                 }
1068
1069                 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
1070                 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1071                 pos += metadata->length;
1072                 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1073                 if(-1 == fseek(f, pos, SEEK_SET)) goto end_;
1074                 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
1075                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
1076                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
1077                         if(!write_big_endian_uint16(f, (FLAC__uint16)encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
1078                 }
1079         }
1080
1081 end_:
1082         fclose(f);
1083         return;
1084 }
1085
1086 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
1087 {
1088         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1089         const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
1090         (void)decoder;
1091
1092         if(encoded_bytes <= *bytes) {
1093                 *bytes = encoded_bytes;
1094                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1095         }
1096         else {
1097                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1098                 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
1099                 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
1100         }
1101
1102         return FLAC__STREAM_DECODER_READ_CONTINUE;
1103 }
1104
1105 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
1106 {
1107         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1108         unsigned channel, l, r;
1109         const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
1110         const unsigned bytes_per_block = sizeof(FLAC__int32) * FLAC__stream_decoder_get_blocksize(decoder);
1111
1112         for(channel = 0; channel < channels; channel++) {
1113                 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], bytes_per_block)) {
1114                         unsigned sample = 0;
1115                         int expect = 0, got = 0;
1116                         fprintf(stderr, "\n%s: ERROR: mismatch in decoded data, verify FAILED!\n", encoder_wrapper->inbasefilename);
1117                         fprintf(stderr, "       Please submit a bug report to\n");
1118                         fprintf(stderr, "           http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1119                         fprintf(stderr, "       Make sure to include an email contact in the comment and/or use the\n");
1120                         fprintf(stderr, "       \"Monitor\" feature to monitor the bug status.\n");
1121                         for(l = 0, r = FLAC__stream_decoder_get_blocksize(decoder); l < r; l++) {
1122                                 if(buffer[channel][l] != encoder_wrapper->verify_fifo.original[channel][l]) {
1123                                         sample = l;
1124                                         expect = (int)encoder_wrapper->verify_fifo.original[channel][l];
1125                                         got = (int)buffer[channel][l];
1126                                         break;
1127                                 }
1128                         }
1129                         FLAC__ASSERT(l < r);
1130                         FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1131                         fprintf(stderr, "       Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)frame->header.number.sample_number + sample, (unsigned)frame->header.number.sample_number / FLAC__stream_decoder_get_blocksize(decoder), channel, sample, expect, got); /*@@@ WATCHOUT: 4GB limit */
1132                         return FLAC__STREAM_DECODER_WRITE_ABORT;
1133                 }
1134         }
1135         /* dequeue the frame from the fifo */
1136         for(channel = 0; channel < channels; channel++) {
1137                 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
1138                         encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
1139                 }
1140         }
1141         encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
1142         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
1143 }
1144
1145 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
1146 {
1147         (void)decoder;
1148         (void)metadata;
1149         (void)client_data;
1150 }
1151
1152 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1153 {
1154         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1155         (void)decoder;
1156         fprintf(stderr, "\n%s: ERROR: verification decoder returned error %d:%s\n", encoder_wrapper->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1157 }
1158
1159 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1160 {
1161 #ifdef _MSC_VER
1162         /* with VC++ you have to spoon feed it the casting */
1163         const double progress = (double)(FLAC__int64)encoder_wrapper->samples_written / (double)(FLAC__int64)encoder_wrapper->total_samples_to_encode;
1164         const double ratio = (double)(FLAC__int64)encoder_wrapper->bytes_written / ((double)(FLAC__int64)encoder_wrapper->unencoded_size * progress);
1165 #else
1166         const double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1167         const double ratio = (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress);
1168 #endif
1169
1170         if(encoder_wrapper->samples_written == encoder_wrapper->total_samples_to_encode) {
1171                 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1172                         encoder_wrapper->inbasefilename,
1173                         encoder_wrapper->verify? (encoder_wrapper->verify_fifo.result == FLAC__VERIFY_OK? " Verify OK," : " Verify FAILED!") : "",
1174                         (unsigned)encoder_wrapper->bytes_written,
1175                         ratio
1176                 );
1177         }
1178         else {
1179                 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_wrapper->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1180         }
1181 }
1182
1183 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1184 {
1185         size_t bytes_read = fread(val, 1, 2, f);
1186
1187         if(bytes_read == 0) {
1188                 if(!eof_ok) {
1189                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1190                         return false;
1191                 }
1192                 else
1193                         return true;
1194         }
1195         else if(bytes_read < 2) {
1196                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1197                 return false;
1198         }
1199         else {
1200                 if(is_big_endian_host) {
1201                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1202                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1203                 }
1204                 return true;
1205         }
1206 }
1207
1208 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1209 {
1210         size_t bytes_read = fread(val, 1, 4, f);
1211
1212         if(bytes_read == 0) {
1213                 if(!eof_ok) {
1214                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1215                         return false;
1216                 }
1217                 else
1218                         return true;
1219         }
1220         else if(bytes_read < 4) {
1221                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1222                 return false;
1223         }
1224         else {
1225                 if(is_big_endian_host) {
1226                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1227                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1228                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1229                 }
1230                 return true;
1231         }
1232 }
1233
1234 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
1235 {
1236         if(!is_big_endian_host) {
1237                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1238                 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1239         }
1240         return fwrite(&val, 1, 2, f) == 2;
1241 }
1242
1243 FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val)
1244 {
1245         if(!is_big_endian_host) {
1246                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1247                 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1248                 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1249                 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1250                 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1251         }
1252         return fwrite(&val, 1, 8, f) == 8;
1253 }