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