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