1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001 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() */
36 #define min(x,y) ((x)<(y)?(x):(y))
38 /* this MUST be >= 588 so that sector aligning can take place with one read */
39 #define CHUNK_OF_SAMPLES 2048
43 FLAC__VERIFY_FAILED_IN_FRAME,
44 FLAC__VERIFY_FAILED_IN_METADATA
47 static const char *verify_code_string[] = {
49 "FLAC__VERIFY_FAILED_IN_FRAME",
50 "FLAC__VERIFY_FAILED_IN_METADATA"
54 FLAC__int32 *original[FLAC__MAX_CHANNELS];
55 unsigned size; /* of each original[] in samples */
56 unsigned tail; /* in wide samples */
57 const FLAC__byte *encoded_signal;
58 unsigned encoded_signal_capacity;
59 unsigned encoded_bytes;
60 FLAC__bool into_frames;
62 FLAC__StreamDecoder *decoder;
66 const char *inbasefilename;
68 const char *outfilename;
69 FLAC__StreamEncoder *encoder;
72 FLAC__uint64 unencoded_size;
73 FLAC__uint64 total_samples_to_encode;
74 FLAC__uint64 bytes_written;
75 FLAC__uint64 samples_written;
76 FLAC__uint64 stream_offset; /* i.e. number of bytes before the first byte of the the first frame's header */
77 unsigned current_frame;
78 verify_fifo_struct verify_fifo;
79 FLAC__StreamMetaData_SeekTable seek_table;
80 unsigned first_seek_point_to_check;
81 } encoder_wrapper_struct;
83 static FLAC__bool is_big_endian_host;
85 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__MAX_BITS_PER_SAMPLE+7)/8)];
86 static signed char *scbuffer = (signed char *)ucbuffer;
87 static FLAC__uint16 *usbuffer = (FLAC__uint16 *)ucbuffer;
88 static FLAC__int16 *ssbuffer = (FLAC__int16 *)ucbuffer;
90 static FLAC__int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
91 static FLAC__int32 *input[FLAC__MAX_CHANNELS];
94 static FLAC__bool init(encoder_wrapper_struct *encoder_wrapper);
95 static FLAC__bool init_encoder(FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_escape_coding, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, unsigned padding, char *requested_seek_points, int num_requested_seek_points, encoder_wrapper_struct *encoder_wrapper);
96 static FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table);
97 static void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, FLAC__uint64 sample, FLAC__uint64 stream_samples, FLAC__uint64 blocksize);
98 static int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r);
99 static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
100 static void append_to_verify_fifo(encoder_wrapper_struct *encoder_wrapper, const FLAC__int32 *input[], unsigned channels, unsigned wide_samples);
101 static FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
102 static void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
103 static FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
104 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data);
105 static void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
106 static void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
107 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
108 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
109 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
110 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
111 static FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val);
113 int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, FLAC__int32 *align_reservoir[], unsigned *align_reservoir_samples, FLAC__bool sector_align, FLAC__bool is_last_file, FLAC__bool verbose, FLAC__uint64 skip, FLAC__bool verify, FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_escape_coding, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned padding, char *requested_seek_points, int num_requested_seek_points)
115 encoder_wrapper_struct encoder_wrapper;
116 FLAC__bool is_unsigned_samples = false;
117 unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
118 size_t bytes_per_wide_sample, bytes_read;
121 FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
122 unsigned align_remainder = 0;
123 int info_align_carry = -1, info_align_zero = -1;
125 FLAC__ASSERT(!sector_align || skip == 0);
127 encoder_wrapper.encoder = 0;
128 encoder_wrapper.verify = verify;
129 encoder_wrapper.verbose = verbose;
130 encoder_wrapper.bytes_written = 0;
131 encoder_wrapper.samples_written = 0;
132 encoder_wrapper.stream_offset = 0;
133 encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
134 encoder_wrapper.outfilename = outfilename;
135 encoder_wrapper.seek_table.points = 0;
136 encoder_wrapper.first_seek_point_to_check = 0;
139 (void)lookahead_length;
141 if(0 == strcmp(outfilename, "-")) {
142 encoder_wrapper.fout = stdout;
145 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
146 fprintf(stderr, "%s: ERROR: can't open output file %s\n", encoder_wrapper.inbasefilename, outfilename);
152 if(!init(&encoder_wrapper))
156 * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
158 while(!feof(infile)) {
159 if(!read_little_endian_uint32(infile, &xx, true, encoder_wrapper.inbasefilename))
163 if(xx == 0x20746d66) { /* "fmt " */
165 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_wrapper.inbasefilename);
168 /* fmt sub-chunk size */
169 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
172 fprintf(stderr, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
175 else if(xx != 16 && xx != 18) {
176 fprintf(stderr, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
179 /* compression code */
180 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
183 fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
186 /* number of channels */
187 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
189 if(x == 0 || x > FLAC__MAX_CHANNELS) {
190 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
193 else if(sector_align && x != 2) {
194 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)x);
199 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
201 if(xx == 0 || xx > FLAC__MAX_SAMPLE_RATE) {
202 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
205 else if(sector_align && xx != 44100) {
206 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)xx);
210 /* avg bytes per second (ignored) */
211 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
213 /* block align (ignored) */
214 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
216 /* bits per sample */
217 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
219 if(x != 8 && x != 16) {
220 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
224 is_unsigned_samples = (x == 8);
226 bytes_per_wide_sample = channels * (bps >> 3);
228 /* skip any extra data in the fmt sub-chunk */
232 for(left = data_bytes; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
233 need = min(left, CHUNK_OF_SAMPLES);
234 if(fread(ucbuffer, 1, bytes_per_wide_sample * need, infile) < need) {
235 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
242 got_fmt_chunk = true;
245 else if(xx == 0x61746164) { /* "data" */
247 fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_wrapper.inbasefilename);
249 else if(!got_fmt_chunk) {
250 fprintf(stderr, "%s: ERROR: got data sub-chunk before fmt sub-chunk\n", encoder_wrapper.inbasefilename);
255 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
259 bytes_per_wide_sample = channels * (bps >> 3);
262 if(infile != stdin) {
263 if(-1 == fseek(infile, bytes_per_wide_sample * (unsigned)skip, SEEK_CUR)) {
264 fprintf(stderr, "%s: ERROR during seek while skipping samples\n", encoder_wrapper.inbasefilename);
270 for(left = (unsigned)skip; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
271 need = min(left, CHUNK_OF_SAMPLES);
272 if(fread(ucbuffer, 1, bytes_per_wide_sample * need, infile) < need) {
273 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
281 data_bytes -= (unsigned)skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
282 encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample + *align_reservoir_samples;
284 align_remainder = (unsigned)(encoder_wrapper.total_samples_to_encode % 588);
286 encoder_wrapper.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
288 encoder_wrapper.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
291 /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
292 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44;
294 if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, do_escape_coding, do_qlp_coeff_prec_search, min_residual_partition_order, max_residual_partition_order, rice_parameter_search_dist, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, requested_seek_points, num_requested_seek_points, &encoder_wrapper))
297 encoder_wrapper.verify_fifo.into_frames = true;
300 * first do any samples in the reservoir
302 if(sector_align && *align_reservoir_samples > 0) {
303 /* 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: */
304 append_to_verify_fifo(&encoder_wrapper, align_reservoir, channels, *align_reservoir_samples);
306 /* 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: */
307 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, align_reservoir, *align_reservoir_samples)) {
308 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)]);
314 * decrement the data_bytes counter if we need to align the file
318 *align_reservoir_samples = 0;
321 *align_reservoir_samples = align_remainder;
322 data_bytes -= (*align_reservoir_samples) * bytes_per_wide_sample;
327 * now do from the file
329 while(data_bytes > 0) {
330 bytes_read = fread(ucbuffer, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
331 if(bytes_read == 0) {
333 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
336 else if(feof(infile)) {
337 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);
342 if(bytes_read % bytes_per_wide_sample != 0) {
343 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
347 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
348 format_input(input, wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
350 /* 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: */
351 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
352 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)]);
355 data_bytes -= bytes_read;
361 * now read unaligned samples into reservoir or pad with zeroes if necessary
365 unsigned wide_samples = 588 - align_remainder;
366 if(wide_samples < 588) {
369 info_align_zero = wide_samples;
370 data_bytes = wide_samples * bytes_per_wide_sample;
371 for(channel = 0; channel < channels; channel++)
372 memset(input[channel], 0, data_bytes);
373 /* 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: */
374 append_to_verify_fifo(&encoder_wrapper, input, channels, wide_samples);
376 /* 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: */
377 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
378 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)]);
384 if(*align_reservoir_samples > 0) {
385 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
386 bytes_read = fread(ucbuffer, sizeof(unsigned char), (*align_reservoir_samples) * bytes_per_wide_sample, infile);
387 if(bytes_read == 0 && ferror(infile)) {
388 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
391 else if(bytes_read != (*align_reservoir_samples) * bytes_per_wide_sample) {
392 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);
396 info_align_carry = *align_reservoir_samples;
397 format_input(align_reservoir, *align_reservoir_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
403 got_data_chunk = true;
407 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));
409 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
411 if(infile != stdin) {
412 if(-1 == fseek(infile, xx, SEEK_CUR)) {
413 fprintf(stderr, "%s: ERROR during seek while skipping unsupported sub-chunk\n", encoder_wrapper.inbasefilename);
419 const unsigned chunk = sizeof(ucbuffer);
420 for(left = xx; left > 0; ) {
421 need = min(left, chunk);
422 if(fread(ucbuffer, 1, need, infile) < need) {
423 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_wrapper.inbasefilename);
432 if(encoder_wrapper.encoder) {
433 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
434 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
435 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
437 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
438 print_stats(&encoder_wrapper);
439 fprintf(stderr, "\n");
441 if(0 != encoder_wrapper.seek_table.points)
442 free(encoder_wrapper.seek_table.points);
444 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
445 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
446 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
447 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
451 if(info_align_carry >= 0)
452 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
453 if(info_align_zero >= 0)
454 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
459 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
460 fprintf(stderr, "\n");
461 if(encoder_wrapper.encoder) {
462 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
463 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
464 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
466 if(0 != encoder_wrapper.seek_table.points)
467 free(encoder_wrapper.seek_table.points);
469 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
470 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
471 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
472 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
482 int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, FLAC__bool is_last_file, FLAC__bool verbose, FLAC__uint64 skip, FLAC__bool verify, FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_escape_coding, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned padding, char *requested_seek_points, int num_requested_seek_points, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned sample_rate)
484 encoder_wrapper_struct encoder_wrapper;
486 const size_t bytes_per_wide_sample = channels * (bps >> 3);
490 encoder_wrapper.encoder = 0;
491 encoder_wrapper.verify = verify;
492 encoder_wrapper.verbose = verbose;
493 encoder_wrapper.bytes_written = 0;
494 encoder_wrapper.samples_written = 0;
495 encoder_wrapper.stream_offset = 0;
496 encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
497 encoder_wrapper.outfilename = outfilename;
498 encoder_wrapper.seek_table.points = 0;
499 encoder_wrapper.first_seek_point_to_check = 0;
501 if(0 == strcmp(outfilename, "-")) {
502 encoder_wrapper.fout = stdout;
505 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
506 fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
512 if(!init(&encoder_wrapper))
515 /* get the file length */
517 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
520 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - skip;
521 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample;
524 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
525 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
528 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)skip;
529 if(skip_bytes > lookahead_length) {
530 skip_bytes -= lookahead_length;
531 lookahead_length = 0;
532 if(infile != stdin) {
533 if(-1 == fseek(infile, (long)skip_bytes, SEEK_SET)) {
534 fprintf(stderr, "%s: ERROR during seek while skipping samples\n", encoder_wrapper.inbasefilename);
540 const unsigned chunk = sizeof(ucbuffer);
541 for(left = skip_bytes; left > 0; ) {
542 need = min(left, chunk);
543 if(fread(ucbuffer, 1, need, infile) < need) {
544 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
552 lookahead += skip_bytes;
553 lookahead_length -= skip_bytes;
557 fseek(infile, 0, SEEK_SET);
560 if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, do_escape_coding, do_qlp_coeff_prec_search, min_residual_partition_order, max_residual_partition_order, rice_parameter_search_dist, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, requested_seek_points, num_requested_seek_points, &encoder_wrapper))
563 encoder_wrapper.verify_fifo.into_frames = true;
565 while(!feof(infile)) {
566 if(lookahead_length > 0) {
567 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
568 memcpy(ucbuffer, lookahead, lookahead_length);
569 bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
571 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
574 lookahead_length = 0;
577 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
579 if(bytes_read == 0) {
581 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
585 else if(bytes_read % bytes_per_wide_sample != 0) {
586 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
590 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
591 format_input(input, wide_samples, is_big_endian, is_unsigned_samples, channels, bps, &encoder_wrapper);
593 /* 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: */
594 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
595 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
601 if(encoder_wrapper.encoder) {
602 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
603 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
604 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
606 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
607 print_stats(&encoder_wrapper);
608 fprintf(stderr, "\n");
610 if(0 != encoder_wrapper.seek_table.points)
611 free(encoder_wrapper.seek_table.points);
613 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
614 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
615 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
616 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
624 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
625 fprintf(stderr, "\n");
626 if(encoder_wrapper.encoder) {
627 if(FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
628 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
629 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
631 if(0 != encoder_wrapper.seek_table.points)
632 free(encoder_wrapper.seek_table.points);
634 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
635 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
636 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
637 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
647 FLAC__bool init(encoder_wrapper_struct *encoder_wrapper)
650 FLAC__uint32 test = 1;
652 is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
654 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
655 input[i] = &(in[i][0]);
657 encoder_wrapper->encoder = FLAC__stream_encoder_new();
658 if(0 == encoder_wrapper->encoder) {
659 fprintf(stderr, "%s: ERROR creating the encoder instance\n", encoder_wrapper->inbasefilename);
666 FLAC__bool init_encoder(FLAC__bool lax, FLAC__bool do_mid_side, FLAC__bool loose_mid_side, FLAC__bool do_exhaustive_model_search, FLAC__bool do_escape_coding, FLAC__bool do_qlp_coeff_prec_search, unsigned min_residual_partition_order, unsigned max_residual_partition_order, unsigned rice_parameter_search_dist, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, unsigned padding, char *requested_seek_points, int num_requested_seek_points, encoder_wrapper_struct *encoder_wrapper)
671 do_mid_side = loose_mid_side = false;
673 if(encoder_wrapper->verify) {
674 /* set up the fifo which will hold the original signal to compare against */
675 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
676 for(i = 0; i < channels; i++) {
677 if(0 == (encoder_wrapper->verify_fifo.original[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder_wrapper->verify_fifo.size))) {
678 fprintf(stderr, "%s: ERROR allocating verify buffers\n", encoder_wrapper->inbasefilename);
682 encoder_wrapper->verify_fifo.tail = 0;
683 encoder_wrapper->verify_fifo.into_frames = false;
684 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
686 /* set up a stream decoder for verification */
687 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_new();
688 if(0 == encoder_wrapper->verify_fifo.decoder) {
689 fprintf(stderr, "%s: ERROR creating the verify decoder instance\n", encoder_wrapper->inbasefilename);
692 FLAC__stream_decoder_set_read_callback(encoder_wrapper->verify_fifo.decoder, verify_read_callback);
693 FLAC__stream_decoder_set_write_callback(encoder_wrapper->verify_fifo.decoder, verify_write_callback);
694 FLAC__stream_decoder_set_metadata_callback(encoder_wrapper->verify_fifo.decoder, verify_metadata_callback);
695 FLAC__stream_decoder_set_error_callback(encoder_wrapper->verify_fifo.decoder, verify_error_callback);
696 FLAC__stream_decoder_set_client_data(encoder_wrapper->verify_fifo.decoder, encoder_wrapper);
697 if(FLAC__stream_decoder_init(encoder_wrapper->verify_fifo.decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
698 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)]);
703 if(!convert_to_seek_table(requested_seek_points, num_requested_seek_points, encoder_wrapper->total_samples_to_encode, blocksize, &encoder_wrapper->seek_table)) {
704 fprintf(stderr, "%s: ERROR allocating seek table\n", encoder_wrapper->inbasefilename);
708 FLAC__stream_encoder_set_streamable_subset(encoder_wrapper->encoder, !lax);
709 FLAC__stream_encoder_set_do_mid_side_stereo(encoder_wrapper->encoder, do_mid_side);
710 FLAC__stream_encoder_set_loose_mid_side_stereo(encoder_wrapper->encoder, loose_mid_side);
711 FLAC__stream_encoder_set_channels(encoder_wrapper->encoder, channels);
712 FLAC__stream_encoder_set_bits_per_sample(encoder_wrapper->encoder, bps);
713 FLAC__stream_encoder_set_sample_rate(encoder_wrapper->encoder, sample_rate);
714 FLAC__stream_encoder_set_blocksize(encoder_wrapper->encoder, blocksize);
715 FLAC__stream_encoder_set_max_lpc_order(encoder_wrapper->encoder, max_lpc_order);
716 FLAC__stream_encoder_set_qlp_coeff_precision(encoder_wrapper->encoder, qlp_coeff_precision);
717 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder_wrapper->encoder, do_qlp_coeff_prec_search);
718 FLAC__stream_encoder_set_do_escape_coding(encoder_wrapper->encoder, do_escape_coding);
719 FLAC__stream_encoder_set_do_exhaustive_model_search(encoder_wrapper->encoder, do_exhaustive_model_search);
720 FLAC__stream_encoder_set_min_residual_partition_order(encoder_wrapper->encoder, min_residual_partition_order);
721 FLAC__stream_encoder_set_max_residual_partition_order(encoder_wrapper->encoder, max_residual_partition_order);
722 FLAC__stream_encoder_set_rice_parameter_search_dist(encoder_wrapper->encoder, rice_parameter_search_dist);
723 FLAC__stream_encoder_set_total_samples_estimate(encoder_wrapper->encoder, encoder_wrapper->total_samples_to_encode);
724 FLAC__stream_encoder_set_seek_table(encoder_wrapper->encoder, (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0);
725 FLAC__stream_encoder_set_padding(encoder_wrapper->encoder, padding);
726 FLAC__stream_encoder_set_last_metadata_is_last(encoder_wrapper->encoder, true);
727 FLAC__stream_encoder_set_write_callback(encoder_wrapper->encoder, write_callback);
728 FLAC__stream_encoder_set_metadata_callback(encoder_wrapper->encoder, metadata_callback);
729 FLAC__stream_encoder_set_client_data(encoder_wrapper->encoder, encoder_wrapper);
731 if(FLAC__stream_encoder_init(encoder_wrapper->encoder) != FLAC__STREAM_ENCODER_OK) {
732 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)]);
736 /* the above call writes all the metadata, so we save the stream offset now */
737 encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
742 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)
744 unsigned i, j, real_points, placeholders;
745 char *pt = requested_seek_points, *q;
748 seek_table->num_points = 0;
750 if(num_requested_seek_points == 0)
753 if(num_requested_seek_points < 0) {
754 strcpy(requested_seek_points, "100x<");
755 num_requested_seek_points = 1;
758 /* first count how many individual seek point we may need */
759 real_points = placeholders = 0;
760 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
762 FLAC__ASSERT(0 != q);
765 if(0 == strcmp(pt, "X")) { /* -S X */
768 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
769 if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
770 real_points += (unsigned)atoi(pt);
779 pt = requested_seek_points;
781 /* make some space */
782 if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
785 /* initialize the seek_table. we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
786 for(i = 0; i < real_points+placeholders; i++) {
787 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
788 seek_table->points[i].stream_offset = 0;
789 seek_table->points[i].frame_samples = 0;
792 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
794 FLAC__ASSERT(0 != q);
797 if(0 == strcmp(pt, "X")) { /* -S X */
798 ; /* we append placeholders later */
800 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
801 if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
803 n = (unsigned)atoi(pt);
804 for(j = 0; j < n; j++)
805 append_point_to_seek_table(seek_table, stream_samples * (FLAC__uint64)j / (FLAC__uint64)n, stream_samples, blocksize);
809 append_point_to_seek_table(seek_table, (FLAC__uint64)atoi(pt), stream_samples, blocksize);
815 /* sort the seekpoints */
816 qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
818 /* uniqify the seekpoints */
820 for(i = j = 0; i < seek_table->num_points; i++) {
822 if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
826 seek_table->points[j++] = seek_table->points[i];
828 seek_table->num_points = j;
830 /* append placeholders */
831 for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
832 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
833 seek_table->num_points += placeholders;
838 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, FLAC__uint64 sample, FLAC__uint64 stream_samples, FLAC__uint64 blocksize)
840 const FLAC__uint64 target_sample = (sample / blocksize) * blocksize;
842 if(stream_samples == 0 || target_sample < stream_samples)
843 seek_table->points[seek_table->num_points++].sample_number = target_sample;
846 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
848 /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
849 if(l->sample_number == r->sample_number)
851 else if(l->sample_number < r->sample_number)
857 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)
859 unsigned wide_sample, sample, channel, byte;
862 if(is_unsigned_samples) {
863 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
864 for(channel = 0; channel < channels; channel++, sample++)
865 dest[channel][wide_sample] = (FLAC__int32)ucbuffer[sample] - 0x80;
868 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
869 for(channel = 0; channel < channels; channel++, sample++)
870 dest[channel][wide_sample] = (FLAC__int32)scbuffer[sample];
874 if(is_big_endian != is_big_endian_host) {
876 const unsigned bytes = wide_samples * channels * (bps >> 3);
877 for(byte = 0; byte < bytes; byte += 2) {
878 tmp = ucbuffer[byte];
879 ucbuffer[byte] = ucbuffer[byte+1];
880 ucbuffer[byte+1] = tmp;
883 if(is_unsigned_samples) {
884 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
885 for(channel = 0; channel < channels; channel++, sample++)
886 dest[channel][wide_sample] = (FLAC__int32)usbuffer[sample] - 0x8000;
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)ssbuffer[sample];
897 const unsigned bytes = wide_samples * channels * (bps >> 3);
898 for(byte = 0; byte < bytes; byte += 3) {
899 tmp = ucbuffer[byte];
900 ucbuffer[byte] = ucbuffer[byte+2];
901 ucbuffer[byte+2] = tmp;
904 if(is_unsigned_samples) {
905 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
906 for(channel = 0; channel < channels; channel++, sample++) {
907 dest[channel][wide_sample] = ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
908 dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
909 dest[channel][wide_sample] |= ucbuffer[byte++];
910 dest[channel][wide_sample] -= 0x800000;
914 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
915 for(channel = 0; channel < channels; channel++, sample++) {
916 dest[channel][wide_sample] = scbuffer[byte++]; dest[channel][wide_sample] <<= 8;
917 dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
918 dest[channel][wide_sample] |= ucbuffer[byte++];
926 /* 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: */
927 append_to_verify_fifo(encoder_wrapper, dest, channels, wide_samples);
930 void append_to_verify_fifo(encoder_wrapper_struct *encoder_wrapper, const FLAC__int32 *src[], unsigned channels, unsigned wide_samples)
932 if(encoder_wrapper->verify) {
934 for(channel = 0; channel < channels; channel++)
935 memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], src[channel], sizeof(FLAC__int32) * wide_samples);
936 encoder_wrapper->verify_fifo.tail += wide_samples;
937 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
941 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
943 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
944 const unsigned mask = (FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
946 /* 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) */
947 if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
948 FLAC__uint64 current_sample = (FLAC__uint64)current_frame * (FLAC__uint64)FLAC__stream_encoder_get_blocksize(encoder), test_sample;
950 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
951 test_sample = encoder_wrapper->seek_table.points[i].sample_number;
952 if(test_sample > current_sample) {
955 else if(test_sample == current_sample) {
956 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
957 encoder_wrapper->seek_table.points[i].frame_samples = FLAC__stream_encoder_get_blocksize(encoder);
958 encoder_wrapper->first_seek_point_to_check++;
962 encoder_wrapper->first_seek_point_to_check++;
967 encoder_wrapper->bytes_written += bytes;
968 encoder_wrapper->samples_written += samples;
969 encoder_wrapper->current_frame = current_frame;
971 if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
972 print_stats(encoder_wrapper);
974 if(encoder_wrapper->verify) {
975 encoder_wrapper->verify_fifo.encoded_signal = buffer;
976 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
977 if(encoder_wrapper->verify_fifo.into_frames) {
978 if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
979 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
980 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
984 if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
985 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
986 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
991 if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_wrapper->fout) == bytes)
992 return FLAC__STREAM_ENCODER_WRITE_OK;
994 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
997 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
999 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1002 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
1003 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
1004 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
1006 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
1009 * we get called by the encoder when the encoding process has
1010 * finished so that we can update the STREAMINFO and SEEKTABLE
1014 (void)encoder; /* silence compiler warning about unused parameter */
1016 if(encoder_wrapper->fout == stdout)
1019 fclose(encoder_wrapper->fout);
1020 if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
1023 /* all this is based on intimate knowledge of the stream header
1024 * layout, but a change to the header format that would break this
1025 * would also break all streams encoded in the previous format.
1028 if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
1029 fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
1032 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
1033 if(fread(&b, 1, 1, f) != 1) goto framesize_;
1034 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
1035 b = (b & 0xf0) | (FLAC__byte)((samples >> 32) & 0x0F);
1036 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1037 b = (FLAC__byte)((samples >> 24) & 0xFF);
1038 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1039 b = (FLAC__byte)((samples >> 16) & 0xFF);
1040 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1041 b = (FLAC__byte)((samples >> 8) & 0xFF);
1042 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1043 b = (FLAC__byte)(samples & 0xFF);
1044 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1047 if(-1 == fseek(f, 12, SEEK_SET)) goto seektable_;
1048 b = (FLAC__byte)((min_framesize >> 16) & 0xFF);
1049 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1050 b = (FLAC__byte)((min_framesize >> 8) & 0xFF);
1051 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1052 b = (FLAC__byte)(min_framesize & 0xFF);
1053 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1054 b = (FLAC__byte)((max_framesize >> 16) & 0xFF);
1055 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1056 b = (FLAC__byte)((max_framesize >> 8) & 0xFF);
1057 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1058 b = (FLAC__byte)(max_framesize & 0xFF);
1059 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1062 if(encoder_wrapper->seek_table.num_points > 0) {
1066 /* convert any unused seek points to placeholders */
1067 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
1068 if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
1070 else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
1071 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
1074 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
1075 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1076 pos += metadata->length;
1077 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1078 if(-1 == fseek(f, pos, SEEK_SET)) goto end_;
1079 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
1080 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
1081 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
1082 if(!write_big_endian_uint16(f, (FLAC__uint16)encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
1091 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
1093 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1094 const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
1097 if(encoded_bytes <= *bytes) {
1098 *bytes = encoded_bytes;
1099 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1102 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1103 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
1104 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
1107 return FLAC__STREAM_DECODER_READ_CONTINUE;
1110 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
1112 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1113 unsigned channel, l, r;
1114 const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
1115 const unsigned bytes_per_block = sizeof(FLAC__int32) * FLAC__stream_decoder_get_blocksize(decoder);
1117 for(channel = 0; channel < channels; channel++) {
1118 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], bytes_per_block)) {
1119 unsigned sample = 0;
1120 int expect = 0, got = 0;
1121 fprintf(stderr, "\n%s: ERROR: mismatch in decoded data, verify FAILED!\n", encoder_wrapper->inbasefilename);
1122 fprintf(stderr, " Please submit a bug report to\n");
1123 fprintf(stderr, " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1124 fprintf(stderr, " Make sure to include an email contact in the comment and/or use the\n");
1125 fprintf(stderr, " \"Monitor\" feature to monitor the bug status.\n");
1126 for(l = 0, r = FLAC__stream_decoder_get_blocksize(decoder); l < r; l++) {
1127 if(buffer[channel][l] != encoder_wrapper->verify_fifo.original[channel][l]) {
1129 expect = (int)encoder_wrapper->verify_fifo.original[channel][l];
1130 got = (int)buffer[channel][l];
1134 FLAC__ASSERT(l < r);
1135 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1136 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 */
1137 return FLAC__STREAM_DECODER_WRITE_ABORT;
1140 /* dequeue the frame from the fifo */
1141 for(channel = 0; channel < channels; channel++) {
1142 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
1143 encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
1146 encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
1147 return FLAC__STREAM_DECODER_WRITE_CONTINUE;
1150 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
1157 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1159 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1161 fprintf(stderr, "\n%s: ERROR: verification decoder returned error %d:%s\n", encoder_wrapper->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1164 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1167 /* with VC++ you have to spoon feed it the casting */
1168 const double progress = (double)(FLAC__int64)encoder_wrapper->samples_written / (double)(FLAC__int64)encoder_wrapper->total_samples_to_encode;
1169 const double ratio = (double)(FLAC__int64)encoder_wrapper->bytes_written / ((double)(FLAC__int64)encoder_wrapper->unencoded_size * progress);
1171 const double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1172 const double ratio = (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress);
1175 if(encoder_wrapper->samples_written == encoder_wrapper->total_samples_to_encode) {
1176 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1177 encoder_wrapper->inbasefilename,
1178 encoder_wrapper->verify? (encoder_wrapper->verify_fifo.result == FLAC__VERIFY_OK? " Verify OK," : " Verify FAILED!") : "",
1179 (unsigned)encoder_wrapper->bytes_written,
1184 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_wrapper->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1188 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1190 size_t bytes_read = fread(val, 1, 2, f);
1192 if(bytes_read == 0) {
1194 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1200 else if(bytes_read < 2) {
1201 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1205 if(is_big_endian_host) {
1206 FLAC__byte tmp, *b = (FLAC__byte*)val;
1207 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1213 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1215 size_t bytes_read = fread(val, 1, 4, f);
1217 if(bytes_read == 0) {
1219 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1225 else if(bytes_read < 4) {
1226 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1230 if(is_big_endian_host) {
1231 FLAC__byte tmp, *b = (FLAC__byte*)val;
1232 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1233 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1239 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
1241 if(!is_big_endian_host) {
1242 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1243 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1245 return fwrite(&val, 1, 2, f) == 2;
1248 FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val)
1250 if(!is_big_endian_host) {
1251 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1252 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1253 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1254 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1255 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1257 return fwrite(&val, 1, 8, f) == 8;