fix bug when skipping data
[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_SET)) {
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         else {
555                 fseek(infile, 0, SEEK_SET);
556         }
557
558         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))
559                 goto raw_abort_;
560
561         encoder_wrapper.verify_fifo.into_frames = true;
562
563         while(!feof(infile)) {
564                 if(lookahead_length > 0) {
565                         FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
566                         memcpy(ucbuffer, lookahead, lookahead_length);
567                         bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
568                         if(ferror(infile)) {
569                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
570                                 goto raw_abort_;
571                         }
572                         lookahead_length = 0;
573                 }
574                 else
575                         bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
576
577                 if(bytes_read == 0) {
578                         if(ferror(infile)) {
579                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
580                                 goto raw_abort_;
581                         }
582                 }
583                 else if(bytes_read % bytes_per_wide_sample != 0) {
584                         fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
585                         goto raw_abort_;
586                 }
587                 else {
588                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
589                         format_input(input, wide_samples, is_big_endian, is_unsigned_samples, channels, bps, &encoder_wrapper);
590
591                         /* 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: */
592                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
593                                 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)]);
594                                 goto raw_abort_;
595                         }
596                 }
597         }
598
599         if(encoder_wrapper.encoder) {
600                 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
601                         FLAC__stream_encoder_finish(encoder_wrapper.encoder);
602                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
603         }
604         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
605                 print_stats(&encoder_wrapper);
606                 fprintf(stderr, "\n");
607         }
608         if(0 != encoder_wrapper.seek_table.points)
609                 free(encoder_wrapper.seek_table.points);
610         if(verify) {
611                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
612                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
613                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
614                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
615                         return 1;
616                 }
617         }
618         if(infile != stdin)
619                 fclose(infile);
620         return 0;
621 raw_abort_:
622         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
623                 fprintf(stderr, "\n");
624         if(encoder_wrapper.encoder) {
625                 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
626                         FLAC__stream_encoder_finish(encoder_wrapper.encoder);
627                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
628         }
629         if(0 != encoder_wrapper.seek_table.points)
630                 free(encoder_wrapper.seek_table.points);
631         if(verify) {
632                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
633                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
634                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
635                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
636                         return 1;
637                 }
638         }
639         if(infile != stdin)
640                 fclose(infile);
641         unlink(outfilename);
642         return 1;
643 }
644
645 FLAC__bool init(encoder_wrapper_struct *encoder_wrapper)
646 {
647         unsigned i;
648         FLAC__uint32 test = 1;
649
650         is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
651
652         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
653                 input[i] = &(in[i][0]);
654
655         encoder_wrapper->encoder = FLAC__stream_encoder_new();
656         if(0 == encoder_wrapper->encoder) {
657                 fprintf(stderr, "%s: ERROR creating the encoder instance\n", encoder_wrapper->inbasefilename);
658                 return false;
659         }
660
661         return true;
662 }
663
664 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)
665 {
666         unsigned i;
667
668         if(channels != 2)
669                 do_mid_side = loose_mid_side = false;
670
671         if(encoder_wrapper->verify) {
672                 /* set up the fifo which will hold the original signal to compare against */
673                 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
674                 for(i = 0; i < channels; i++) {
675                         if(0 == (encoder_wrapper->verify_fifo.original[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder_wrapper->verify_fifo.size))) {
676                                 fprintf(stderr, "%s: ERROR allocating verify buffers\n", encoder_wrapper->inbasefilename);
677                                 return false;
678                         }
679                 }
680                 encoder_wrapper->verify_fifo.tail = 0;
681                 encoder_wrapper->verify_fifo.into_frames = false;
682                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
683
684                 /* set up a stream decoder for verification */
685                 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_new();
686                 if(0 == encoder_wrapper->verify_fifo.decoder) {
687                         fprintf(stderr, "%s: ERROR creating the verify decoder instance\n", encoder_wrapper->inbasefilename);
688                         return false;
689                 }
690                 FLAC__stream_decoder_set_read_callback(encoder_wrapper->verify_fifo.decoder, verify_read_callback);
691                 FLAC__stream_decoder_set_write_callback(encoder_wrapper->verify_fifo.decoder, verify_write_callback);
692                 FLAC__stream_decoder_set_metadata_callback(encoder_wrapper->verify_fifo.decoder, verify_metadata_callback);
693                 FLAC__stream_decoder_set_error_callback(encoder_wrapper->verify_fifo.decoder, verify_error_callback);
694                 FLAC__stream_decoder_set_client_data(encoder_wrapper->verify_fifo.decoder, encoder_wrapper);
695                 if(FLAC__stream_decoder_init(encoder_wrapper->verify_fifo.decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
696                         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)]);
697                         return false;
698                 }
699         }
700
701         if(!convert_to_seek_table(requested_seek_points, num_requested_seek_points, encoder_wrapper->total_samples_to_encode, blocksize, &encoder_wrapper->seek_table)) {
702                 fprintf(stderr, "%s: ERROR allocating seek table\n", encoder_wrapper->inbasefilename);
703                 return false;
704         }
705
706         FLAC__stream_encoder_set_streamable_subset(encoder_wrapper->encoder, !lax);
707         FLAC__stream_encoder_set_do_mid_side_stereo(encoder_wrapper->encoder, do_mid_side);
708         FLAC__stream_encoder_set_loose_mid_side_stereo(encoder_wrapper->encoder, loose_mid_side);
709         FLAC__stream_encoder_set_channels(encoder_wrapper->encoder, channels);
710         FLAC__stream_encoder_set_bits_per_sample(encoder_wrapper->encoder, bps);
711         FLAC__stream_encoder_set_sample_rate(encoder_wrapper->encoder, sample_rate);
712         FLAC__stream_encoder_set_blocksize(encoder_wrapper->encoder, blocksize);
713         FLAC__stream_encoder_set_max_lpc_order(encoder_wrapper->encoder, max_lpc_order);
714         FLAC__stream_encoder_set_qlp_coeff_precision(encoder_wrapper->encoder, qlp_coeff_precision);
715         FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder_wrapper->encoder, do_qlp_coeff_prec_search);
716         FLAC__stream_encoder_set_do_escape_coding(encoder_wrapper->encoder, do_escape_coding);
717         FLAC__stream_encoder_set_do_exhaustive_model_search(encoder_wrapper->encoder, do_exhaustive_model_search);
718         FLAC__stream_encoder_set_min_residual_partition_order(encoder_wrapper->encoder, min_residual_partition_order);
719         FLAC__stream_encoder_set_max_residual_partition_order(encoder_wrapper->encoder, max_residual_partition_order);
720         FLAC__stream_encoder_set_rice_parameter_search_dist(encoder_wrapper->encoder, rice_parameter_search_dist);
721         FLAC__stream_encoder_set_total_samples_estimate(encoder_wrapper->encoder, encoder_wrapper->total_samples_to_encode);
722         FLAC__stream_encoder_set_seek_table(encoder_wrapper->encoder, (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0);
723         FLAC__stream_encoder_set_padding(encoder_wrapper->encoder, padding);
724         FLAC__stream_encoder_set_last_metadata_is_last(encoder_wrapper->encoder, true);
725         FLAC__stream_encoder_set_write_callback(encoder_wrapper->encoder, write_callback);
726         FLAC__stream_encoder_set_metadata_callback(encoder_wrapper->encoder, metadata_callback);
727         FLAC__stream_encoder_set_client_data(encoder_wrapper->encoder, encoder_wrapper);
728
729         if(FLAC__stream_encoder_init(encoder_wrapper->encoder) != FLAC__STREAM_ENCODER_OK) {
730                 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)]);
731                 return false;
732         }
733
734         /* the above call writes all the metadata, so we save the stream offset now */
735         encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
736
737         return true;
738 }
739
740 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)
741 {
742         unsigned i, j, real_points, placeholders;
743         char *pt = requested_seek_points, *q;
744         FLAC__bool first;
745
746         seek_table->num_points = 0;
747
748         if(num_requested_seek_points == 0)
749                 return true;
750
751         if(num_requested_seek_points < 0) {
752                 strcpy(requested_seek_points, "100x<");
753                 num_requested_seek_points = 1;
754         }
755
756         /* first count how many individual seek point we may need */
757         real_points = placeholders = 0;
758         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
759                 q = strchr(pt, '<');
760                 FLAC__ASSERT(0 != q);
761                 *q = '\0';
762
763                 if(0 == strcmp(pt, "X")) { /* -S X */
764                         placeholders++;
765                 }
766                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
767                         if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
768                                 real_points += (unsigned)atoi(pt);
769                 }
770                 else { /* -S # */
771                         real_points++;
772                 }
773                 *q++ = '<';
774
775                 pt = q;
776         }
777         pt = requested_seek_points;
778
779         /* make some space */
780         if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
781                 return false;
782
783         /* initialize the seek_table.  we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
784         for(i = 0; i < real_points+placeholders; i++) {
785                 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
786                 seek_table->points[i].stream_offset = 0;
787                 seek_table->points[i].frame_samples = 0;
788         }
789
790         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
791                 q = strchr(pt, '<');
792                 FLAC__ASSERT(0 != q);
793                 *q++ = '\0';
794
795                 if(0 == strcmp(pt, "X")) { /* -S X */
796                         ; /* we append placeholders later */
797                 }
798                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
799                         if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
800                                 unsigned j, n;
801                                 n = (unsigned)atoi(pt);
802                                 for(j = 0; j < n; j++)
803                                         append_point_to_seek_table(seek_table, stream_samples * (FLAC__uint64)j / (FLAC__uint64)n, stream_samples, blocksize);
804                         }
805                 }
806                 else { /* -S # */
807                         append_point_to_seek_table(seek_table, (FLAC__uint64)atoi(pt), stream_samples, blocksize);
808                 }
809
810                 pt = q;
811         }
812
813         /* sort the seekpoints */
814         qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
815
816         /* uniqify the seekpoints */
817         first = true;
818         for(i = j = 0; i < seek_table->num_points; i++) {
819                 if(!first) {
820                         if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
821                                 continue;
822                 }
823                 first = false;
824                 seek_table->points[j++] = seek_table->points[i];
825         }
826         seek_table->num_points = j;
827
828         /* append placeholders */
829         for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
830                 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
831         seek_table->num_points += placeholders;
832
833         return true;
834 }
835
836 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, FLAC__uint64 sample, FLAC__uint64 stream_samples, FLAC__uint64 blocksize)
837 {
838         const FLAC__uint64 target_sample = (sample / blocksize) * blocksize;
839
840         if(stream_samples == 0 || target_sample < stream_samples)
841                 seek_table->points[seek_table->num_points++].sample_number = target_sample;
842 }
843
844 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
845 {
846         /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
847         if(l->sample_number == r->sample_number)
848                 return 0;
849         else if(l->sample_number < r->sample_number)
850                 return -1;
851         else
852                 return 1;
853 }
854
855 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)
856 {
857         unsigned wide_sample, sample, channel, byte;
858
859         if(bps == 8) {
860                 if(is_unsigned_samples) {
861                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
862                                 for(channel = 0; channel < channels; channel++, sample++)
863                                         dest[channel][wide_sample] = (FLAC__int32)ucbuffer[sample] - 0x80;
864                 }
865                 else {
866                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
867                                 for(channel = 0; channel < channels; channel++, sample++)
868                                         dest[channel][wide_sample] = (FLAC__int32)scbuffer[sample];
869                 }
870         }
871         else if(bps == 16) {
872                 if(is_big_endian != is_big_endian_host) {
873                         unsigned char tmp;
874                         const unsigned bytes = wide_samples * channels * (bps >> 3);
875                         for(byte = 0; byte < bytes; byte += 2) {
876                                 tmp = ucbuffer[byte];
877                                 ucbuffer[byte] = ucbuffer[byte+1];
878                                 ucbuffer[byte+1] = tmp;
879                         }
880                 }
881                 if(is_unsigned_samples) {
882                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
883                                 for(channel = 0; channel < channels; channel++, sample++)
884                                         dest[channel][wide_sample] = (FLAC__int32)usbuffer[sample] - 0x8000;
885                 }
886                 else {
887                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
888                                 for(channel = 0; channel < channels; channel++, sample++)
889                                         dest[channel][wide_sample] = (FLAC__int32)ssbuffer[sample];
890                 }
891         }
892         else if(bps == 24) {
893                 if(!is_big_endian) {
894                         unsigned char tmp;
895                         const unsigned bytes = wide_samples * channels * (bps >> 3);
896                         for(byte = 0; byte < bytes; byte += 3) {
897                                 tmp = ucbuffer[byte];
898                                 ucbuffer[byte] = ucbuffer[byte+2];
899                                 ucbuffer[byte+2] = tmp;
900                         }
901                 }
902                 if(is_unsigned_samples) {
903                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
904                                 for(channel = 0; channel < channels; channel++, sample++) {
905                                         dest[channel][wide_sample]  = ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
906                                         dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
907                                         dest[channel][wide_sample] |= ucbuffer[byte++];
908                                         dest[channel][wide_sample] -= 0x800000;
909                                 }
910                 }
911                 else {
912                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
913                                 for(channel = 0; channel < channels; channel++, sample++) {
914                                         dest[channel][wide_sample]  = scbuffer[byte++]; dest[channel][wide_sample] <<= 8;
915                                         dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
916                                         dest[channel][wide_sample] |= ucbuffer[byte++];
917                                 }
918                 }
919         }
920         else {
921                 FLAC__ASSERT(0);
922         }
923
924         /* 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: */
925         append_to_verify_fifo(encoder_wrapper, dest, channels, wide_samples);
926 }
927
928 void append_to_verify_fifo(encoder_wrapper_struct *encoder_wrapper, const FLAC__int32 *src[], unsigned channels, unsigned wide_samples)
929 {
930         if(encoder_wrapper->verify) {
931                 unsigned channel;
932                 for(channel = 0; channel < channels; channel++)
933                         memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], src[channel], sizeof(FLAC__int32) * wide_samples);
934                 encoder_wrapper->verify_fifo.tail += wide_samples;
935                 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
936         }
937 }
938
939 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
940 {
941         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
942         const unsigned mask = (FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
943
944         /* 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) */
945         if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
946                 FLAC__uint64 current_sample = (FLAC__uint64)current_frame * (FLAC__uint64)FLAC__stream_encoder_get_blocksize(encoder), test_sample;
947                 unsigned i;
948                 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
949                         test_sample = encoder_wrapper->seek_table.points[i].sample_number;
950                         if(test_sample > current_sample) {
951                                 break;
952                         }
953                         else if(test_sample == current_sample) {
954                                 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
955                                 encoder_wrapper->seek_table.points[i].frame_samples = FLAC__stream_encoder_get_blocksize(encoder);
956                                 encoder_wrapper->first_seek_point_to_check++;
957                                 break;
958                         }
959                         else {
960                                 encoder_wrapper->first_seek_point_to_check++;
961                         }
962                 }
963         }
964
965         encoder_wrapper->bytes_written += bytes;
966         encoder_wrapper->samples_written += samples;
967         encoder_wrapper->current_frame = current_frame;
968
969         if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
970                 print_stats(encoder_wrapper);
971
972         if(encoder_wrapper->verify) {
973                 encoder_wrapper->verify_fifo.encoded_signal = buffer;
974                 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
975                 if(encoder_wrapper->verify_fifo.into_frames) {
976                         if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
977                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
978                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
979                         }
980                 }
981                 else {
982                         if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
983                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
984                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
985                         }
986                 }
987         }
988
989         if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_wrapper->fout) == bytes)
990                 return FLAC__STREAM_ENCODER_WRITE_OK;
991         else
992                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
993 }
994
995 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
996 {
997         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
998         FLAC__byte b;
999         FILE *f;
1000         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
1001         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
1002         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
1003
1004         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
1005
1006         /*
1007          * we get called by the encoder when the encoding process has
1008          * finished so that we can update the STREAMINFO and SEEKTABLE
1009          * blocks.
1010          */
1011
1012         (void)encoder; /* silence compiler warning about unused parameter */
1013
1014         if(encoder_wrapper->fout == stdout)
1015                 return;
1016
1017         fclose(encoder_wrapper->fout);
1018         if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
1019                 return;
1020
1021         /* all this is based on intimate knowledge of the stream header
1022          * layout, but a change to the header format that would break this
1023          * would also break all streams encoded in the previous format.
1024          */
1025
1026         if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
1027         fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
1028
1029 samples_:
1030         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
1031         if(fread(&b, 1, 1, f) != 1) goto framesize_;
1032         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
1033         b = (b & 0xf0) | (FLAC__byte)((samples >> 32) & 0x0F);
1034         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1035         b = (FLAC__byte)((samples >> 24) & 0xFF);
1036         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1037         b = (FLAC__byte)((samples >> 16) & 0xFF);
1038         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1039         b = (FLAC__byte)((samples >> 8) & 0xFF);
1040         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1041         b = (FLAC__byte)(samples & 0xFF);
1042         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1043
1044 framesize_:
1045         if(-1 == fseek(f, 12, SEEK_SET)) goto seektable_;
1046         b = (FLAC__byte)((min_framesize >> 16) & 0xFF);
1047         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1048         b = (FLAC__byte)((min_framesize >> 8) & 0xFF);
1049         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1050         b = (FLAC__byte)(min_framesize & 0xFF);
1051         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1052         b = (FLAC__byte)((max_framesize >> 16) & 0xFF);
1053         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1054         b = (FLAC__byte)((max_framesize >> 8) & 0xFF);
1055         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1056         b = (FLAC__byte)(max_framesize & 0xFF);
1057         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1058
1059 seektable_:
1060         if(encoder_wrapper->seek_table.num_points > 0) {
1061                 long pos;
1062                 unsigned i;
1063
1064                 /* convert any unused seek points to placeholders */
1065                 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
1066                         if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
1067                                 break;
1068                         else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
1069                                 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
1070                 }
1071
1072                 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
1073                 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1074                 pos += metadata->length;
1075                 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1076                 if(-1 == fseek(f, pos, SEEK_SET)) goto end_;
1077                 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
1078                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
1079                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
1080                         if(!write_big_endian_uint16(f, (FLAC__uint16)encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
1081                 }
1082         }
1083
1084 end_:
1085         fclose(f);
1086         return;
1087 }
1088
1089 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
1090 {
1091         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1092         const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
1093         (void)decoder;
1094
1095         if(encoded_bytes <= *bytes) {
1096                 *bytes = encoded_bytes;
1097                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1098         }
1099         else {
1100                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1101                 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
1102                 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
1103         }
1104
1105         return FLAC__STREAM_DECODER_READ_CONTINUE;
1106 }
1107
1108 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
1109 {
1110         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1111         unsigned channel, l, r;
1112         const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
1113         const unsigned bytes_per_block = sizeof(FLAC__int32) * FLAC__stream_decoder_get_blocksize(decoder);
1114
1115         for(channel = 0; channel < channels; channel++) {
1116                 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], bytes_per_block)) {
1117                         unsigned sample = 0;
1118                         int expect = 0, got = 0;
1119                         fprintf(stderr, "\n%s: ERROR: mismatch in decoded data, verify FAILED!\n", encoder_wrapper->inbasefilename);
1120                         fprintf(stderr, "       Please submit a bug report to\n");
1121                         fprintf(stderr, "           http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1122                         fprintf(stderr, "       Make sure to include an email contact in the comment and/or use the\n");
1123                         fprintf(stderr, "       \"Monitor\" feature to monitor the bug status.\n");
1124                         for(l = 0, r = FLAC__stream_decoder_get_blocksize(decoder); l < r; l++) {
1125                                 if(buffer[channel][l] != encoder_wrapper->verify_fifo.original[channel][l]) {
1126                                         sample = l;
1127                                         expect = (int)encoder_wrapper->verify_fifo.original[channel][l];
1128                                         got = (int)buffer[channel][l];
1129                                         break;
1130                                 }
1131                         }
1132                         FLAC__ASSERT(l < r);
1133                         FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1134                         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 */
1135                         return FLAC__STREAM_DECODER_WRITE_ABORT;
1136                 }
1137         }
1138         /* dequeue the frame from the fifo */
1139         for(channel = 0; channel < channels; channel++) {
1140                 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
1141                         encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
1142                 }
1143         }
1144         encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
1145         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
1146 }
1147
1148 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
1149 {
1150         (void)decoder;
1151         (void)metadata;
1152         (void)client_data;
1153 }
1154
1155 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1156 {
1157         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1158         (void)decoder;
1159         fprintf(stderr, "\n%s: ERROR: verification decoder returned error %d:%s\n", encoder_wrapper->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1160 }
1161
1162 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1163 {
1164 #ifdef _MSC_VER
1165         /* with VC++ you have to spoon feed it the casting */
1166         const double progress = (double)(FLAC__int64)encoder_wrapper->samples_written / (double)(FLAC__int64)encoder_wrapper->total_samples_to_encode;
1167         const double ratio = (double)(FLAC__int64)encoder_wrapper->bytes_written / ((double)(FLAC__int64)encoder_wrapper->unencoded_size * progress);
1168 #else
1169         const double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1170         const double ratio = (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress);
1171 #endif
1172
1173         if(encoder_wrapper->samples_written == encoder_wrapper->total_samples_to_encode) {
1174                 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1175                         encoder_wrapper->inbasefilename,
1176                         encoder_wrapper->verify? (encoder_wrapper->verify_fifo.result == FLAC__VERIFY_OK? " Verify OK," : " Verify FAILED!") : "",
1177                         (unsigned)encoder_wrapper->bytes_written,
1178                         ratio
1179                 );
1180         }
1181         else {
1182                 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_wrapper->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1183         }
1184 }
1185
1186 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1187 {
1188         size_t bytes_read = fread(val, 1, 2, f);
1189
1190         if(bytes_read == 0) {
1191                 if(!eof_ok) {
1192                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1193                         return false;
1194                 }
1195                 else
1196                         return true;
1197         }
1198         else if(bytes_read < 2) {
1199                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1200                 return false;
1201         }
1202         else {
1203                 if(is_big_endian_host) {
1204                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1205                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1206                 }
1207                 return true;
1208         }
1209 }
1210
1211 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1212 {
1213         size_t bytes_read = fread(val, 1, 4, f);
1214
1215         if(bytes_read == 0) {
1216                 if(!eof_ok) {
1217                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1218                         return false;
1219                 }
1220                 else
1221                         return true;
1222         }
1223         else if(bytes_read < 4) {
1224                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1225                 return false;
1226         }
1227         else {
1228                 if(is_big_endian_host) {
1229                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1230                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1231                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1232                 }
1233                 return true;
1234         }
1235 }
1236
1237 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
1238 {
1239         if(!is_big_endian_host) {
1240                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1241                 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1242         }
1243         return fwrite(&val, 1, 2, f) == 2;
1244 }
1245
1246 FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val)
1247 {
1248         if(!is_big_endian_host) {
1249                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1250                 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1251                 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1252                 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1253                 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1254         }
1255         return fwrite(&val, 1, 8, f) == 8;
1256 }