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 <stdio.h> /* for FILE et al. */
26 #include <stdlib.h> /* for malloc */
27 #include <string.h> /* for strcmp() */
34 #define min(x,y) ((x)<(y)?(x):(y))
36 #define CHUNK_OF_SAMPLES 2048
40 FLAC__VERIFY_FAILED_IN_FRAME,
41 FLAC__VERIFY_FAILED_IN_METADATA
44 static const char *verify_code_string[] = {
46 "FLAC__VERIFY_FAILED_IN_FRAME",
47 "FLAC__VERIFY_FAILED_IN_METADATA"
51 int32 *original[FLAC__MAX_CHANNELS];
52 unsigned size; /* of each original[] in samples */
53 unsigned tail; /* in wide samples */
54 const byte *encoded_signal;
55 unsigned encoded_signal_capacity;
56 unsigned encoded_bytes;
59 FLAC__StreamDecoder *decoder;
64 const char *outfilename;
65 FLAC__StreamEncoder *encoder;
68 uint64 unencoded_size;
69 uint64 total_samples_to_encode;
71 uint64 samples_written;
72 uint64 stream_offset; /* i.e. number of bytes before the first byte of the the first frame's header */
73 unsigned current_frame;
74 verify_fifo_struct verify_fifo;
75 FLAC__StreamMetaData_SeekTable seek_table;
76 unsigned first_seek_point_to_check;
77 } encoder_wrapper_struct;
79 static bool is_big_endian_host;
81 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__MAX_BITS_PER_SAMPLE+7)/8)];
82 static signed char *scbuffer = (signed char *)ucbuffer;
83 static uint16 *usbuffer = (uint16 *)ucbuffer;
84 static int16 *ssbuffer = (int16 *)ucbuffer;
86 static int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
87 static int32 *input[FLAC__MAX_CHANNELS];
90 static bool init(encoder_wrapper_struct *encoder_wrapper);
91 static bool init_encoder(bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, 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);
92 static bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table);
93 static void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize);
94 static int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r);
95 static void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
96 static FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
97 static void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
98 static FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data);
99 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data);
100 static void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
101 static void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
102 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
103 static bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok);
104 static bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok);
105 static bool write_big_endian_uint16(FILE *f, uint16 val);
106 static bool write_big_endian_uint64(FILE *f, uint64 val);
108 int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const byte *lookahead, unsigned lookahead_length, bool verbose, uint64 skip, bool verify, bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, 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)
110 encoder_wrapper_struct encoder_wrapper;
111 bool is_unsigned_samples = false;
112 unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
113 size_t bytes_per_wide_sample, bytes_read;
116 bool got_fmt_chunk = false, got_data_chunk = false;
118 encoder_wrapper.encoder = 0;
119 encoder_wrapper.verify = verify;
120 encoder_wrapper.verbose = verbose;
121 encoder_wrapper.bytes_written = 0;
122 encoder_wrapper.samples_written = 0;
123 encoder_wrapper.stream_offset = 0;
124 encoder_wrapper.outfilename = outfilename;
125 encoder_wrapper.seek_table.points = 0;
126 encoder_wrapper.first_seek_point_to_check = 0;
129 (void)lookahead_length;
131 if(0 == strcmp(outfilename, "-")) {
132 encoder_wrapper.fout = stdout;
135 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
136 fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
142 if(!init(&encoder_wrapper))
146 * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
148 while(!feof(infile)) {
149 if(!read_little_endian_uint32(infile, &xx, true))
153 if(xx == 0x20746d66) { /* "fmt " */
155 fprintf(stderr, "WARNING: skipping extra 'fmt ' sub-chunk\n");
158 /* fmt sub-chunk size */
159 if(!read_little_endian_uint32(infile, &xx, false))
162 fprintf(stderr, "ERROR: unsupported non-standard 'fmt ' sub-chunk has length %u != 16\n", (unsigned)xx);
165 /* compression code */
166 if(!read_little_endian_uint16(infile, &x, false))
169 fprintf(stderr, "ERROR: unsupported compression type %u\n", (unsigned)x);
172 /* number of channels */
173 if(!read_little_endian_uint16(infile, &x, false))
175 if(x == 0 || x > FLAC__MAX_CHANNELS) {
176 fprintf(stderr, "ERROR: unsupported number channels %u\n", (unsigned)x);
181 if(!read_little_endian_uint32(infile, &xx, false))
183 if(xx == 0 || xx > FLAC__MAX_SAMPLE_RATE) {
184 fprintf(stderr, "ERROR: unsupported sample rate %u\n", (unsigned)xx);
188 /* avg bytes per second (ignored) */
189 if(!read_little_endian_uint32(infile, &xx, false))
191 /* block align (ignored) */
192 if(!read_little_endian_uint16(infile, &x, false))
194 /* bits per sample */
195 if(!read_little_endian_uint16(infile, &x, false))
197 if(x != 8 && x != 16) {
198 fprintf(stderr, "ERROR: unsupported bits per sample %u\n", (unsigned)x);
202 is_unsigned_samples = (x == 8);
204 got_fmt_chunk = true;
207 else if(xx == 0x61746164) { /* "data" */
209 fprintf(stderr, "WARNING: skipping extra 'data' sub-chunk\n");
211 else if(!got_fmt_chunk) {
212 fprintf(stderr, "ERROR: got data sub-chunk before fmt sub-chunk\n");
217 if(!read_little_endian_uint32(infile, &xx, false))
221 bytes_per_wide_sample = channels * (bps >> 3);
224 if(infile != stdin) {
225 if(-1 == fseek(infile, bytes_per_wide_sample * (unsigned)skip, SEEK_CUR)) {
226 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
232 for(left = skip; left > 0; ) {
233 need = min(left, CHUNK_OF_SAMPLES);
234 if(fread(ucbuffer, 1, bytes_per_wide_sample * need, infile) < need) {
235 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
243 data_bytes -= skip * bytes_per_wide_sample;
244 encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample;
245 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44; /* 44 for the size of the WAV headers */
247 if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, 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))
250 encoder_wrapper.verify_fifo.into_frames = true;
252 while(data_bytes > 0) {
253 bytes_read = fread(ucbuffer, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
254 if(bytes_read == 0) {
256 fprintf(stderr, "ERROR reading from %s\n", infilename);
259 else if(feof(infile)) {
260 fprintf(stderr, "WARNING: unexpected EOF from %s, expected %u samples, got %u samples\n", infilename, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
265 if(bytes_read % bytes_per_wide_sample != 0) {
266 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infilename);
270 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
271 format_input(wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
273 /* 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: */
274 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
275 fprintf(stderr, "ERROR during encoding, state = %d:%s\n", FLAC__stream_encoder_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_state(encoder_wrapper.encoder)]);
278 data_bytes -= bytes_read;
282 got_data_chunk = true;
286 fprintf(stderr, "WARNING: skipping unknown sub-chunk '%c%c%c%c'\n", (char)(xx&255), (char)((xx>>8)&255), (char)((xx>>16)&255), (char)(xx>>24));
288 if(!read_little_endian_uint32(infile, &xx, false))
290 if(infile != stdin) {
291 if(-1 == fseek(infile, xx, SEEK_CUR)) {
292 fprintf(stderr, "ERROR seeking ahead while skipping unsupported sub-chunk in input file %s\n", infilename);
298 const unsigned chunk = sizeof(ucbuffer);
299 for(left = xx; left > 0; ) {
300 need = min(left, chunk);
301 if(fread(ucbuffer, 1, need, infile) < need) {
302 fprintf(stderr, "ERROR seeking while skipping unsupported sub-chunk in input file %s\n", infilename);
311 if(encoder_wrapper.encoder) {
312 if(FLAC__stream_encoder_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
313 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
314 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
316 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
317 print_stats(&encoder_wrapper);
318 fprintf(stderr, "\n");
320 if(0 != encoder_wrapper.seek_table.points)
321 free(encoder_wrapper.seek_table.points);
323 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
324 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
325 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
326 fprintf(stderr, "%s: Verify FAILED! (%s) Do not trust %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
329 else if(encoder_wrapper.verbose) {
330 fprintf(stderr, "%s: Verify succeeded\n", infilename);
337 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
338 fprintf(stderr, "\n");
339 if(encoder_wrapper.encoder) {
340 if(FLAC__stream_encoder_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
341 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
342 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
344 if(0 != encoder_wrapper.seek_table.points)
345 free(encoder_wrapper.seek_table.points);
347 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
348 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
349 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
350 fprintf(stderr, "%s: Verify FAILED! (%s) Do not trust %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
353 else if(encoder_wrapper.verbose) {
354 fprintf(stderr, "%s: Verify succeeded\n", infilename);
363 int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const byte *lookahead, unsigned lookahead_length, bool verbose, uint64 skip, bool verify, bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, 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, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned sample_rate)
365 encoder_wrapper_struct encoder_wrapper;
367 const size_t bytes_per_wide_sample = channels * (bps >> 3);
369 encoder_wrapper.encoder = 0;
370 encoder_wrapper.verify = verify;
371 encoder_wrapper.verbose = verbose;
372 encoder_wrapper.bytes_written = 0;
373 encoder_wrapper.samples_written = 0;
374 encoder_wrapper.stream_offset = 0;
375 encoder_wrapper.outfilename = outfilename;
376 encoder_wrapper.seek_table.points = 0;
377 encoder_wrapper.first_seek_point_to_check = 0;
379 if(0 == strcmp(outfilename, "-")) {
380 encoder_wrapper.fout = stdout;
383 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
384 fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
390 if(!init(&encoder_wrapper))
393 /* get the file length */
395 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
398 encoder_wrapper.unencoded_size = (unsigned)infilesize - skip * bytes_per_wide_sample;
399 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - skip;
402 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
403 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
406 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)skip;
407 if(skip_bytes > lookahead_length) {
408 skip_bytes -= lookahead_length;
409 lookahead_length = 0;
410 if(infile != stdin) {
411 if(-1 == fseek(infile, (long)skip_bytes, SEEK_SET)) {
412 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
418 const unsigned chunk = sizeof(ucbuffer);
419 for(left = skip_bytes; left > 0; ) {
420 need = min(left, chunk);
421 if(fread(ucbuffer, 1, need, infile) < need) {
422 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
430 lookahead += skip_bytes;
431 lookahead_length -= skip_bytes;
435 fseek(infile, 0, SEEK_SET);
438 if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, 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))
441 encoder_wrapper.verify_fifo.into_frames = true;
443 while(!feof(infile)) {
444 if(lookahead_length > 0) {
445 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
446 memcpy(ucbuffer, lookahead, lookahead_length);
447 bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
449 fprintf(stderr, "ERROR reading from %s\n", infilename);
452 lookahead_length = 0;
455 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
457 if(bytes_read == 0) {
459 fprintf(stderr, "ERROR reading from %s\n", infilename);
463 else if(bytes_read % bytes_per_wide_sample != 0) {
464 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infilename);
468 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
469 format_input(wide_samples, is_big_endian, is_unsigned_samples, channels, bps, &encoder_wrapper);
471 /* 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: */
472 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
473 fprintf(stderr, "ERROR during encoding, state = %d:%s\n", FLAC__stream_encoder_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_state(encoder_wrapper.encoder)]);
479 if(encoder_wrapper.encoder) {
480 if(FLAC__stream_encoder_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
481 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
482 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
484 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
485 print_stats(&encoder_wrapper);
486 fprintf(stderr, "\n");
488 if(0 != encoder_wrapper.seek_table.points)
489 free(encoder_wrapper.seek_table.points);
491 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
492 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
493 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
494 fprintf(stderr, "%s: Verify FAILED! (%s) Do not trust %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
497 else if(encoder_wrapper.verbose) {
498 fprintf(stderr, "%s: Verify succeeded\n", infilename);
505 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
506 fprintf(stderr, "\n");
507 if(encoder_wrapper.encoder) {
508 if(FLAC__stream_encoder_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
509 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
510 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
512 if(0 != encoder_wrapper.seek_table.points)
513 free(encoder_wrapper.seek_table.points);
515 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
516 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
517 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
518 fprintf(stderr, "%s: Verify FAILED! (%s) Do not trust %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
521 else if(encoder_wrapper.verbose) {
522 fprintf(stderr, "%s: Verify succeeded\n", infilename);
531 bool init(encoder_wrapper_struct *encoder_wrapper)
536 is_big_endian_host = (*((byte*)(&test)))? false : true;
538 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
539 input[i] = &(in[i][0]);
541 encoder_wrapper->encoder = FLAC__stream_encoder_new();
542 if(0 == encoder_wrapper->encoder) {
543 fprintf(stderr, "ERROR creating the encoder instance\n");
550 bool init_encoder(bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, 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)
555 do_mid_side = loose_mid_side = false;
557 if(encoder_wrapper->verify) {
558 /* set up the fifo which will hold the original signal to compare against */
559 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
560 for(i = 0; i < channels; i++) {
561 if(0 == (encoder_wrapper->verify_fifo.original[i] = (int32*)malloc(sizeof(int32) * encoder_wrapper->verify_fifo.size))) {
562 fprintf(stderr, "ERROR allocating verify buffers\n");
566 encoder_wrapper->verify_fifo.tail = 0;
567 encoder_wrapper->verify_fifo.into_frames = false;
568 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
570 /* set up a stream decoder for verification */
571 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_new();
572 if(0 == encoder_wrapper->verify_fifo.decoder) {
573 fprintf(stderr, "ERROR creating the verify decoder instance\n");
576 if(FLAC__stream_decoder_init(encoder_wrapper->verify_fifo.decoder, verify_read_callback, verify_write_callback, verify_metadata_callback, verify_error_callback, encoder_wrapper) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
577 fprintf(stderr, "ERROR initializing decoder, state = %d:%s\n", FLAC__stream_decoder_state(encoder_wrapper->verify_fifo.decoder), FLAC__StreamDecoderStateString[FLAC__stream_decoder_state(encoder_wrapper->verify_fifo.decoder)]);
582 if(!convert_to_seek_table(requested_seek_points, num_requested_seek_points, encoder_wrapper->total_samples_to_encode, blocksize, &encoder_wrapper->seek_table)) {
583 fprintf(stderr, "ERROR allocating seek table\n");
587 if(FLAC__stream_encoder_init(encoder_wrapper->encoder, !lax, do_mid_side, loose_mid_side, channels, bps, sample_rate, blocksize, max_lpc_order, qlp_coeff_precision, do_qlp_coeff_prec_search, do_exhaustive_model_search, min_residual_partition_order, max_residual_partition_order, rice_parameter_search_dist, encoder_wrapper->total_samples_to_encode, (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0, padding, true /*last_metadata_is_last*/, write_callback, metadata_callback, encoder_wrapper) != FLAC__STREAM_ENCODER_OK) {
588 fprintf(stderr, "ERROR initializing encoder, state = %d:%s\n", FLAC__stream_encoder_state(encoder_wrapper->encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_state(encoder_wrapper->encoder)]);
592 /* the above call writes all the metadata, so we save the stream offset now */
593 encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
598 bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table)
600 unsigned i, j, real_points, placeholders;
601 char *pt = requested_seek_points, *q;
604 seek_table->num_points = 0;
606 if(num_requested_seek_points == 0)
609 if(num_requested_seek_points < 0) {
610 strcpy(requested_seek_points, "100x<");
611 num_requested_seek_points = 1;
614 /* first count how many individual seek point we may need */
615 real_points = placeholders = 0;
616 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
618 FLAC__ASSERT(0 != q);
621 if(0 == strcmp(pt, "X")) { /* -S X */
624 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
625 if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
626 real_points += (unsigned)atoi(pt);
635 pt = requested_seek_points;
637 /* make some space */
638 if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
641 /* initialize the seek_table. we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
642 for(i = 0; i < real_points+placeholders; i++) {
643 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
644 seek_table->points[i].stream_offset = 0;
645 seek_table->points[i].frame_samples = 0;
648 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
650 FLAC__ASSERT(0 != q);
653 if(0 == strcmp(pt, "X")) { /* -S X */
654 ; /* we append placeholders later */
656 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
657 if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
659 n = (unsigned)atoi(pt);
660 for(j = 0; j < n; j++)
661 append_point_to_seek_table(seek_table, stream_samples * (uint64)j / (uint64)n, stream_samples, blocksize);
665 append_point_to_seek_table(seek_table, (uint64)atoi(pt), stream_samples, blocksize);
671 /* sort the seekpoints */
672 qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
674 /* uniqify the seekpoints */
676 for(i = j = 0; i < seek_table->num_points; i++) {
678 if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
682 seek_table->points[j++] = seek_table->points[i];
684 seek_table->num_points = j;
686 /* append placeholders */
687 for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
688 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
689 seek_table->num_points += placeholders;
694 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize)
696 const uint64 target_sample = (sample / blocksize) * blocksize;
698 if(stream_samples == 0 || target_sample < stream_samples)
699 seek_table->points[seek_table->num_points++].sample_number = target_sample;
702 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
704 /* we don't just 'return l->sample_number - r->sample_number' since the result (int64) might overflow an 'int' */
705 if(l->sample_number == r->sample_number)
707 else if(l->sample_number < r->sample_number)
713 void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
715 unsigned wide_sample, sample, channel, byte;
718 if(is_unsigned_samples) {
719 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
720 for(channel = 0; channel < channels; channel++, sample++)
721 input[channel][wide_sample] = (int32)ucbuffer[sample] - 0x80;
724 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
725 for(channel = 0; channel < channels; channel++, sample++)
726 input[channel][wide_sample] = (int32)scbuffer[sample];
730 if(is_big_endian != is_big_endian_host) {
732 const unsigned bytes = wide_samples * channels * (bps >> 3);
733 for(byte = 0; byte < bytes; byte += 2) {
734 tmp = ucbuffer[byte];
735 ucbuffer[byte] = ucbuffer[byte+1];
736 ucbuffer[byte+1] = tmp;
739 if(is_unsigned_samples) {
740 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
741 for(channel = 0; channel < channels; channel++, sample++)
742 input[channel][wide_sample] = (int32)usbuffer[sample] - 0x8000;
745 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
746 for(channel = 0; channel < channels; channel++, sample++)
747 input[channel][wide_sample] = (int32)ssbuffer[sample];
753 const unsigned bytes = wide_samples * channels * (bps >> 3);
754 for(byte = 0; byte < bytes; byte += 3) {
755 tmp = ucbuffer[byte];
756 ucbuffer[byte] = ucbuffer[byte+2];
757 ucbuffer[byte+2] = tmp;
760 if(is_unsigned_samples) {
761 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
762 for(channel = 0; channel < channels; channel++, sample++) {
763 input[channel][wide_sample] = ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
764 input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
765 input[channel][wide_sample] |= ucbuffer[byte++];
766 input[channel][wide_sample] -= 0x800000;
770 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
771 for(channel = 0; channel < channels; channel++, sample++) {
772 input[channel][wide_sample] = scbuffer[byte++]; input[channel][wide_sample] <<= 8;
773 input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
774 input[channel][wide_sample] |= ucbuffer[byte++];
782 if(encoder_wrapper->verify) {
783 for(channel = 0; channel < channels; channel++)
784 memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], &input[channel][0], sizeof(int32) * wide_samples);
785 encoder_wrapper->verify_fifo.tail += wide_samples;
786 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
790 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
792 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
793 const unsigned mask = (FLAC__stream_encoder_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
795 /* 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) */
796 if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
797 uint64 current_sample = (uint64)current_frame * (uint64)FLAC__stream_encoder_blocksize(encoder), test_sample;
799 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
800 test_sample = encoder_wrapper->seek_table.points[i].sample_number;
801 if(test_sample > current_sample) {
804 else if(test_sample == current_sample) {
805 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
806 encoder_wrapper->seek_table.points[i].frame_samples = FLAC__stream_encoder_blocksize(encoder);
807 encoder_wrapper->first_seek_point_to_check++;
811 encoder_wrapper->first_seek_point_to_check++;
816 encoder_wrapper->bytes_written += bytes;
817 encoder_wrapper->samples_written += samples;
818 encoder_wrapper->current_frame = current_frame;
820 if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
821 print_stats(encoder_wrapper);
823 if(encoder_wrapper->verify) {
824 encoder_wrapper->verify_fifo.encoded_signal = buffer;
825 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
826 if(encoder_wrapper->verify_fifo.into_frames) {
827 if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
828 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
829 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
833 if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
834 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
835 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
840 if(fwrite(buffer, sizeof(byte), bytes, encoder_wrapper->fout) == bytes)
841 return FLAC__STREAM_ENCODER_WRITE_OK;
843 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
846 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
848 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
851 const uint64 samples = metadata->data.stream_info.total_samples;
852 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
853 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
855 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
858 * we get called by the encoder when the encoding process has
859 * finished so that we can update the STREAMINFO and SEEKTABLE
863 (void)encoder; /* silence compiler warning about unused parameter */
865 if(encoder_wrapper->fout == stdout)
868 fclose(encoder_wrapper->fout);
869 if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
872 /* all this is based on intimate knowledge of the stream header
873 * layout, but a change to the header format that would break this
874 * would also break all streams encoded in the previous format.
877 if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
878 fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
881 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
882 if(fread(&b, 1, 1, f) != 1) goto framesize_;
883 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
884 b = (b & 0xf0) | (byte)((samples >> 32) & 0x0F);
885 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
886 b = (byte)((samples >> 24) & 0xFF);
887 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
888 b = (byte)((samples >> 16) & 0xFF);
889 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
890 b = (byte)((samples >> 8) & 0xFF);
891 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
892 b = (byte)(samples & 0xFF);
893 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
896 if(-1 == fseek(f, 12, SEEK_SET)) goto seektable_;
897 b = (byte)((min_framesize >> 16) & 0xFF);
898 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
899 b = (byte)((min_framesize >> 8) & 0xFF);
900 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
901 b = (byte)(min_framesize & 0xFF);
902 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
903 b = (byte)((max_framesize >> 16) & 0xFF);
904 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
905 b = (byte)((max_framesize >> 8) & 0xFF);
906 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
907 b = (byte)(max_framesize & 0xFF);
908 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
911 if(encoder_wrapper->seek_table.num_points > 0) {
915 /* convert any unused seek points to placeholders */
916 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
917 if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
919 else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
920 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
923 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
924 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
925 pos += metadata->length;
926 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
927 if(-1 == fseek(f, pos, SEEK_SET)) goto end_;
928 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
929 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
930 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
931 if(!write_big_endian_uint16(f, encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
940 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
942 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
943 const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
946 if(encoded_bytes <= *bytes) {
947 *bytes = encoded_bytes;
948 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
951 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
952 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
953 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
956 return FLAC__STREAM_DECODER_READ_CONTINUE;
959 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
961 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
962 unsigned channel, l, r;
963 const unsigned channels = FLAC__stream_decoder_channels(decoder);
964 const unsigned bytes_per_block = sizeof(int32) * FLAC__stream_decoder_blocksize(decoder);
966 for(channel = 0; channel < channels; channel++) {
967 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], bytes_per_block)) {
968 fprintf(stderr, "\nERROR: mismatch in decoded data, verify FAILED!\n");
969 fprintf(stderr, " Please submit a bug report to\n");
970 fprintf(stderr, " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
971 fprintf(stderr, " Make sure to include an email contact in the comment and/or use the\n");
972 fprintf(stderr, " \"Monitor\" feature to monitor the bug status.\n");
973 return FLAC__STREAM_DECODER_WRITE_ABORT;
976 /* dequeue the frame from the fifo */
977 for(channel = 0; channel < channels; channel++) {
978 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
979 encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
982 encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
983 return FLAC__STREAM_DECODER_WRITE_CONTINUE;
986 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
993 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
997 fprintf(stderr, "\nERROR: verification decoder returned error %d:%s\n", status, FLAC__StreamDecoderErrorStatusString[status]);
1000 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1003 /* with VC++ you have to spoon feed it the casting */
1004 double progress = (double)(int64)encoder_wrapper->samples_written / (double)(int64)encoder_wrapper->total_samples_to_encode;
1006 double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1008 fprintf(stderr, "\r%0.2f%% complete: frame %u, wrote %u bytes (%u/%u samples), r=%5.3f",
1009 progress * 100.0, encoder_wrapper->current_frame,
1010 (unsigned)encoder_wrapper->bytes_written, (unsigned)encoder_wrapper->samples_written, (unsigned)encoder_wrapper->total_samples_to_encode,
1012 /* with VC++ you have to spoon feed it the casting */
1013 (double)(int64)encoder_wrapper->bytes_written / ((double)(int64)encoder_wrapper->unencoded_size * progress)
1015 (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress)
1020 bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok)
1022 size_t bytes_read = fread(val, 1, 2, f);
1024 if(bytes_read == 0) {
1026 fprintf(stderr, "ERROR: unexpected EOF\n");
1032 else if(bytes_read < 2) {
1033 fprintf(stderr, "ERROR: unexpected EOF\n");
1037 if(is_big_endian_host) {
1038 byte tmp, *b = (byte*)val;
1039 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1045 bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok)
1047 size_t bytes_read = fread(val, 1, 4, f);
1049 if(bytes_read == 0) {
1051 fprintf(stderr, "ERROR: unexpected EOF\n");
1057 else if(bytes_read < 4) {
1058 fprintf(stderr, "ERROR: unexpected EOF\n");
1062 if(is_big_endian_host) {
1063 byte tmp, *b = (byte*)val;
1064 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1065 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1071 bool write_big_endian_uint16(FILE *f, uint16 val)
1073 if(!is_big_endian_host) {
1074 byte *b = (byte *)&val, tmp;
1075 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1077 return fwrite(&val, 1, 2, f) == 2;
1080 bool write_big_endian_uint64(FILE *f, uint64 val)
1082 if(!is_big_endian_host) {
1083 byte *b = (byte *)&val, tmp;
1084 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1085 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1086 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1087 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1089 return fwrite(&val, 1, 8, f) == 8;