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 /*@@@ need to "_finish()" the verify decoder */
21 #if defined _WIN32 && !defined __CYGWIN__
22 /* where MSVC puts unlink() */
27 #include <stdio.h> /* for FILE et al. */
28 #include <stdlib.h> /* for malloc */
29 #include <string.h> /* for strcmp() */
36 #define min(x,y) ((x)<(y)?(x):(y))
38 #define CHUNK_OF_SAMPLES 2048
42 FLAC__VERIFY_FAILED_IN_FRAME,
43 FLAC__VERIFY_FAILED_IN_METADATA
46 static const char *verify_code_string[] = {
48 "FLAC__VERIFY_FAILED_IN_FRAME",
49 "FLAC__VERIFY_FAILED_IN_METADATA"
53 int32 *original[FLAC__MAX_CHANNELS];
54 unsigned size; /* of each original[] in samples */
55 unsigned tail; /* in wide samples */
56 const byte *encoded_signal;
57 unsigned encoded_signal_capacity;
58 unsigned encoded_bytes;
61 FLAC__StreamDecoder *decoder;
66 const char *outfilename;
67 FLAC__Encoder *encoder;
70 uint64 unencoded_size;
71 uint64 total_samples_to_encode;
73 uint64 samples_written;
74 uint64 stream_offset; /* i.e. number of bytes before the first byte of the the first frame's header */
75 unsigned current_frame;
76 verify_fifo_struct verify_fifo;
77 FLAC__StreamMetaData_SeekTable seek_table;
78 unsigned first_seek_point_to_check;
79 } encoder_wrapper_struct;
81 static bool is_big_endian_host;
83 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__MAX_BITS_PER_SAMPLE+7)/8)];
84 static signed char *scbuffer = (signed char *)ucbuffer;
85 static uint16 *usbuffer = (uint16 *)ucbuffer;
86 static int16 *ssbuffer = (int16 *)ucbuffer;
88 static int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
89 static int32 *input[FLAC__MAX_CHANNELS];
92 static bool init(encoder_wrapper_struct *encoder_wrapper);
93 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);
94 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);
95 static void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize);
96 static int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r);
97 static void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
98 static FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
99 static void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
100 static FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data);
101 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data);
102 static void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
103 static void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
104 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
105 static bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok);
106 static bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok);
107 static bool write_big_endian_uint16(FILE *f, uint16 val);
108 static bool write_big_endian_uint64(FILE *f, uint64 val);
110 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)
112 encoder_wrapper_struct encoder_wrapper;
113 bool is_unsigned_samples = false;
114 unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
115 size_t bytes_per_wide_sample, bytes_read;
118 bool got_fmt_chunk = false, got_data_chunk = false;
120 encoder_wrapper.encoder = 0;
121 encoder_wrapper.verify = verify;
122 encoder_wrapper.verbose = verbose;
123 encoder_wrapper.bytes_written = 0;
124 encoder_wrapper.samples_written = 0;
125 encoder_wrapper.stream_offset = 0;
126 encoder_wrapper.outfilename = outfilename;
127 encoder_wrapper.seek_table.points = 0;
128 encoder_wrapper.first_seek_point_to_check = 0;
131 (void)lookahead_length;
133 if(0 == strcmp(outfilename, "-")) {
134 encoder_wrapper.fout = stdout;
137 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
138 fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
144 if(!init(&encoder_wrapper))
148 * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
150 while(!feof(infile)) {
151 if(!read_little_endian_uint32(infile, &xx, true))
155 if(xx == 0x20746d66) { /* "fmt " */
157 fprintf(stderr, "WARNING: skipping extra 'fmt ' sub-chunk\n");
161 if(!read_little_endian_uint32(infile, &xx, false))
164 fprintf(stderr, "ERROR: unsupported chunk\n");
167 /* compression code */
168 if(!read_little_endian_uint16(infile, &x, false))
171 fprintf(stderr, "ERROR: unsupported compression type %u\n", (unsigned)x);
174 /* number of channels */
175 if(!read_little_endian_uint16(infile, &x, false))
177 if(x == 0 || x > FLAC__MAX_CHANNELS) {
178 fprintf(stderr, "ERROR: unsupported number channels %u\n", (unsigned)x);
183 if(!read_little_endian_uint32(infile, &xx, false))
185 if(xx == 0 || xx > FLAC__MAX_SAMPLE_RATE) {
186 fprintf(stderr, "ERROR: unsupported sample rate %u\n", (unsigned)xx);
190 /* avg bytes per second (ignored) */
191 if(!read_little_endian_uint32(infile, &xx, false))
193 /* block align (ignored) */
194 if(!read_little_endian_uint16(infile, &x, false))
196 /* bits per sample */
197 if(!read_little_endian_uint16(infile, &x, false))
199 if(x != 8 && x != 16) {
200 fprintf(stderr, "ERROR: unsupported bits per sample %u\n", (unsigned)x);
204 is_unsigned_samples = (x == 8);
206 got_fmt_chunk = true;
209 else if(xx == 0x61746164) { /* "data" */
211 fprintf(stderr, "WARNING: skipping extra 'data' sub-chunk\n");
213 else if(!got_fmt_chunk) {
214 fprintf(stderr, "ERROR: got data sub-chunk before fmt sub-chunk\n");
219 if(!read_little_endian_uint32(infile, &xx, false))
223 bytes_per_wide_sample = channels * (bps >> 3);
226 if(infile != stdin) {
227 if(-1 == fseek(infile, bytes_per_wide_sample * (unsigned)skip, SEEK_CUR)) {
228 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
234 for(left = skip; left > 0; ) {
235 need = min(left, CHUNK_OF_SAMPLES);
236 if(fread(ucbuffer, 1, bytes_per_wide_sample * need, infile) < need) {
237 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
245 encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample - skip;
246 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44; /* 44 for the size of the WAV headers */
248 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))
251 encoder_wrapper.verify_fifo.into_frames = true;
253 while(data_bytes > 0) {
254 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
255 if(bytes_read == 0) {
257 fprintf(stderr, "ERROR reading from %s\n", infilename);
260 else if(feof(infile))
264 if(bytes_read > data_bytes)
265 bytes_read = data_bytes; /* chop off anything after the end of the data chunk */
266 if(bytes_read % bytes_per_wide_sample != 0) {
267 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infilename);
271 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
272 format_input(wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
274 /* 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: */
275 if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
276 fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
279 data_bytes -= bytes_read;
283 got_data_chunk = true;
287 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));
289 if(!read_little_endian_uint32(infile, &xx, false))
291 if(infile != stdin) {
292 if(-1 == fseek(infile, xx, SEEK_CUR)) {
293 fprintf(stderr, "ERROR seeking ahead while skipping unsupported sub-chunk in input file %s\n", infilename);
299 const unsigned chunk = sizeof(ucbuffer);
300 for(left = xx; left > 0; ) {
301 need = min(left, chunk);
302 if(fread(ucbuffer, 1, need, infile) < need) {
303 fprintf(stderr, "ERROR seeking while skipping unsupported sub-chunk in input file %s\n", infilename);
312 if(encoder_wrapper.encoder) {
313 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
314 FLAC__encoder_finish(encoder_wrapper.encoder);
315 FLAC__encoder_free_instance(encoder_wrapper.encoder);
317 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
318 print_stats(&encoder_wrapper);
319 fprintf(stderr, "\n");
321 if(0 != encoder_wrapper.seek_table.points)
322 free(encoder_wrapper.seek_table.points);
324 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
325 fprintf(stderr, "%s: Verify FAILED! (%s) Do not trust %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
328 else if(encoder_wrapper.verbose) {
329 fprintf(stderr, "%s: Verify succeeded\n", infilename);
336 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
337 fprintf(stderr, "\n");
338 if(encoder_wrapper.encoder) {
339 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
340 FLAC__encoder_finish(encoder_wrapper.encoder);
341 FLAC__encoder_free_instance(encoder_wrapper.encoder);
343 if(0 != encoder_wrapper.seek_table.points)
344 free(encoder_wrapper.seek_table.points);
346 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
347 fprintf(stderr, "%s: Verify FAILED! (%s) Do not trust %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
350 else if(encoder_wrapper.verbose) {
351 fprintf(stderr, "%s: Verify succeeded\n", infilename);
360 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)
362 encoder_wrapper_struct encoder_wrapper;
364 const size_t bytes_per_wide_sample = channels * (bps >> 3);
366 encoder_wrapper.encoder = 0;
367 encoder_wrapper.verify = verify;
368 encoder_wrapper.verbose = verbose;
369 encoder_wrapper.bytes_written = 0;
370 encoder_wrapper.samples_written = 0;
371 encoder_wrapper.stream_offset = 0;
372 encoder_wrapper.outfilename = outfilename;
373 encoder_wrapper.seek_table.points = 0;
374 encoder_wrapper.first_seek_point_to_check = 0;
376 if(0 == strcmp(outfilename, "-")) {
377 encoder_wrapper.fout = stdout;
380 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
381 fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
387 if(!init(&encoder_wrapper))
390 /* get the file length */
392 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
395 encoder_wrapper.unencoded_size = (unsigned)infilesize - skip * bytes_per_wide_sample;
396 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - skip;
399 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
400 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
403 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)skip;
404 if(skip_bytes > lookahead_length) {
405 skip_bytes -= lookahead_length;
406 lookahead_length = 0;
407 if(infile != stdin) {
408 if(-1 == fseek(infile, (long)skip_bytes, SEEK_SET)) {
409 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
415 const unsigned chunk = sizeof(ucbuffer);
416 for(left = skip_bytes; left > 0; ) {
417 need = min(left, chunk);
418 if(fread(ucbuffer, 1, need, infile) < need) {
419 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
427 lookahead += skip_bytes;
428 lookahead_length -= skip_bytes;
432 fseek(infile, 0, SEEK_SET);
435 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))
438 encoder_wrapper.verify_fifo.into_frames = true;
440 while(!feof(infile)) {
441 if(lookahead_length > 0) {
442 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
443 memcpy(ucbuffer, lookahead, lookahead_length);
444 bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
446 fprintf(stderr, "ERROR reading from %s\n", infilename);
449 lookahead_length = 0;
452 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
454 if(bytes_read == 0) {
456 fprintf(stderr, "ERROR reading from %s\n", infilename);
460 else if(bytes_read % bytes_per_wide_sample != 0) {
461 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infilename);
465 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
466 format_input(wide_samples, is_big_endian, is_unsigned_samples, channels, bps, &encoder_wrapper);
468 /* 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: */
469 if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
470 fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
476 if(encoder_wrapper.encoder) {
477 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
478 FLAC__encoder_finish(encoder_wrapper.encoder);
479 FLAC__encoder_free_instance(encoder_wrapper.encoder);
481 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
482 print_stats(&encoder_wrapper);
483 fprintf(stderr, "\n");
485 if(0 != encoder_wrapper.seek_table.points)
486 free(encoder_wrapper.seek_table.points);
488 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
489 fprintf(stderr, "%s: Verify FAILED! (%s) Do not trust %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
492 else if(encoder_wrapper.verbose) {
493 fprintf(stderr, "%s: Verify succeeded\n", infilename);
500 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
501 fprintf(stderr, "\n");
502 if(encoder_wrapper.encoder) {
503 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
504 FLAC__encoder_finish(encoder_wrapper.encoder);
505 FLAC__encoder_free_instance(encoder_wrapper.encoder);
507 if(0 != encoder_wrapper.seek_table.points)
508 free(encoder_wrapper.seek_table.points);
510 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
511 fprintf(stderr, "%s: Verify FAILED! (%s) Do not trust %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
514 else if(encoder_wrapper.verbose) {
515 fprintf(stderr, "%s: Verify succeeded\n", infilename);
524 bool init(encoder_wrapper_struct *encoder_wrapper)
529 is_big_endian_host = (*((byte*)(&test)))? false : true;
531 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
532 input[i] = &(in[i][0]);
534 encoder_wrapper->encoder = FLAC__encoder_get_new_instance();
535 if(0 == encoder_wrapper->encoder) {
536 fprintf(stderr, "ERROR creating the encoder instance\n");
543 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)
548 do_mid_side = loose_mid_side = false;
550 if(encoder_wrapper->verify) {
551 /* set up the fifo which will hold the original signal to compare against */
552 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
553 for(i = 0; i < channels; i++) {
554 if(0 == (encoder_wrapper->verify_fifo.original[i] = (int32*)malloc(sizeof(int32) * encoder_wrapper->verify_fifo.size))) {
555 fprintf(stderr, "ERROR allocating verify buffers\n");
559 encoder_wrapper->verify_fifo.tail = 0;
560 encoder_wrapper->verify_fifo.into_frames = false;
561 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
563 /* set up a stream decoder for verification */
564 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_get_new_instance();
565 if(0 == encoder_wrapper->verify_fifo.decoder) {
566 fprintf(stderr, "ERROR creating the verify decoder instance\n");
569 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) {
570 fprintf(stderr, "ERROR initializing decoder, state = %d:%s\n", encoder_wrapper->verify_fifo.decoder->state, FLAC__StreamDecoderStateString[encoder_wrapper->verify_fifo.decoder->state]);
575 if(!convert_to_seek_table(requested_seek_points, num_requested_seek_points, encoder_wrapper->total_samples_to_encode, blocksize, &encoder_wrapper->seek_table)) {
576 fprintf(stderr, "ERROR allocating seek table\n");
580 encoder_wrapper->encoder->streamable_subset = !lax;
581 encoder_wrapper->encoder->channels = channels;
582 encoder_wrapper->encoder->bits_per_sample = bps;
583 encoder_wrapper->encoder->sample_rate = sample_rate;
584 encoder_wrapper->encoder->blocksize = blocksize;
585 encoder_wrapper->encoder->qlp_coeff_precision = qlp_coeff_precision;
586 encoder_wrapper->encoder->max_lpc_order = max_lpc_order;
587 encoder_wrapper->encoder->do_mid_side_stereo = do_mid_side;
588 encoder_wrapper->encoder->loose_mid_side_stereo = loose_mid_side;
589 encoder_wrapper->encoder->do_exhaustive_model_search = do_exhaustive_model_search;
590 encoder_wrapper->encoder->do_qlp_coeff_prec_search = do_qlp_coeff_prec_search;
591 encoder_wrapper->encoder->min_residual_partition_order = min_residual_partition_order;
592 encoder_wrapper->encoder->max_residual_partition_order = max_residual_partition_order;
593 encoder_wrapper->encoder->rice_parameter_search_dist = rice_parameter_search_dist;
594 encoder_wrapper->encoder->total_samples_estimate = encoder_wrapper->total_samples_to_encode;
595 encoder_wrapper->encoder->seek_table = (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0;
596 encoder_wrapper->encoder->padding = padding;
598 if(FLAC__encoder_init(encoder_wrapper->encoder, write_callback, metadata_callback, encoder_wrapper) != FLAC__ENCODER_OK) {
599 fprintf(stderr, "ERROR initializing encoder, state = %d:%s\n", encoder_wrapper->encoder->state, FLAC__EncoderStateString[encoder_wrapper->encoder->state]);
603 /* the above call writes all the metadata, so we save the stream offset now */
604 encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
609 bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table)
611 unsigned i, j, real_points, placeholders;
612 char *pt = requested_seek_points, *q;
615 seek_table->num_points = 0;
617 if(num_requested_seek_points == 0)
620 if(num_requested_seek_points < 0) {
621 strcpy(requested_seek_points, "100x<");
622 num_requested_seek_points = 1;
625 /* first count how many individual seek point we may need */
626 real_points = placeholders = 0;
627 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
629 FLAC__ASSERT(0 != q);
632 if(0 == strcmp(pt, "X")) { /* -S X */
635 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
636 if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
637 real_points += (unsigned)atoi(pt);
646 pt = requested_seek_points;
648 /* make some space */
649 if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
652 /* initialize the seek_table. we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
653 for(i = 0; i < real_points+placeholders; i++) {
654 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
655 seek_table->points[i].stream_offset = 0;
656 seek_table->points[i].frame_samples = 0;
659 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
661 FLAC__ASSERT(0 != q);
664 if(0 == strcmp(pt, "X")) { /* -S X */
665 ; /* we append placeholders later */
667 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
668 if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
670 n = (unsigned)atoi(pt);
671 for(j = 0; j < n; j++)
672 append_point_to_seek_table(seek_table, stream_samples * (uint64)j / (uint64)n, stream_samples, blocksize);
676 append_point_to_seek_table(seek_table, (uint64)atoi(pt), stream_samples, blocksize);
682 /* sort the seekpoints */
683 qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
685 /* uniqify the seekpoints */
687 for(i = j = 0; i < seek_table->num_points; i++) {
689 if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
693 seek_table->points[j++] = seek_table->points[i];
695 seek_table->num_points = j;
697 /* append placeholders */
698 for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
699 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
700 seek_table->num_points += placeholders;
705 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize)
707 const uint64 target_sample = (sample / blocksize) * blocksize;
709 if(stream_samples == 0 || target_sample < stream_samples)
710 seek_table->points[seek_table->num_points++].sample_number = target_sample;
713 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
715 /* we don't just 'return l->sample_number - r->sample_number' since the result (int64) might overflow an 'int' */
716 if(l->sample_number == r->sample_number)
718 else if(l->sample_number < r->sample_number)
724 void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
726 unsigned wide_sample, sample, channel, byte;
729 if(is_unsigned_samples) {
730 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
731 for(channel = 0; channel < channels; channel++, sample++)
732 input[channel][wide_sample] = (int32)ucbuffer[sample] - 0x80;
735 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
736 for(channel = 0; channel < channels; channel++, sample++)
737 input[channel][wide_sample] = (int32)scbuffer[sample];
741 if(is_big_endian != is_big_endian_host) {
743 const unsigned bytes = wide_samples * channels * (bps >> 3);
744 for(byte = 0; byte < bytes; byte += 2) {
745 tmp = ucbuffer[byte];
746 ucbuffer[byte] = ucbuffer[byte+1];
747 ucbuffer[byte+1] = tmp;
750 if(is_unsigned_samples) {
751 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
752 for(channel = 0; channel < channels; channel++, sample++)
753 input[channel][wide_sample] = (int32)usbuffer[sample] - 0x8000;
756 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
757 for(channel = 0; channel < channels; channel++, sample++)
758 input[channel][wide_sample] = (int32)ssbuffer[sample];
764 const unsigned bytes = wide_samples * channels * (bps >> 3);
765 for(byte = 0; byte < bytes; byte += 3) {
766 tmp = ucbuffer[byte];
767 ucbuffer[byte] = ucbuffer[byte+2];
768 ucbuffer[byte+2] = tmp;
771 if(is_unsigned_samples) {
772 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
773 for(channel = 0; channel < channels; channel++, sample++) {
774 input[channel][wide_sample] = ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
775 input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
776 input[channel][wide_sample] |= ucbuffer[byte++];
777 input[channel][wide_sample] -= 0x800000;
781 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
782 for(channel = 0; channel < channels; channel++, sample++) {
783 input[channel][wide_sample] = scbuffer[byte++]; input[channel][wide_sample] <<= 8;
784 input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
785 input[channel][wide_sample] |= ucbuffer[byte++];
793 if(encoder_wrapper->verify) {
794 for(channel = 0; channel < channels; channel++)
795 memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], &input[channel][0], sizeof(int32) * wide_samples);
796 encoder_wrapper->verify_fifo.tail += wide_samples;
797 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
801 FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
803 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
804 unsigned mask = (encoder->do_exhaustive_model_search || encoder->do_qlp_coeff_prec_search)? 0x1f : 0x7f;
806 /* 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) */
807 if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
808 uint64 current_sample = (uint64)current_frame * (uint64)encoder->blocksize, test_sample;
810 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
811 test_sample = encoder_wrapper->seek_table.points[i].sample_number;
812 if(test_sample > current_sample) {
815 else if(test_sample == current_sample) {
816 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
817 encoder_wrapper->seek_table.points[i].frame_samples = encoder->blocksize;
818 encoder_wrapper->first_seek_point_to_check++;
822 encoder_wrapper->first_seek_point_to_check++;
827 encoder_wrapper->bytes_written += bytes;
828 encoder_wrapper->samples_written += samples;
829 encoder_wrapper->current_frame = current_frame;
831 if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
832 print_stats(encoder_wrapper);
834 if(encoder_wrapper->verify) {
835 encoder_wrapper->verify_fifo.encoded_signal = buffer;
836 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
837 if(encoder_wrapper->verify_fifo.into_frames) {
838 if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
839 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
840 return FLAC__ENCODER_WRITE_FATAL_ERROR;
844 if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
845 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
846 return FLAC__ENCODER_WRITE_FATAL_ERROR;
851 if(fwrite(buffer, sizeof(byte), bytes, encoder_wrapper->fout) == bytes)
852 return FLAC__ENCODER_WRITE_OK;
854 return FLAC__ENCODER_WRITE_FATAL_ERROR;
857 void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
859 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
862 const uint64 samples = metadata->data.stream_info.total_samples;
863 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
864 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
866 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
869 * we get called by the encoder when the encoding process has
870 * finished so that we can update the STREAMINFO and SEEKTABLE
874 (void)encoder; /* silence compiler warning about unused parameter */
876 if(encoder_wrapper->fout == stdout)
879 fclose(encoder_wrapper->fout);
880 if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
883 /* all this is based on intimate knowledge of the stream header
884 * layout, but a change to the header format that would break this
885 * would also break all streams encoded in the previous format.
888 if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
889 fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
892 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
893 if(fread(&b, 1, 1, f) != 1) goto framesize_;
894 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
895 b = (b & 0xf0) | (byte)((samples >> 32) & 0x0F);
896 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
897 b = (byte)((samples >> 24) & 0xFF);
898 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
899 b = (byte)((samples >> 16) & 0xFF);
900 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
901 b = (byte)((samples >> 8) & 0xFF);
902 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
903 b = (byte)(samples & 0xFF);
904 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
907 if(-1 == fseek(f, 12, SEEK_SET)) goto seektable_;
908 b = (byte)((min_framesize >> 16) & 0xFF);
909 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
910 b = (byte)((min_framesize >> 8) & 0xFF);
911 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
912 b = (byte)(min_framesize & 0xFF);
913 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
914 b = (byte)((max_framesize >> 16) & 0xFF);
915 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
916 b = (byte)((max_framesize >> 8) & 0xFF);
917 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
918 b = (byte)(max_framesize & 0xFF);
919 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
922 if(encoder_wrapper->seek_table.num_points > 0) {
926 /* convert any unused seek points to placeholders */
927 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
928 if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
930 else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
931 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
934 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
935 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
936 pos += metadata->length;
937 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
938 if(-1 == fseek(f, pos, SEEK_SET)) goto end_;
939 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
940 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
941 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
942 if(!write_big_endian_uint16(f, encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
951 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
953 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
954 const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
957 if(encoded_bytes <= *bytes) {
958 *bytes = encoded_bytes;
959 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
962 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
963 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
964 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
967 return FLAC__STREAM_DECODER_READ_CONTINUE;
970 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
972 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
973 unsigned channel, l, r;
975 for(channel = 0; channel < decoder->channels; channel++) {
976 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], sizeof(int32) * decoder->blocksize)) {
977 fprintf(stderr, "\nERROR: mismatch in decoded data, verify FAILED!\n");
978 fprintf(stderr, " Please submit a bug report to\n");
979 fprintf(stderr, " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
980 fprintf(stderr, " Make sure to include an email contact in the comment and/or use the\n");
981 fprintf(stderr, " \"Monitor\" feature to monitor the bug status.\n");
982 return FLAC__STREAM_DECODER_WRITE_ABORT;
985 /* dequeue the frame from the fifo */
986 for(channel = 0; channel < decoder->channels; channel++) {
987 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
988 encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
991 encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
992 return FLAC__STREAM_DECODER_WRITE_CONTINUE;
995 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
1002 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1006 fprintf(stderr, "\nERROR: verification decoder returned error %d:%s\n", status, FLAC__StreamDecoderErrorStatusString[status]);
1009 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1012 /* with VC++ you have to spoon feed it the casting */
1013 double progress = (double)(int64)encoder_wrapper->samples_written / (double)(int64)encoder_wrapper->total_samples_to_encode;
1015 double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1017 fprintf(stderr, "\r%0.2f%% complete: frame %u, wrote %u bytes (%u/%u samples), r=%5.3f",
1018 progress * 100.0, encoder_wrapper->current_frame,
1019 (unsigned)encoder_wrapper->bytes_written, (unsigned)encoder_wrapper->samples_written, (unsigned)encoder_wrapper->total_samples_to_encode,
1021 /* with VC++ you have to spoon feed it the casting */
1022 (double)(int64)encoder_wrapper->bytes_written / ((double)(int64)encoder_wrapper->unencoded_size * progress)
1024 (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress)
1029 bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok)
1031 size_t bytes_read = fread(val, 1, 2, f);
1033 if(bytes_read == 0) {
1035 fprintf(stderr, "ERROR: unexpected EOF\n");
1041 else if(bytes_read < 2) {
1042 fprintf(stderr, "ERROR: unexpected EOF\n");
1046 if(is_big_endian_host) {
1047 byte tmp, *b = (byte*)val;
1048 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1054 bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok)
1056 size_t bytes_read = fread(val, 1, 4, f);
1058 if(bytes_read == 0) {
1060 fprintf(stderr, "ERROR: unexpected EOF\n");
1066 else if(bytes_read < 4) {
1067 fprintf(stderr, "ERROR: unexpected EOF\n");
1071 if(is_big_endian_host) {
1072 byte tmp, *b = (byte*)val;
1073 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1074 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1080 bool write_big_endian_uint16(FILE *f, uint16 val)
1082 if(!is_big_endian_host) {
1083 byte *b = (byte *)&val, tmp;
1084 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1086 return fwrite(&val, 1, 2, f) == 2;
1089 bool write_big_endian_uint64(FILE *f, uint64 val)
1091 if(!is_big_endian_host) {
1092 byte *b = (byte *)&val, tmp;
1093 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1094 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1095 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1096 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1098 return fwrite(&val, 1, 8, f) == 8;