1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002 Josh Coalson
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.
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.
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.
19 #if defined _WIN32 && !defined __CYGWIN__
20 /* where MSVC puts unlink() */
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() */
39 #define min(x,y) ((x)<(y)?(x):(y))
41 /* this MUST be >= 588 so that sector aligning can take place with one read */
42 #define CHUNK_OF_SAMPLES 2048
46 FLAC__VERIFY_FAILED_IN_FRAME,
47 FLAC__VERIFY_FAILED_IN_METADATA
50 static const char *verify_code_string[] = {
52 "FLAC__VERIFY_FAILED_IN_FRAME",
53 "FLAC__VERIFY_FAILED_IN_METADATA"
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;
65 FLAC__StreamDecoder *decoder;
76 const char *inbasefilename;
78 const char *outfilename;
79 FLAC__StreamEncoder *encoder;
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;
95 } encoder_wrapper_struct;
97 static FLAC__bool is_big_endian_host;
99 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__MAX_BITS_PER_SAMPLE+7)/8)];
100 static signed char *scbuffer = (signed char *)ucbuffer;
101 static FLAC__uint16 *usbuffer = (FLAC__uint16 *)ucbuffer;
102 static FLAC__int16 *ssbuffer = (FLAC__int16 *)ucbuffer;
104 static FLAC__int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
105 static FLAC__int32 *input[FLAC__MAX_CHANNELS];
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);
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)
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;
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;
139 FLAC__ASSERT(!options.sector_align || options.common.skip == 0);
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;
152 encoder_wrapper.use_ogg = options.common.use_ogg;
156 (void)lookahead_length;
158 if(0 == strcmp(outfilename, "-")) {
159 encoder_wrapper.fout = file__get_binary_stdout();
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);
170 if(!init(&encoder_wrapper))
174 * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
176 while(!feof(infile)) {
177 if(!read_little_endian_uint32(infile, &xx, true, encoder_wrapper.inbasefilename))
181 if(xx == 0x20746d66) { /* "fmt " */
183 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_wrapper.inbasefilename);
186 /* fmt sub-chunk size */
187 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
190 fprintf(stderr, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
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);
197 /* compression code */
198 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
201 fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
204 /* number of channels */
205 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
207 if(x == 0 || x > FLAC__MAX_CHANNELS) {
208 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
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);
217 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
219 if(xx == 0 || xx > FLAC__MAX_SAMPLE_RATE) {
220 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
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);
228 /* avg bytes per second (ignored) */
229 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
231 /* block align (ignored) */
232 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
234 /* bits per sample */
235 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
237 if(x != 8 && x != 16 && x != 24) {
238 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
242 is_unsigned_samples = (x == 8);
244 /* skip any extra data in the fmt sub-chunk */
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);
258 got_fmt_chunk = true;
261 else if(xx == 0x61746164) { /* "data" */
263 fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_wrapper.inbasefilename);
265 else if(!got_fmt_chunk) {
266 fprintf(stderr, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_wrapper.inbasefilename);
271 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
275 bytes_per_wide_sample = channels * (bps >> 3);
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... */
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);
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 */
299 encoder_wrapper.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
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;
305 if(!init_encoder(options.common, channels, bps, sample_rate, &encoder_wrapper))
308 encoder_wrapper.verify_fifo.into_frames = true;
311 * first do any samples in the reservoir
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);
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)]);
325 * decrement the data_bytes counter if we need to align the file
327 if(options.sector_align) {
328 if(options.is_last_file) {
329 *options.align_reservoir_samples = 0;
332 *options.align_reservoir_samples = align_remainder;
333 data_bytes -= (*options.align_reservoir_samples) * bytes_per_wide_sample;
338 * now do from the file
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) {
344 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
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);
353 if(bytes_read % bytes_per_wide_sample != 0) {
354 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
358 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
359 format_input(input, wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
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)]);
366 data_bytes -= bytes_read;
372 * now read unaligned samples into reservoir or pad with zeroes if necessary
374 if(options.sector_align) {
375 if(options.is_last_file) {
376 unsigned wide_samples = 588 - align_remainder;
377 if(wide_samples < 588) {
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);
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)]);
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);
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);
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);
414 got_data_chunk = true;
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));
420 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
422 if(fseek(infile, xx, SEEK_CUR) < 0) {
423 /* can't seek input, read ahead manually... */
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);
438 if(encoder_wrapper.encoder) {
439 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
440 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
441 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
443 if(encoder_wrapper.use_ogg)
444 ogg_stream_clear(&encoder_wrapper.ogg.os);
447 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
448 print_stats(&encoder_wrapper);
449 fprintf(stderr, "\n");
451 if(0 != encoder_wrapper.seek_table.points)
452 free(encoder_wrapper.seek_table.points);
453 if(options.common.verify) {
454 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
455 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
456 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
457 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
461 if(info_align_carry >= 0)
462 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
463 if(info_align_zero >= 0)
464 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
469 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
470 fprintf(stderr, "\n");
471 if(encoder_wrapper.encoder) {
472 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
473 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
474 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
476 if(encoder_wrapper.use_ogg)
477 ogg_stream_clear(&encoder_wrapper.ogg.os);
480 if(0 != encoder_wrapper.seek_table.points)
481 free(encoder_wrapper.seek_table.points);
482 if(options.common.verify) {
483 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
484 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
485 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
486 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
496 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)
498 encoder_wrapper_struct encoder_wrapper;
500 const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
502 encoder_wrapper.encoder = 0;
503 encoder_wrapper.verify = options.common.verify;
504 encoder_wrapper.verbose = options.common.verbose;
505 encoder_wrapper.bytes_written = 0;
506 encoder_wrapper.samples_written = 0;
507 encoder_wrapper.stream_offset = 0;
508 encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
509 encoder_wrapper.outfilename = outfilename;
510 encoder_wrapper.seek_table.points = 0;
511 encoder_wrapper.first_seek_point_to_check = 0;
513 encoder_wrapper.use_ogg = options.common.use_ogg;
516 if(0 == strcmp(outfilename, "-")) {
517 encoder_wrapper.fout = file__get_binary_stdout();
520 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
521 fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
528 if(!init(&encoder_wrapper))
531 /* get the file length */
533 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
536 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - options.common.skip;
537 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample;
540 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
541 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
543 if(options.common.skip > 0) {
544 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)options.common.skip;
545 if(skip_bytes > lookahead_length) {
546 skip_bytes -= lookahead_length;
547 lookahead_length = 0;
548 if(fseek(infile, (long)skip_bytes, SEEK_CUR) < 0) {
549 /* can't seek input, read ahead manually... */
551 const unsigned chunk = sizeof(ucbuffer);
552 for(left = skip_bytes; left > 0; ) {
553 need = min(left, chunk);
554 if(fread(ucbuffer, 1, need, infile) < need) {
555 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
563 lookahead += skip_bytes;
564 lookahead_length -= skip_bytes;
568 if(!init_encoder(options.common, options.channels, options.bps, options.sample_rate, &encoder_wrapper))
571 encoder_wrapper.verify_fifo.into_frames = true;
573 while(!feof(infile)) {
574 if(lookahead_length > 0) {
575 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
576 memcpy(ucbuffer, lookahead, lookahead_length);
577 bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
579 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
582 lookahead_length = 0;
585 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
587 if(bytes_read == 0) {
589 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
593 else if(bytes_read % bytes_per_wide_sample != 0) {
594 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
598 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
599 format_input(input, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, &encoder_wrapper);
601 /* 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: */
602 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
603 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)]);
609 if(encoder_wrapper.encoder) {
610 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
611 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
612 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
614 if(encoder_wrapper.use_ogg)
615 ogg_stream_clear(&encoder_wrapper.ogg.os);
618 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
619 print_stats(&encoder_wrapper);
620 fprintf(stderr, "\n");
622 if(0 != encoder_wrapper.seek_table.points)
623 free(encoder_wrapper.seek_table.points);
624 if(options.common.verify) {
625 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
626 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
627 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
628 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
636 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
637 fprintf(stderr, "\n");
638 if(encoder_wrapper.encoder) {
639 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
640 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
641 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
643 if(encoder_wrapper.use_ogg)
644 ogg_stream_clear(&encoder_wrapper.ogg.os);
647 if(0 != encoder_wrapper.seek_table.points)
648 free(encoder_wrapper.seek_table.points);
649 if(options.common.verify) {
650 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
651 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
652 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
653 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
663 FLAC__bool init(encoder_wrapper_struct *encoder_wrapper)
666 FLAC__uint32 test = 1;
668 is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
670 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
671 input[i] = &(in[i][0]);
673 encoder_wrapper->encoder = FLAC__stream_encoder_new();
674 if(0 == encoder_wrapper->encoder) {
675 fprintf(stderr, "%s: ERROR creating the encoder instance\n", encoder_wrapper->inbasefilename);
680 if(encoder_wrapper->use_ogg) {
681 if(ogg_stream_init(&encoder_wrapper->ogg.os, 0) != 0) {
682 fprintf(stderr, "%s: ERROR initializing the Ogg stream\n", encoder_wrapper->inbasefilename);
683 FLAC__stream_encoder_delete(encoder_wrapper->encoder);
692 FLAC__bool init_encoder(encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper)
697 options.do_mid_side = options.loose_mid_side = false;
699 if(encoder_wrapper->verify) {
700 /* set up the fifo which will hold the original signal to compare against */
701 encoder_wrapper->verify_fifo.size = options.blocksize + CHUNK_OF_SAMPLES;
702 for(i = 0; i < channels; i++) {
703 if(0 == (encoder_wrapper->verify_fifo.original[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder_wrapper->verify_fifo.size))) {
704 fprintf(stderr, "%s: ERROR allocating verify buffers\n", encoder_wrapper->inbasefilename);
708 encoder_wrapper->verify_fifo.tail = 0;
709 encoder_wrapper->verify_fifo.into_frames = false;
710 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
712 /* set up a stream decoder for verification */
713 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_new();
714 if(0 == encoder_wrapper->verify_fifo.decoder) {
715 fprintf(stderr, "%s: ERROR creating the verify decoder instance\n", encoder_wrapper->inbasefilename);
718 FLAC__stream_decoder_set_read_callback(encoder_wrapper->verify_fifo.decoder, verify_read_callback);
719 FLAC__stream_decoder_set_write_callback(encoder_wrapper->verify_fifo.decoder, verify_write_callback);
720 FLAC__stream_decoder_set_metadata_callback(encoder_wrapper->verify_fifo.decoder, verify_metadata_callback);
721 FLAC__stream_decoder_set_error_callback(encoder_wrapper->verify_fifo.decoder, verify_error_callback);
722 FLAC__stream_decoder_set_client_data(encoder_wrapper->verify_fifo.decoder, encoder_wrapper);
723 if(FLAC__stream_decoder_init(encoder_wrapper->verify_fifo.decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
724 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)]);
729 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)) {
730 fprintf(stderr, "%s: ERROR allocating seek table\n", encoder_wrapper->inbasefilename);
734 FLAC__stream_encoder_set_streamable_subset(encoder_wrapper->encoder, !options.lax);
735 FLAC__stream_encoder_set_do_mid_side_stereo(encoder_wrapper->encoder, options.do_mid_side);
736 FLAC__stream_encoder_set_loose_mid_side_stereo(encoder_wrapper->encoder, options.loose_mid_side);
737 FLAC__stream_encoder_set_channels(encoder_wrapper->encoder, channels);
738 FLAC__stream_encoder_set_bits_per_sample(encoder_wrapper->encoder, bps);
739 FLAC__stream_encoder_set_sample_rate(encoder_wrapper->encoder, sample_rate);
740 FLAC__stream_encoder_set_blocksize(encoder_wrapper->encoder, options.blocksize);
741 FLAC__stream_encoder_set_max_lpc_order(encoder_wrapper->encoder, options.max_lpc_order);
742 FLAC__stream_encoder_set_qlp_coeff_precision(encoder_wrapper->encoder, options.qlp_coeff_precision);
743 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder_wrapper->encoder, options.do_qlp_coeff_prec_search);
744 FLAC__stream_encoder_set_do_escape_coding(encoder_wrapper->encoder, options.do_escape_coding);
745 FLAC__stream_encoder_set_do_exhaustive_model_search(encoder_wrapper->encoder, options.do_exhaustive_model_search);
746 FLAC__stream_encoder_set_min_residual_partition_order(encoder_wrapper->encoder, options.min_residual_partition_order);
747 FLAC__stream_encoder_set_max_residual_partition_order(encoder_wrapper->encoder, options.max_residual_partition_order);
748 FLAC__stream_encoder_set_rice_parameter_search_dist(encoder_wrapper->encoder, options.rice_parameter_search_dist);
749 FLAC__stream_encoder_set_total_samples_estimate(encoder_wrapper->encoder, encoder_wrapper->total_samples_to_encode);
750 FLAC__stream_encoder_set_seek_table(encoder_wrapper->encoder, (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0);
751 FLAC__stream_encoder_set_padding(encoder_wrapper->encoder, options.padding);
752 FLAC__stream_encoder_set_last_metadata_is_last(encoder_wrapper->encoder, true);
753 FLAC__stream_encoder_set_write_callback(encoder_wrapper->encoder, write_callback);
754 FLAC__stream_encoder_set_metadata_callback(encoder_wrapper->encoder, metadata_callback);
755 FLAC__stream_encoder_set_client_data(encoder_wrapper->encoder, encoder_wrapper);
757 if(FLAC__stream_encoder_init(encoder_wrapper->encoder) != FLAC__STREAM_ENCODER_OK) {
758 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)]);
762 /* the above call writes all the metadata, so we save the stream offset now */
763 encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
768 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)
770 unsigned i, j, real_points, placeholders;
771 char *pt = requested_seek_points, *q;
774 seek_table->num_points = 0;
776 if(num_requested_seek_points == 0)
779 if(num_requested_seek_points < 0) {
780 strcpy(requested_seek_points, "100x<");
781 num_requested_seek_points = 1;
784 /* first count how many individual seek point we may need */
785 real_points = placeholders = 0;
786 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
788 FLAC__ASSERT(0 != q);
791 if(0 == strcmp(pt, "X")) { /* -S X */
794 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
795 if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
796 real_points += (unsigned)atoi(pt);
805 pt = requested_seek_points;
807 /* make some space */
808 if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
811 /* initialize the seek_table. we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
812 for(i = 0; i < real_points+placeholders; i++) {
813 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
814 seek_table->points[i].stream_offset = 0;
815 seek_table->points[i].frame_samples = 0;
818 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
820 FLAC__ASSERT(0 != q);
823 if(0 == strcmp(pt, "X")) { /* -S X */
824 ; /* we append placeholders later */
826 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
827 if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
829 n = (unsigned)atoi(pt);
830 for(j = 0; j < n; j++)
831 append_point_to_seek_table(seek_table, stream_samples * (FLAC__uint64)j / (FLAC__uint64)n, stream_samples, blocksize);
835 append_point_to_seek_table(seek_table, (FLAC__uint64)atoi(pt), stream_samples, blocksize);
841 /* sort the seekpoints */
842 qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
844 /* uniqify the seekpoints */
846 for(i = j = 0; i < seek_table->num_points; i++) {
848 if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
852 seek_table->points[j++] = seek_table->points[i];
854 seek_table->num_points = j;
856 /* append placeholders */
857 for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
858 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
859 seek_table->num_points += placeholders;
864 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, FLAC__uint64 sample, FLAC__uint64 stream_samples, FLAC__uint64 blocksize)
866 const FLAC__uint64 target_sample = (sample / blocksize) * blocksize;
868 if(stream_samples == 0 || target_sample < stream_samples)
869 seek_table->points[seek_table->num_points++].sample_number = target_sample;
872 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
874 /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
875 if(l->sample_number == r->sample_number)
877 else if(l->sample_number < r->sample_number)
883 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)
885 unsigned wide_sample, sample, channel, byte;
888 if(is_unsigned_samples) {
889 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
890 for(channel = 0; channel < channels; channel++, sample++)
891 dest[channel][wide_sample] = (FLAC__int32)ucbuffer[sample] - 0x80;
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)scbuffer[sample];
900 if(is_big_endian != is_big_endian_host) {
902 const unsigned bytes = wide_samples * channels * (bps >> 3);
903 for(byte = 0; byte < bytes; byte += 2) {
904 tmp = ucbuffer[byte];
905 ucbuffer[byte] = ucbuffer[byte+1];
906 ucbuffer[byte+1] = tmp;
909 if(is_unsigned_samples) {
910 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
911 for(channel = 0; channel < channels; channel++, sample++)
912 dest[channel][wide_sample] = (FLAC__int32)usbuffer[sample] - 0x8000;
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)ssbuffer[sample];
923 const unsigned bytes = wide_samples * channels * (bps >> 3);
924 for(byte = 0; byte < bytes; byte += 3) {
925 tmp = ucbuffer[byte];
926 ucbuffer[byte] = ucbuffer[byte+2];
927 ucbuffer[byte+2] = tmp;
930 if(is_unsigned_samples) {
931 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
932 for(channel = 0; channel < channels; channel++, sample++) {
933 dest[channel][wide_sample] = ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
934 dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
935 dest[channel][wide_sample] |= ucbuffer[byte++];
936 dest[channel][wide_sample] -= 0x800000;
940 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
941 for(channel = 0; channel < channels; channel++, sample++) {
942 dest[channel][wide_sample] = scbuffer[byte++]; dest[channel][wide_sample] <<= 8;
943 dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
944 dest[channel][wide_sample] |= ucbuffer[byte++];
952 /* 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: */
953 append_to_verify_fifo(encoder_wrapper, dest, channels, wide_samples);
956 void append_to_verify_fifo(encoder_wrapper_struct *encoder_wrapper, const FLAC__int32 *src[], unsigned channels, unsigned wide_samples)
958 if(encoder_wrapper->verify) {
960 for(channel = 0; channel < channels; channel++)
961 memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], src[channel], sizeof(FLAC__int32) * wide_samples);
962 encoder_wrapper->verify_fifo.tail += wide_samples;
963 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
967 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
969 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
970 const unsigned mask = (FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
972 /* 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) */
973 if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
974 FLAC__uint64 current_sample = (FLAC__uint64)current_frame * (FLAC__uint64)FLAC__stream_encoder_get_blocksize(encoder), test_sample;
976 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
977 test_sample = encoder_wrapper->seek_table.points[i].sample_number;
978 if(test_sample > current_sample) {
981 else if(test_sample == current_sample) {
982 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
983 encoder_wrapper->seek_table.points[i].frame_samples = FLAC__stream_encoder_get_blocksize(encoder);
984 encoder_wrapper->first_seek_point_to_check++;
988 encoder_wrapper->first_seek_point_to_check++;
993 encoder_wrapper->bytes_written += bytes;
994 encoder_wrapper->samples_written += samples;
995 encoder_wrapper->current_frame = current_frame;
997 if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
998 print_stats(encoder_wrapper);
1000 if(encoder_wrapper->verify) {
1001 encoder_wrapper->verify_fifo.encoded_signal = buffer;
1002 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
1003 if(encoder_wrapper->verify_fifo.into_frames) {
1004 if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
1005 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
1006 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
1010 if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
1011 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
1012 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
1017 #ifdef FLAC__HAS_OGG
1018 if(encoder_wrapper->use_ogg) {
1021 memset(&op, 0, sizeof(op));
1022 op.packet = (unsigned char *)buffer;
1023 op.granulepos = encoder_wrapper->samples_written - 1;
1025 * this depends on the behavior of libFLAC that we will get one
1026 * write_callback first with all the metadata (and 'samples'
1027 * will be 0), then one write_callback for each frame.
1029 op.packetno = (samples == 0? -1 : (int)encoder_wrapper->current_frame);
1032 if (encoder_wrapper->bytes_written == bytes)
1035 if (encoder_wrapper->total_samples_to_encode == encoder_wrapper->samples_written)
1038 ogg_stream_packetin(&encoder_wrapper->ogg.os, &op);
1040 while(ogg_stream_pageout(&encoder_wrapper->ogg.os, &encoder_wrapper->ogg.og) != 0) {
1042 written = fwrite(encoder_wrapper->ogg.og.header, 1, encoder_wrapper->ogg.og.header_len, encoder_wrapper->fout);
1043 if (written != encoder_wrapper->ogg.og.header_len)
1044 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
1046 written = fwrite(encoder_wrapper->ogg.og.body, 1, encoder_wrapper->ogg.og.body_len, encoder_wrapper->fout);
1047 if (written != encoder_wrapper->ogg.og.body_len)
1048 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
1051 return FLAC__STREAM_ENCODER_WRITE_OK;
1056 if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_wrapper->fout) == bytes)
1057 return FLAC__STREAM_ENCODER_WRITE_OK;
1059 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
1063 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
1065 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1067 FILE *f = encoder_wrapper->fout;
1068 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
1069 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
1070 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
1072 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
1075 * If we are writing to an ogg stream, there is no need to go back
1076 * and update the STREAMINFO or SEEKTABLE blocks; the values we would
1077 * update are not necessary with Ogg as the transport. We can't do
1078 * it reliably anyway without knowing the Ogg structure.
1080 #ifdef FLAC__HAS_OGG
1081 if(encoder_wrapper->use_ogg)
1086 * we get called by the encoder when the encoding process has
1087 * finished so that we can update the STREAMINFO and SEEKTABLE
1091 (void)encoder; /* silence compiler warning about unused parameter */
1094 fclose(encoder_wrapper->fout);
1095 if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
1099 /* all this is based on intimate knowledge of the stream header
1100 * layout, but a change to the header format that would break this
1101 * would also break all streams encoded in the previous format.
1104 if(-1 == fseek(f, 26, SEEK_SET)) goto end_;
1105 fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
1108 /* if we get this far we know we can seek so no need to check the
1109 * return value from fseek()
1111 fseek(f, 21, SEEK_SET);
1112 if(fread(&b, 1, 1, f) != 1) goto framesize_;
1113 fseek(f, 21, SEEK_SET);
1114 b = (b & 0xf0) | (FLAC__byte)((samples >> 32) & 0x0F);
1115 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1116 b = (FLAC__byte)((samples >> 24) & 0xFF);
1117 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1118 b = (FLAC__byte)((samples >> 16) & 0xFF);
1119 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1120 b = (FLAC__byte)((samples >> 8) & 0xFF);
1121 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1122 b = (FLAC__byte)(samples & 0xFF);
1123 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1126 fseek(f, 12, SEEK_SET);
1127 b = (FLAC__byte)((min_framesize >> 16) & 0xFF);
1128 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1129 b = (FLAC__byte)((min_framesize >> 8) & 0xFF);
1130 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1131 b = (FLAC__byte)(min_framesize & 0xFF);
1132 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1133 b = (FLAC__byte)((max_framesize >> 16) & 0xFF);
1134 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1135 b = (FLAC__byte)((max_framesize >> 8) & 0xFF);
1136 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1137 b = (FLAC__byte)(max_framesize & 0xFF);
1138 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1141 if(encoder_wrapper->seek_table.num_points > 0) {
1145 /* convert any unused seek points to placeholders */
1146 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
1147 if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
1149 else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
1150 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
1153 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
1154 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1155 pos += metadata->length;
1156 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1157 fseek(f, pos, SEEK_SET);
1158 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
1159 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
1160 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
1161 if(!write_big_endian_uint16(f, (FLAC__uint16)encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
1170 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
1172 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1173 const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
1176 if(encoded_bytes <= *bytes) {
1177 *bytes = encoded_bytes;
1178 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1181 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1182 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
1183 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
1186 return FLAC__STREAM_DECODER_READ_CONTINUE;
1189 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
1191 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1192 unsigned channel, l, r;
1193 const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
1194 const unsigned bytes_per_block = sizeof(FLAC__int32) * FLAC__stream_decoder_get_blocksize(decoder);
1196 for(channel = 0; channel < channels; channel++) {
1197 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], bytes_per_block)) {
1198 unsigned sample = 0;
1199 int expect = 0, got = 0;
1200 fprintf(stderr, "\n%s: ERROR: mismatch in decoded data, verify FAILED!\n", encoder_wrapper->inbasefilename);
1201 fprintf(stderr, " Please submit a bug report to\n");
1202 fprintf(stderr, " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1203 fprintf(stderr, " Make sure to include an email contact in the comment and/or use the\n");
1204 fprintf(stderr, " \"Monitor\" feature to monitor the bug status.\n");
1205 for(l = 0, r = FLAC__stream_decoder_get_blocksize(decoder); l < r; l++) {
1206 if(buffer[channel][l] != encoder_wrapper->verify_fifo.original[channel][l]) {
1208 expect = (int)encoder_wrapper->verify_fifo.original[channel][l];
1209 got = (int)buffer[channel][l];
1213 FLAC__ASSERT(l < r);
1214 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1215 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 */
1216 return FLAC__STREAM_DECODER_WRITE_ABORT;
1219 /* dequeue the frame from the fifo */
1220 for(channel = 0; channel < channels; channel++) {
1221 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
1222 encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
1225 encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
1226 return FLAC__STREAM_DECODER_WRITE_CONTINUE;
1229 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
1236 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1238 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1240 fprintf(stderr, "\n%s: ERROR: verification decoder returned error %d:%s\n", encoder_wrapper->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1243 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1245 #if defined _MSC_VER || defined __MINGW32__
1246 /* with VC++ you have to spoon feed it the casting */
1247 const double progress = (double)(FLAC__int64)encoder_wrapper->samples_written / (double)(FLAC__int64)encoder_wrapper->total_samples_to_encode;
1248 const double ratio = (double)(FLAC__int64)encoder_wrapper->bytes_written / ((double)(FLAC__int64)encoder_wrapper->unencoded_size * progress);
1250 const double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1251 const double ratio = (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress);
1254 if(encoder_wrapper->samples_written == encoder_wrapper->total_samples_to_encode) {
1255 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1256 encoder_wrapper->inbasefilename,
1257 encoder_wrapper->verify? (encoder_wrapper->verify_fifo.result == FLAC__VERIFY_OK? " Verify OK," : " Verify FAILED!") : "",
1258 (unsigned)encoder_wrapper->bytes_written,
1263 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_wrapper->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1267 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1269 size_t bytes_read = fread(val, 1, 2, f);
1271 if(bytes_read == 0) {
1273 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1279 else if(bytes_read < 2) {
1280 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1284 if(is_big_endian_host) {
1285 FLAC__byte tmp, *b = (FLAC__byte*)val;
1286 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1292 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1294 size_t bytes_read = fread(val, 1, 4, f);
1296 if(bytes_read == 0) {
1298 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1304 else if(bytes_read < 4) {
1305 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1309 if(is_big_endian_host) {
1310 FLAC__byte tmp, *b = (FLAC__byte*)val;
1311 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1312 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1318 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
1320 if(!is_big_endian_host) {
1321 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1322 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1324 return fwrite(&val, 1, 2, f) == 2;
1327 FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val)
1329 if(!is_big_endian_host) {
1330 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1331 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1332 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1333 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1334 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1336 return fwrite(&val, 1, 8, f) == 8;