update to match new way of passing metadata to stream encoder
[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 *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 = 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                                         /* 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: */
315                                         append_to_verify_fifo(&encoder_wrapper, options.align_reservoir, channels, *options.align_reservoir_samples);
316
317                                         /* 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: */
318                                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, options.align_reservoir, *options.align_reservoir_samples)) {
319                                                 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)]);
320                                                 goto wav_abort_;
321                                         }
322                                 }
323
324                                 /*
325                                  * decrement the data_bytes counter if we need to align the file
326                                  */
327                                 if(options.sector_align) {
328                                         if(options.is_last_file) {
329                                                 *options.align_reservoir_samples = 0;
330                                         }
331                                         else {
332                                                 *options.align_reservoir_samples = align_remainder;
333                                                 data_bytes -= (*options.align_reservoir_samples) * bytes_per_wide_sample;
334                                         }
335                                 }
336
337                                 /*
338                                  * now do from the file
339                                  */
340                                 while(data_bytes > 0) {
341                                         bytes_read = fread(ucbuffer, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
342                                         if(bytes_read == 0) {
343                                                 if(ferror(infile)) {
344                                                         fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
345                                                         goto wav_abort_;
346                                                 }
347                                                 else if(feof(infile)) {
348                                                         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);
349                                                         data_bytes = 0;
350                                                 }
351                                         }
352                                         else {
353                                                 if(bytes_read % bytes_per_wide_sample != 0) {
354                                                         fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
355                                                         goto wav_abort_;
356                                                 }
357                                                 else {
358                                                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
359                                                         format_input(input, wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
360
361                                                         /* 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: */
362                                                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
363                                                                 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)]);
364                                                                 goto wav_abort_;
365                                                         }
366                                                         data_bytes -= bytes_read;
367                                                 }
368                                         }
369                                 }
370
371                                 /*
372                                  * now read unaligned samples into reservoir or pad with zeroes if necessary
373                                  */
374                                 if(options.sector_align) {
375                                         if(options.is_last_file) {
376                                                 unsigned wide_samples = 588 - align_remainder;
377                                                 if(wide_samples < 588) {
378                                                         unsigned channel;
379
380                                                         info_align_zero = wide_samples;
381                                                         data_bytes = wide_samples * bytes_per_wide_sample;
382                                                         for(channel = 0; channel < channels; channel++)
383                                                                 memset(input[channel], 0, data_bytes);
384                                                         /* 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: */
385                                                         append_to_verify_fifo(&encoder_wrapper, input, channels, wide_samples);
386
387                                                         /* 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: */
388                                                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
389                                                                 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)]);
390                                                                 goto wav_abort_;
391                                                         }
392                                                 }
393                                         }
394                                         else {
395                                                 if(*options.align_reservoir_samples > 0) {
396                                                         FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
397                                                         bytes_read = fread(ucbuffer, sizeof(unsigned char), (*options.align_reservoir_samples) * bytes_per_wide_sample, infile);
398                                                         if(bytes_read == 0 && ferror(infile)) {
399                                                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
400                                                                 goto wav_abort_;
401                                                         }
402                                                         else if(bytes_read != (*options.align_reservoir_samples) * bytes_per_wide_sample) {
403                                                                 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);
404                                                                 data_bytes = 0;
405                                                         }
406                                                         else {
407                                                                 info_align_carry = *options.align_reservoir_samples;
408                                                                 format_input(options.align_reservoir, *options.align_reservoir_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
409                                                         }
410                                                 }
411                                         }
412                                 }
413
414                                 got_data_chunk = true;
415                         }
416                 }
417                 else {
418                         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));
419                         /* sub-chunk size */
420                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
421                                 goto wav_abort_;
422                         if(fseek(infile, xx, SEEK_CUR) < 0) {
423                                 /* can't seek input, read ahead manually... */
424                                 unsigned left, need;
425                                 const unsigned chunk = sizeof(ucbuffer);
426                                 for(left = xx; left > 0; ) {
427                                         need = min(left, chunk);
428                                         if(fread(ucbuffer, 1, need, infile) < need) {
429                                                 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_wrapper.inbasefilename);
430                                                 goto wav_abort_;
431                                         }
432                                         left -= need;
433                                 }
434                         }
435                 }
436         }
437
438         if(encoder_wrapper.encoder) {
439                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
440                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
441 #ifdef FLAC__HAS_OGG
442                 if(encoder_wrapper.use_ogg)
443                         ogg_stream_clear(&encoder_wrapper.ogg.os);
444 #endif
445         }
446         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
447                 print_stats(&encoder_wrapper);
448                 fprintf(stderr, "\n");
449         }
450         if(0 != encoder_wrapper.seek_table.points)
451                 free(encoder_wrapper.seek_table.points);
452         if(options.common.verify) {
453                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
454                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
455                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
456                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
457                         return 1;
458                 }
459         }
460         if(info_align_carry >= 0)
461                 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
462         if(info_align_zero >= 0)
463                 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
464         if(infile != stdin)
465                 fclose(infile);
466         return 0;
467 wav_abort_:
468         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
469                 fprintf(stderr, "\n");
470         if(encoder_wrapper.encoder) {
471                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
472                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
473 #ifdef FLAC__HAS_OGG
474                 if(encoder_wrapper.use_ogg)
475                         ogg_stream_clear(&encoder_wrapper.ogg.os);
476 #endif
477         }
478         if(0 != encoder_wrapper.seek_table.points)
479                 free(encoder_wrapper.seek_table.points);
480         if(options.common.verify) {
481                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
482                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
483                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
484                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
485                         return 1;
486                 }
487         }
488         if(infile != stdin)
489                 fclose(infile);
490         unlink(outfilename);
491         return 1;
492 }
493
494 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)
495 {
496         encoder_wrapper_struct encoder_wrapper;
497         size_t bytes_read;
498         const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
499
500         encoder_wrapper.encoder = 0;
501         encoder_wrapper.verify = options.common.verify;
502         encoder_wrapper.verbose = options.common.verbose;
503         encoder_wrapper.bytes_written = 0;
504         encoder_wrapper.samples_written = 0;
505         encoder_wrapper.stream_offset = 0;
506         encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
507         encoder_wrapper.outfilename = outfilename;
508         encoder_wrapper.seek_table.points = 0;
509         encoder_wrapper.first_seek_point_to_check = 0;
510 #ifdef FLAC__HAS_OGG
511         encoder_wrapper.use_ogg = options.common.use_ogg;
512 #endif
513
514         if(0 == strcmp(outfilename, "-")) {
515                 encoder_wrapper.fout = file__get_binary_stdout();
516         }
517         else {
518                 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
519                         fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
520                         if(infile != stdin)
521                                 fclose(infile);
522                         return 1;
523                 }
524         }
525
526         if(!init(&encoder_wrapper))
527                 goto raw_abort_;
528
529         /* get the file length */
530         if(infilesize < 0) {
531                 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
532         }
533         else {
534                 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - options.common.skip;
535                 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample;
536         }
537
538         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
539                 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
540
541         if(options.common.skip > 0) {
542                 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)options.common.skip;
543                 if(skip_bytes > lookahead_length) {
544                         skip_bytes -= lookahead_length;
545                         lookahead_length = 0;
546                         if(fseek(infile, (long)skip_bytes, SEEK_CUR) < 0) {
547                                 /* can't seek input, read ahead manually... */
548                                 unsigned left, need;
549                                 const unsigned chunk = sizeof(ucbuffer);
550                                 for(left = skip_bytes; left > 0; ) {
551                                         need = min(left, chunk);
552                                         if(fread(ucbuffer, 1, need, infile) < need) {
553                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
554                                                 goto raw_abort_;
555                                         }
556                                         left -= need;
557                                 }
558                         }
559                 }
560                 else {
561                         lookahead += skip_bytes;
562                         lookahead_length -= skip_bytes;
563                 }
564         }
565
566         if(!init_encoder(options.common, options.channels, options.bps, options.sample_rate, &encoder_wrapper))
567                 goto raw_abort_;
568
569         encoder_wrapper.verify_fifo.into_frames = true;
570
571         while(!feof(infile)) {
572                 if(lookahead_length > 0) {
573                         FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
574                         memcpy(ucbuffer, lookahead, lookahead_length);
575                         bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
576                         if(ferror(infile)) {
577                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
578                                 goto raw_abort_;
579                         }
580                         lookahead_length = 0;
581                 }
582                 else
583                         bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
584
585                 if(bytes_read == 0) {
586                         if(ferror(infile)) {
587                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
588                                 goto raw_abort_;
589                         }
590                 }
591                 else if(bytes_read % bytes_per_wide_sample != 0) {
592                         fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
593                         goto raw_abort_;
594                 }
595                 else {
596                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
597                         format_input(input, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, &encoder_wrapper);
598
599                         /* 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: */
600                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
601                                 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)]);
602                                 goto raw_abort_;
603                         }
604                 }
605         }
606
607         if(encoder_wrapper.encoder) {
608                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
609                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
610 #ifdef FLAC__HAS_OGG
611                 if(encoder_wrapper.use_ogg)
612                         ogg_stream_clear(&encoder_wrapper.ogg.os);
613 #endif
614         }
615         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
616                 print_stats(&encoder_wrapper);
617                 fprintf(stderr, "\n");
618         }
619         if(0 != encoder_wrapper.seek_table.points)
620                 free(encoder_wrapper.seek_table.points);
621         if(options.common.verify) {
622                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
623                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
624                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
625                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
626                         return 1;
627                 }
628         }
629         if(infile != stdin)
630                 fclose(infile);
631         return 0;
632 raw_abort_:
633         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
634                 fprintf(stderr, "\n");
635         if(encoder_wrapper.encoder) {
636                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
637                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
638 #ifdef FLAC__HAS_OGG
639                 if(encoder_wrapper.use_ogg)
640                         ogg_stream_clear(&encoder_wrapper.ogg.os);
641 #endif
642         }
643         if(0 != encoder_wrapper.seek_table.points)
644                 free(encoder_wrapper.seek_table.points);
645         if(options.common.verify) {
646                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
647                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
648                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
649                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
650                         return 1;
651                 }
652         }
653         if(infile != stdin)
654                 fclose(infile);
655         unlink(outfilename);
656         return 1;
657 }
658
659 FLAC__bool init(encoder_wrapper_struct *encoder_wrapper)
660 {
661         unsigned i;
662         FLAC__uint32 test = 1;
663
664         is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
665
666         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
667                 input[i] = &(in[i][0]);
668
669         encoder_wrapper->encoder = FLAC__stream_encoder_new();
670         if(0 == encoder_wrapper->encoder) {
671                 fprintf(stderr, "%s: ERROR creating the encoder instance\n", encoder_wrapper->inbasefilename);
672                 return false;
673         }
674
675 #ifdef FLAC__HAS_OGG
676         if(encoder_wrapper->use_ogg) {
677                 if(ogg_stream_init(&encoder_wrapper->ogg.os, 0) != 0) {
678                         fprintf(stderr, "%s: ERROR initializing the Ogg stream\n", encoder_wrapper->inbasefilename);
679                         FLAC__stream_encoder_delete(encoder_wrapper->encoder);
680                         return false;
681                 }
682         }
683 #endif
684
685         return true;
686 }
687
688 FLAC__bool init_encoder(encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper)
689 {
690         unsigned i, num_metadata;
691         FLAC__StreamMetaData seek_table, padding;
692         FLAC__StreamMetaData *metadata[2];
693
694         if(channels != 2)
695                 options.do_mid_side = options.loose_mid_side = false;
696
697         if(encoder_wrapper->verify) {
698                 /* set up the fifo which will hold the original signal to compare against */
699                 encoder_wrapper->verify_fifo.size = options.blocksize + CHUNK_OF_SAMPLES;
700                 for(i = 0; i < channels; i++) {
701                         if(0 == (encoder_wrapper->verify_fifo.original[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder_wrapper->verify_fifo.size))) {
702                                 fprintf(stderr, "%s: ERROR allocating verify buffers\n", encoder_wrapper->inbasefilename);
703                                 return false;
704                         }
705                 }
706                 encoder_wrapper->verify_fifo.tail = 0;
707                 encoder_wrapper->verify_fifo.into_frames = false;
708                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
709
710                 /* set up a stream decoder for verification */
711                 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_new();
712                 if(0 == encoder_wrapper->verify_fifo.decoder) {
713                         fprintf(stderr, "%s: ERROR creating the verify decoder instance\n", encoder_wrapper->inbasefilename);
714                         return false;
715                 }
716                 FLAC__stream_decoder_set_read_callback(encoder_wrapper->verify_fifo.decoder, verify_read_callback);
717                 FLAC__stream_decoder_set_write_callback(encoder_wrapper->verify_fifo.decoder, verify_write_callback);
718                 FLAC__stream_decoder_set_metadata_callback(encoder_wrapper->verify_fifo.decoder, verify_metadata_callback);
719                 FLAC__stream_decoder_set_error_callback(encoder_wrapper->verify_fifo.decoder, verify_error_callback);
720                 FLAC__stream_decoder_set_client_data(encoder_wrapper->verify_fifo.decoder, encoder_wrapper);
721                 if(FLAC__stream_decoder_init(encoder_wrapper->verify_fifo.decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
722                         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)]);
723                         return false;
724                 }
725         }
726
727         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)) {
728                 fprintf(stderr, "%s: ERROR allocating seek table\n", encoder_wrapper->inbasefilename);
729                 return false;
730         }
731
732         num_metadata = 0;
733         if(encoder_wrapper->seek_table.num_points > 0) {
734                 seek_table.is_last = false; /* the encoder will set this for us */
735                 seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
736                 seek_table.length = encoder_wrapper->seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
737                 seek_table.data.seek_table = encoder_wrapper->seek_table;
738                 metadata[num_metadata++] = &seek_table;
739         }
740         if(options.padding > 0) {
741                 padding.is_last = false; /* the encoder will set this for us */
742                 padding.type = FLAC__METADATA_TYPE_PADDING;
743                 padding.length = (unsigned)options.padding;
744                 metadata[num_metadata++] = &padding;
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_metadata(encoder_wrapper->encoder, (num_metadata > 0)? metadata : 0, num_metadata);
764         FLAC__stream_encoder_set_write_callback(encoder_wrapper->encoder, write_callback);
765         FLAC__stream_encoder_set_metadata_callback(encoder_wrapper->encoder, metadata_callback);
766         FLAC__stream_encoder_set_client_data(encoder_wrapper->encoder, encoder_wrapper);
767
768         if(FLAC__stream_encoder_init(encoder_wrapper->encoder) != FLAC__STREAM_ENCODER_OK) {
769                 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)]);
770                 return false;
771         }
772
773         /* the above call writes all the metadata, so we save the stream offset now */
774         encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
775
776         return true;
777 }
778
779 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)
780 {
781         unsigned i, j, real_points, placeholders;
782         char *pt = requested_seek_points, *q;
783         FLAC__bool first;
784
785         seek_table->num_points = 0;
786
787         if(num_requested_seek_points == 0)
788                 return true;
789
790         if(num_requested_seek_points < 0) {
791                 strcpy(requested_seek_points, "100x<");
792                 num_requested_seek_points = 1;
793         }
794
795         /* first count how many individual seek point we may need */
796         real_points = placeholders = 0;
797         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
798                 q = strchr(pt, '<');
799                 FLAC__ASSERT(0 != q);
800                 *q = '\0';
801
802                 if(0 == strcmp(pt, "X")) { /* -S X */
803                         placeholders++;
804                 }
805                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
806                         if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
807                                 real_points += (unsigned)atoi(pt);
808                 }
809                 else { /* -S # */
810                         real_points++;
811                 }
812                 *q++ = '<';
813
814                 pt = q;
815         }
816         pt = requested_seek_points;
817
818         /* make some space */
819         if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
820                 return false;
821
822         /* initialize the seek_table.  we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
823         for(i = 0; i < real_points+placeholders; i++) {
824                 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
825                 seek_table->points[i].stream_offset = 0;
826                 seek_table->points[i].frame_samples = 0;
827         }
828
829         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
830                 q = strchr(pt, '<');
831                 FLAC__ASSERT(0 != q);
832                 *q++ = '\0';
833
834                 if(0 == strcmp(pt, "X")) { /* -S X */
835                         ; /* we append placeholders later */
836                 }
837                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
838                         if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
839                                 unsigned j, n;
840                                 n = (unsigned)atoi(pt);
841                                 for(j = 0; j < n; j++)
842                                         append_point_to_seek_table(seek_table, stream_samples * (FLAC__uint64)j / (FLAC__uint64)n, stream_samples, blocksize);
843                         }
844                 }
845                 else { /* -S # */
846                         append_point_to_seek_table(seek_table, (FLAC__uint64)atoi(pt), stream_samples, blocksize);
847                 }
848
849                 pt = q;
850         }
851
852         /* sort the seekpoints */
853         qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
854
855         /* uniqify the seekpoints */
856         first = true;
857         for(i = j = 0; i < seek_table->num_points; i++) {
858                 if(!first) {
859                         if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
860                                 continue;
861                 }
862                 first = false;
863                 seek_table->points[j++] = seek_table->points[i];
864         }
865         seek_table->num_points = j;
866
867         /* append placeholders */
868         for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
869                 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
870         seek_table->num_points += placeholders;
871
872         return true;
873 }
874
875 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, FLAC__uint64 sample, FLAC__uint64 stream_samples, FLAC__uint64 blocksize)
876 {
877         const FLAC__uint64 target_sample = (sample / blocksize) * blocksize;
878
879         if(stream_samples == 0 || target_sample < stream_samples)
880                 seek_table->points[seek_table->num_points++].sample_number = target_sample;
881 }
882
883 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
884 {
885         /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
886         if(l->sample_number == r->sample_number)
887                 return 0;
888         else if(l->sample_number < r->sample_number)
889                 return -1;
890         else
891                 return 1;
892 }
893
894 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)
895 {
896         unsigned wide_sample, sample, channel, byte;
897
898         if(bps == 8) {
899                 if(is_unsigned_samples) {
900                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
901                                 for(channel = 0; channel < channels; channel++, sample++)
902                                         dest[channel][wide_sample] = (FLAC__int32)ucbuffer[sample] - 0x80;
903                 }
904                 else {
905                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
906                                 for(channel = 0; channel < channels; channel++, sample++)
907                                         dest[channel][wide_sample] = (FLAC__int32)scbuffer[sample];
908                 }
909         }
910         else if(bps == 16) {
911                 if(is_big_endian != is_big_endian_host) {
912                         unsigned char tmp;
913                         const unsigned bytes = wide_samples * channels * (bps >> 3);
914                         for(byte = 0; byte < bytes; byte += 2) {
915                                 tmp = ucbuffer[byte];
916                                 ucbuffer[byte] = ucbuffer[byte+1];
917                                 ucbuffer[byte+1] = tmp;
918                         }
919                 }
920                 if(is_unsigned_samples) {
921                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
922                                 for(channel = 0; channel < channels; channel++, sample++)
923                                         dest[channel][wide_sample] = (FLAC__int32)usbuffer[sample] - 0x8000;
924                 }
925                 else {
926                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
927                                 for(channel = 0; channel < channels; channel++, sample++)
928                                         dest[channel][wide_sample] = (FLAC__int32)ssbuffer[sample];
929                 }
930         }
931         else if(bps == 24) {
932                 if(!is_big_endian) {
933                         unsigned char tmp;
934                         const unsigned bytes = wide_samples * channels * (bps >> 3);
935                         for(byte = 0; byte < bytes; byte += 3) {
936                                 tmp = ucbuffer[byte];
937                                 ucbuffer[byte] = ucbuffer[byte+2];
938                                 ucbuffer[byte+2] = tmp;
939                         }
940                 }
941                 if(is_unsigned_samples) {
942                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
943                                 for(channel = 0; channel < channels; channel++, sample++) {
944                                         dest[channel][wide_sample]  = ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
945                                         dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
946                                         dest[channel][wide_sample] |= ucbuffer[byte++];
947                                         dest[channel][wide_sample] -= 0x800000;
948                                 }
949                 }
950                 else {
951                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
952                                 for(channel = 0; channel < channels; channel++, sample++) {
953                                         dest[channel][wide_sample]  = scbuffer[byte++]; dest[channel][wide_sample] <<= 8;
954                                         dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
955                                         dest[channel][wide_sample] |= ucbuffer[byte++];
956                                 }
957                 }
958         }
959         else {
960                 FLAC__ASSERT(0);
961         }
962
963         /* 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: */
964         append_to_verify_fifo(encoder_wrapper, dest, channels, wide_samples);
965 }
966
967 void append_to_verify_fifo(encoder_wrapper_struct *encoder_wrapper, const FLAC__int32 *src[], unsigned channels, unsigned wide_samples)
968 {
969         if(encoder_wrapper->verify) {
970                 unsigned channel;
971                 for(channel = 0; channel < channels; channel++)
972                         memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], src[channel], sizeof(FLAC__int32) * wide_samples);
973                 encoder_wrapper->verify_fifo.tail += wide_samples;
974                 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
975         }
976 }
977
978 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
979 {
980         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
981         const unsigned mask = (FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
982
983         /* 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) */
984         if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
985                 FLAC__uint64 current_sample = (FLAC__uint64)current_frame * (FLAC__uint64)FLAC__stream_encoder_get_blocksize(encoder), test_sample;
986                 unsigned i;
987                 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
988                         test_sample = encoder_wrapper->seek_table.points[i].sample_number;
989                         if(test_sample > current_sample) {
990                                 break;
991                         }
992                         else if(test_sample == current_sample) {
993                                 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
994                                 encoder_wrapper->seek_table.points[i].frame_samples = FLAC__stream_encoder_get_blocksize(encoder);
995                                 encoder_wrapper->first_seek_point_to_check++;
996                                 break;
997                         }
998                         else {
999                                 encoder_wrapper->first_seek_point_to_check++;
1000                         }
1001                 }
1002         }
1003
1004         encoder_wrapper->bytes_written += bytes;
1005         encoder_wrapper->samples_written += samples;
1006         encoder_wrapper->current_frame = current_frame;
1007
1008         if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
1009                 print_stats(encoder_wrapper);
1010
1011         if(encoder_wrapper->verify) {
1012                 encoder_wrapper->verify_fifo.encoded_signal = buffer;
1013                 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
1014                 if(encoder_wrapper->verify_fifo.into_frames) {
1015                         if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
1016                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
1017                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
1018                         }
1019                 }
1020                 else {
1021                         if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
1022                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
1023                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
1024                         }
1025                 }
1026         }
1027
1028 #ifdef FLAC__HAS_OGG
1029         if(encoder_wrapper->use_ogg) {
1030                 ogg_packet op;
1031
1032                 memset(&op, 0, sizeof(op));
1033                 op.packet = (unsigned char *)buffer;
1034                 op.granulepos = encoder_wrapper->samples_written - 1;
1035                 /*@@@ WATCHOUT:
1036                  * this depends on the behavior of libFLAC that we will get one
1037                  * write_callback first with all the metadata (and 'samples'
1038                  * will be 0), then one write_callback for each frame.
1039                  */
1040                 op.packetno = (samples == 0? -1 : (int)encoder_wrapper->current_frame);
1041                 op.bytes = bytes;
1042
1043                 if (encoder_wrapper->bytes_written == bytes)
1044                         op.b_o_s = 1;
1045
1046                 if (encoder_wrapper->total_samples_to_encode == encoder_wrapper->samples_written)
1047                         op.e_o_s = 1;
1048
1049                 ogg_stream_packetin(&encoder_wrapper->ogg.os, &op);
1050
1051                 while(ogg_stream_pageout(&encoder_wrapper->ogg.os, &encoder_wrapper->ogg.og) != 0) {
1052                         int written;
1053                         written = fwrite(encoder_wrapper->ogg.og.header, 1, encoder_wrapper->ogg.og.header_len, encoder_wrapper->fout);
1054                         if (written != encoder_wrapper->ogg.og.header_len)
1055                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
1056
1057                         written = fwrite(encoder_wrapper->ogg.og.body, 1, encoder_wrapper->ogg.og.body_len, encoder_wrapper->fout);
1058                         if (written != encoder_wrapper->ogg.og.body_len)
1059                                 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
1060                 }
1061
1062                 return FLAC__STREAM_ENCODER_WRITE_OK;
1063         }
1064         else
1065 #endif
1066         {
1067                 if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_wrapper->fout) == bytes)
1068                         return FLAC__STREAM_ENCODER_WRITE_OK;
1069                 else
1070                         return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
1071         }
1072 }
1073
1074 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
1075 {
1076         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1077         FLAC__byte b;
1078         FILE *f = encoder_wrapper->fout;
1079         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
1080         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
1081         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
1082
1083         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
1084
1085         /*
1086          * If we are writing to an ogg stream, there is no need to go back
1087          * and update the STREAMINFO or SEEKTABLE blocks; the values we would
1088          * update are not necessary with Ogg as the transport.  We can't do
1089          * it reliably anyway without knowing the Ogg structure.
1090          */
1091 #ifdef FLAC__HAS_OGG
1092         if(encoder_wrapper->use_ogg)
1093                 return;
1094 #endif
1095
1096         /*
1097          * we get called by the encoder when the encoding process has
1098          * finished so that we can update the STREAMINFO and SEEKTABLE
1099          * blocks.
1100          */
1101
1102         (void)encoder; /* silence compiler warning about unused parameter */
1103
1104         if(f != stdout) {
1105                 fclose(encoder_wrapper->fout);
1106                 if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
1107                         return;
1108         }
1109
1110         /* all this is based on intimate knowledge of the stream header
1111          * layout, but a change to the header format that would break this
1112          * would also break all streams encoded in the previous format.
1113          */
1114
1115         if(-1 == fseek(f, 26, SEEK_SET)) goto end_;
1116         fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
1117
1118 samples_:
1119         /* if we get this far we know we can seek so no need to check the
1120          * return value from fseek()
1121          */
1122         fseek(f, 21, SEEK_SET);
1123         if(fread(&b, 1, 1, f) != 1) goto framesize_;
1124         fseek(f, 21, SEEK_SET);
1125         b = (b & 0xf0) | (FLAC__byte)((samples >> 32) & 0x0F);
1126         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1127         b = (FLAC__byte)((samples >> 24) & 0xFF);
1128         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1129         b = (FLAC__byte)((samples >> 16) & 0xFF);
1130         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1131         b = (FLAC__byte)((samples >> 8) & 0xFF);
1132         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1133         b = (FLAC__byte)(samples & 0xFF);
1134         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1135
1136 framesize_:
1137         fseek(f, 12, SEEK_SET);
1138         b = (FLAC__byte)((min_framesize >> 16) & 0xFF);
1139         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1140         b = (FLAC__byte)((min_framesize >> 8) & 0xFF);
1141         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1142         b = (FLAC__byte)(min_framesize & 0xFF);
1143         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1144         b = (FLAC__byte)((max_framesize >> 16) & 0xFF);
1145         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1146         b = (FLAC__byte)((max_framesize >> 8) & 0xFF);
1147         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1148         b = (FLAC__byte)(max_framesize & 0xFF);
1149         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1150
1151 seektable_:
1152         if(encoder_wrapper->seek_table.num_points > 0) {
1153                 long pos;
1154                 unsigned i;
1155
1156                 /* convert any unused seek points to placeholders */
1157                 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
1158                         if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
1159                                 break;
1160                         else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
1161                                 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
1162                 }
1163
1164                 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
1165                 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1166                 pos += metadata->length;
1167                 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1168                 fseek(f, pos, SEEK_SET);
1169                 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
1170                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
1171                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
1172                         if(!write_big_endian_uint16(f, (FLAC__uint16)encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
1173                 }
1174         }
1175
1176 end_:
1177         fclose(f);
1178         return;
1179 }
1180
1181 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
1182 {
1183         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1184         const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
1185         (void)decoder;
1186
1187         if(encoded_bytes <= *bytes) {
1188                 *bytes = encoded_bytes;
1189                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1190         }
1191         else {
1192                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1193                 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
1194                 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
1195         }
1196
1197         return FLAC__STREAM_DECODER_READ_CONTINUE;
1198 }
1199
1200 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
1201 {
1202         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1203         unsigned channel, l, r;
1204         const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
1205         const unsigned bytes_per_block = sizeof(FLAC__int32) * FLAC__stream_decoder_get_blocksize(decoder);
1206
1207         for(channel = 0; channel < channels; channel++) {
1208                 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], bytes_per_block)) {
1209                         unsigned sample = 0;
1210                         int expect = 0, got = 0;
1211                         fprintf(stderr, "\n%s: ERROR: mismatch in decoded data, verify FAILED!\n", encoder_wrapper->inbasefilename);
1212                         fprintf(stderr, "       Please submit a bug report to\n");
1213                         fprintf(stderr, "           http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1214                         fprintf(stderr, "       Make sure to include an email contact in the comment and/or use the\n");
1215                         fprintf(stderr, "       \"Monitor\" feature to monitor the bug status.\n");
1216                         for(l = 0, r = FLAC__stream_decoder_get_blocksize(decoder); l < r; l++) {
1217                                 if(buffer[channel][l] != encoder_wrapper->verify_fifo.original[channel][l]) {
1218                                         sample = l;
1219                                         expect = (int)encoder_wrapper->verify_fifo.original[channel][l];
1220                                         got = (int)buffer[channel][l];
1221                                         break;
1222                                 }
1223                         }
1224                         FLAC__ASSERT(l < r);
1225                         FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1226                         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 */
1227                         return FLAC__STREAM_DECODER_WRITE_ABORT;
1228                 }
1229         }
1230         /* dequeue the frame from the fifo */
1231         for(channel = 0; channel < channels; channel++) {
1232                 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
1233                         encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
1234                 }
1235         }
1236         encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
1237         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
1238 }
1239
1240 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
1241 {
1242         (void)decoder;
1243         (void)metadata;
1244         (void)client_data;
1245 }
1246
1247 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1248 {
1249         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1250         (void)decoder;
1251         fprintf(stderr, "\n%s: ERROR: verification decoder returned error %d:%s\n", encoder_wrapper->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1252 }
1253
1254 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1255 {
1256 #if defined _MSC_VER || defined __MINGW32__
1257         /* with VC++ you have to spoon feed it the casting */
1258         const double progress = (double)(FLAC__int64)encoder_wrapper->samples_written / (double)(FLAC__int64)encoder_wrapper->total_samples_to_encode;
1259         const double ratio = (double)(FLAC__int64)encoder_wrapper->bytes_written / ((double)(FLAC__int64)encoder_wrapper->unencoded_size * progress);
1260 #else
1261         const double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1262         const double ratio = (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress);
1263 #endif
1264
1265         if(encoder_wrapper->samples_written == encoder_wrapper->total_samples_to_encode) {
1266                 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1267                         encoder_wrapper->inbasefilename,
1268                         encoder_wrapper->verify? (encoder_wrapper->verify_fifo.result == FLAC__VERIFY_OK? " Verify OK," : " Verify FAILED!") : "",
1269                         (unsigned)encoder_wrapper->bytes_written,
1270                         ratio
1271                 );
1272         }
1273         else {
1274                 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_wrapper->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1275         }
1276 }
1277
1278 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1279 {
1280         size_t bytes_read = fread(val, 1, 2, f);
1281
1282         if(bytes_read == 0) {
1283                 if(!eof_ok) {
1284                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1285                         return false;
1286                 }
1287                 else
1288                         return true;
1289         }
1290         else if(bytes_read < 2) {
1291                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1292                 return false;
1293         }
1294         else {
1295                 if(is_big_endian_host) {
1296                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1297                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1298                 }
1299                 return true;
1300         }
1301 }
1302
1303 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1304 {
1305         size_t bytes_read = fread(val, 1, 4, f);
1306
1307         if(bytes_read == 0) {
1308                 if(!eof_ok) {
1309                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1310                         return false;
1311                 }
1312                 else
1313                         return true;
1314         }
1315         else if(bytes_read < 4) {
1316                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1317                 return false;
1318         }
1319         else {
1320                 if(is_big_endian_host) {
1321                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1322                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1323                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1324                 }
1325                 return true;
1326         }
1327 }
1328
1329 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
1330 {
1331         if(!is_big_endian_host) {
1332                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1333                 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1334         }
1335         return fwrite(&val, 1, 2, f) == 2;
1336 }
1337
1338 FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val)
1339 {
1340         if(!is_big_endian_host) {
1341                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1342                 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1343                 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1344                 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1345                 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1346         }
1347         return fwrite(&val, 1, 8, f) == 8;
1348 }