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