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 encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample - skip;
244 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44; /* 44 for the size of the WAV headers */
246 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))
249 encoder_wrapper.verify_fifo.into_frames = true;
251 while(data_bytes > 0) {
252 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
253 if(bytes_read == 0) {
255 fprintf(stderr, "ERROR reading from %s\n", infilename);
258 else if(feof(infile))
262 if(bytes_read > data_bytes)
263 bytes_read = data_bytes; /* chop off anything after the end of the data sub-chunk */
264 if(bytes_read % bytes_per_wide_sample != 0) {
265 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infilename);
269 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
270 format_input(wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
272 /* 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: */
273 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
274 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)]);
277 data_bytes -= bytes_read;
281 got_data_chunk = true;
285 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));
287 if(!read_little_endian_uint32(infile, &xx, false))
289 if(infile != stdin) {
290 if(-1 == fseek(infile, xx, SEEK_CUR)) {
291 fprintf(stderr, "ERROR seeking ahead while skipping unsupported sub-chunk in input file %s\n", infilename);
297 const unsigned chunk = sizeof(ucbuffer);
298 for(left = xx; left > 0; ) {
299 need = min(left, chunk);
300 if(fread(ucbuffer, 1, need, infile) < need) {
301 fprintf(stderr, "ERROR seeking while skipping unsupported sub-chunk in input file %s\n", infilename);
310 if(encoder_wrapper.encoder) {
311 if(FLAC__stream_encoder_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
312 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
313 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
315 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
316 print_stats(&encoder_wrapper);
317 fprintf(stderr, "\n");
319 if(0 != encoder_wrapper.seek_table.points)
320 free(encoder_wrapper.seek_table.points);
322 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
323 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
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(FLAC__stream_encoder_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
340 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
341 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
343 if(0 != encoder_wrapper.seek_table.points)
344 free(encoder_wrapper.seek_table.points);
346 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
347 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
348 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
349 fprintf(stderr, "%s: Verify FAILED! (%s) Do not trust %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
352 else if(encoder_wrapper.verbose) {
353 fprintf(stderr, "%s: Verify succeeded\n", infilename);
362 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)
364 encoder_wrapper_struct encoder_wrapper;
366 const size_t bytes_per_wide_sample = channels * (bps >> 3);
368 encoder_wrapper.encoder = 0;
369 encoder_wrapper.verify = verify;
370 encoder_wrapper.verbose = verbose;
371 encoder_wrapper.bytes_written = 0;
372 encoder_wrapper.samples_written = 0;
373 encoder_wrapper.stream_offset = 0;
374 encoder_wrapper.outfilename = outfilename;
375 encoder_wrapper.seek_table.points = 0;
376 encoder_wrapper.first_seek_point_to_check = 0;
378 if(0 == strcmp(outfilename, "-")) {
379 encoder_wrapper.fout = stdout;
382 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
383 fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
389 if(!init(&encoder_wrapper))
392 /* get the file length */
394 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
397 encoder_wrapper.unencoded_size = (unsigned)infilesize - skip * bytes_per_wide_sample;
398 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - skip;
401 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
402 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
405 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)skip;
406 if(skip_bytes > lookahead_length) {
407 skip_bytes -= lookahead_length;
408 lookahead_length = 0;
409 if(infile != stdin) {
410 if(-1 == fseek(infile, (long)skip_bytes, SEEK_SET)) {
411 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
417 const unsigned chunk = sizeof(ucbuffer);
418 for(left = skip_bytes; left > 0; ) {
419 need = min(left, chunk);
420 if(fread(ucbuffer, 1, need, infile) < need) {
421 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
429 lookahead += skip_bytes;
430 lookahead_length -= skip_bytes;
434 fseek(infile, 0, SEEK_SET);
437 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))
440 encoder_wrapper.verify_fifo.into_frames = true;
442 while(!feof(infile)) {
443 if(lookahead_length > 0) {
444 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
445 memcpy(ucbuffer, lookahead, lookahead_length);
446 bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
448 fprintf(stderr, "ERROR reading from %s\n", infilename);
451 lookahead_length = 0;
454 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
456 if(bytes_read == 0) {
458 fprintf(stderr, "ERROR reading from %s\n", infilename);
462 else if(bytes_read % bytes_per_wide_sample != 0) {
463 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infilename);
467 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
468 format_input(wide_samples, is_big_endian, is_unsigned_samples, channels, bps, &encoder_wrapper);
470 /* 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: */
471 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
472 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)]);
478 if(encoder_wrapper.encoder) {
479 if(FLAC__stream_encoder_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
480 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
481 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
483 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
484 print_stats(&encoder_wrapper);
485 fprintf(stderr, "\n");
487 if(0 != encoder_wrapper.seek_table.points)
488 free(encoder_wrapper.seek_table.points);
490 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
491 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
492 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
493 fprintf(stderr, "%s: Verify FAILED! (%s) Do not trust %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
496 else if(encoder_wrapper.verbose) {
497 fprintf(stderr, "%s: Verify succeeded\n", infilename);
504 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
505 fprintf(stderr, "\n");
506 if(encoder_wrapper.encoder) {
507 if(FLAC__stream_encoder_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_OK)
508 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
509 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
511 if(0 != encoder_wrapper.seek_table.points)
512 free(encoder_wrapper.seek_table.points);
514 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
515 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
516 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
517 fprintf(stderr, "%s: Verify FAILED! (%s) Do not trust %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
520 else if(encoder_wrapper.verbose) {
521 fprintf(stderr, "%s: Verify succeeded\n", infilename);
530 bool init(encoder_wrapper_struct *encoder_wrapper)
535 is_big_endian_host = (*((byte*)(&test)))? false : true;
537 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
538 input[i] = &(in[i][0]);
540 encoder_wrapper->encoder = FLAC__stream_encoder_new();
541 if(0 == encoder_wrapper->encoder) {
542 fprintf(stderr, "ERROR creating the encoder instance\n");
549 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)
554 do_mid_side = loose_mid_side = false;
556 if(encoder_wrapper->verify) {
557 /* set up the fifo which will hold the original signal to compare against */
558 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
559 for(i = 0; i < channels; i++) {
560 if(0 == (encoder_wrapper->verify_fifo.original[i] = (int32*)malloc(sizeof(int32) * encoder_wrapper->verify_fifo.size))) {
561 fprintf(stderr, "ERROR allocating verify buffers\n");
565 encoder_wrapper->verify_fifo.tail = 0;
566 encoder_wrapper->verify_fifo.into_frames = false;
567 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
569 /* set up a stream decoder for verification */
570 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_new();
571 if(0 == encoder_wrapper->verify_fifo.decoder) {
572 fprintf(stderr, "ERROR creating the verify decoder instance\n");
575 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) {
576 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)]);
581 if(!convert_to_seek_table(requested_seek_points, num_requested_seek_points, encoder_wrapper->total_samples_to_encode, blocksize, &encoder_wrapper->seek_table)) {
582 fprintf(stderr, "ERROR allocating seek table\n");
586 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) {
587 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)]);
591 /* the above call writes all the metadata, so we save the stream offset now */
592 encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
597 bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table)
599 unsigned i, j, real_points, placeholders;
600 char *pt = requested_seek_points, *q;
603 seek_table->num_points = 0;
605 if(num_requested_seek_points == 0)
608 if(num_requested_seek_points < 0) {
609 strcpy(requested_seek_points, "100x<");
610 num_requested_seek_points = 1;
613 /* first count how many individual seek point we may need */
614 real_points = placeholders = 0;
615 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
617 FLAC__ASSERT(0 != q);
620 if(0 == strcmp(pt, "X")) { /* -S X */
623 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
624 if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
625 real_points += (unsigned)atoi(pt);
634 pt = requested_seek_points;
636 /* make some space */
637 if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
640 /* initialize the seek_table. we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
641 for(i = 0; i < real_points+placeholders; i++) {
642 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
643 seek_table->points[i].stream_offset = 0;
644 seek_table->points[i].frame_samples = 0;
647 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
649 FLAC__ASSERT(0 != q);
652 if(0 == strcmp(pt, "X")) { /* -S X */
653 ; /* we append placeholders later */
655 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
656 if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
658 n = (unsigned)atoi(pt);
659 for(j = 0; j < n; j++)
660 append_point_to_seek_table(seek_table, stream_samples * (uint64)j / (uint64)n, stream_samples, blocksize);
664 append_point_to_seek_table(seek_table, (uint64)atoi(pt), stream_samples, blocksize);
670 /* sort the seekpoints */
671 qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
673 /* uniqify the seekpoints */
675 for(i = j = 0; i < seek_table->num_points; i++) {
677 if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
681 seek_table->points[j++] = seek_table->points[i];
683 seek_table->num_points = j;
685 /* append placeholders */
686 for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
687 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
688 seek_table->num_points += placeholders;
693 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize)
695 const uint64 target_sample = (sample / blocksize) * blocksize;
697 if(stream_samples == 0 || target_sample < stream_samples)
698 seek_table->points[seek_table->num_points++].sample_number = target_sample;
701 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
703 /* we don't just 'return l->sample_number - r->sample_number' since the result (int64) might overflow an 'int' */
704 if(l->sample_number == r->sample_number)
706 else if(l->sample_number < r->sample_number)
712 void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
714 unsigned wide_sample, sample, channel, byte;
717 if(is_unsigned_samples) {
718 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
719 for(channel = 0; channel < channels; channel++, sample++)
720 input[channel][wide_sample] = (int32)ucbuffer[sample] - 0x80;
723 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
724 for(channel = 0; channel < channels; channel++, sample++)
725 input[channel][wide_sample] = (int32)scbuffer[sample];
729 if(is_big_endian != is_big_endian_host) {
731 const unsigned bytes = wide_samples * channels * (bps >> 3);
732 for(byte = 0; byte < bytes; byte += 2) {
733 tmp = ucbuffer[byte];
734 ucbuffer[byte] = ucbuffer[byte+1];
735 ucbuffer[byte+1] = tmp;
738 if(is_unsigned_samples) {
739 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
740 for(channel = 0; channel < channels; channel++, sample++)
741 input[channel][wide_sample] = (int32)usbuffer[sample] - 0x8000;
744 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
745 for(channel = 0; channel < channels; channel++, sample++)
746 input[channel][wide_sample] = (int32)ssbuffer[sample];
752 const unsigned bytes = wide_samples * channels * (bps >> 3);
753 for(byte = 0; byte < bytes; byte += 3) {
754 tmp = ucbuffer[byte];
755 ucbuffer[byte] = ucbuffer[byte+2];
756 ucbuffer[byte+2] = tmp;
759 if(is_unsigned_samples) {
760 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
761 for(channel = 0; channel < channels; channel++, sample++) {
762 input[channel][wide_sample] = ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
763 input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
764 input[channel][wide_sample] |= ucbuffer[byte++];
765 input[channel][wide_sample] -= 0x800000;
769 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
770 for(channel = 0; channel < channels; channel++, sample++) {
771 input[channel][wide_sample] = scbuffer[byte++]; input[channel][wide_sample] <<= 8;
772 input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
773 input[channel][wide_sample] |= ucbuffer[byte++];
781 if(encoder_wrapper->verify) {
782 for(channel = 0; channel < channels; channel++)
783 memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], &input[channel][0], sizeof(int32) * wide_samples);
784 encoder_wrapper->verify_fifo.tail += wide_samples;
785 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
789 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
791 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
792 const unsigned mask = (FLAC__stream_encoder_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
794 /* 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) */
795 if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
796 uint64 current_sample = (uint64)current_frame * (uint64)FLAC__stream_encoder_blocksize(encoder), test_sample;
798 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
799 test_sample = encoder_wrapper->seek_table.points[i].sample_number;
800 if(test_sample > current_sample) {
803 else if(test_sample == current_sample) {
804 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
805 encoder_wrapper->seek_table.points[i].frame_samples = FLAC__stream_encoder_blocksize(encoder);
806 encoder_wrapper->first_seek_point_to_check++;
810 encoder_wrapper->first_seek_point_to_check++;
815 encoder_wrapper->bytes_written += bytes;
816 encoder_wrapper->samples_written += samples;
817 encoder_wrapper->current_frame = current_frame;
819 if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
820 print_stats(encoder_wrapper);
822 if(encoder_wrapper->verify) {
823 encoder_wrapper->verify_fifo.encoded_signal = buffer;
824 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
825 if(encoder_wrapper->verify_fifo.into_frames) {
826 if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
827 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
828 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
832 if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
833 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
834 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
839 if(fwrite(buffer, sizeof(byte), bytes, encoder_wrapper->fout) == bytes)
840 return FLAC__STREAM_ENCODER_WRITE_OK;
842 return FLAC__STREAM_ENCODER_WRITE_FATAL_ERROR;
845 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
847 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
850 const uint64 samples = metadata->data.stream_info.total_samples;
851 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
852 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
854 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
857 * we get called by the encoder when the encoding process has
858 * finished so that we can update the STREAMINFO and SEEKTABLE
862 (void)encoder; /* silence compiler warning about unused parameter */
864 if(encoder_wrapper->fout == stdout)
867 fclose(encoder_wrapper->fout);
868 if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
871 /* all this is based on intimate knowledge of the stream header
872 * layout, but a change to the header format that would break this
873 * would also break all streams encoded in the previous format.
876 if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
877 fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
880 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
881 if(fread(&b, 1, 1, f) != 1) goto framesize_;
882 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
883 b = (b & 0xf0) | (byte)((samples >> 32) & 0x0F);
884 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
885 b = (byte)((samples >> 24) & 0xFF);
886 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
887 b = (byte)((samples >> 16) & 0xFF);
888 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
889 b = (byte)((samples >> 8) & 0xFF);
890 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
891 b = (byte)(samples & 0xFF);
892 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
895 if(-1 == fseek(f, 12, SEEK_SET)) goto seektable_;
896 b = (byte)((min_framesize >> 16) & 0xFF);
897 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
898 b = (byte)((min_framesize >> 8) & 0xFF);
899 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
900 b = (byte)(min_framesize & 0xFF);
901 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
902 b = (byte)((max_framesize >> 16) & 0xFF);
903 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
904 b = (byte)((max_framesize >> 8) & 0xFF);
905 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
906 b = (byte)(max_framesize & 0xFF);
907 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
910 if(encoder_wrapper->seek_table.num_points > 0) {
914 /* convert any unused seek points to placeholders */
915 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
916 if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
918 else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
919 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
922 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
923 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
924 pos += metadata->length;
925 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
926 if(-1 == fseek(f, pos, SEEK_SET)) goto end_;
927 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
928 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
929 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
930 if(!write_big_endian_uint16(f, encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
939 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
941 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
942 const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
945 if(encoded_bytes <= *bytes) {
946 *bytes = encoded_bytes;
947 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
950 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
951 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
952 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
955 return FLAC__STREAM_DECODER_READ_CONTINUE;
958 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
960 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
961 unsigned channel, l, r;
962 const unsigned channels = FLAC__stream_decoder_channels(decoder);
963 const unsigned bytes_per_block = sizeof(int32) * FLAC__stream_decoder_blocksize(decoder);
965 for(channel = 0; channel < channels; channel++) {
966 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], bytes_per_block)) {
967 fprintf(stderr, "\nERROR: mismatch in decoded data, verify FAILED!\n");
968 fprintf(stderr, " Please submit a bug report to\n");
969 fprintf(stderr, " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
970 fprintf(stderr, " Make sure to include an email contact in the comment and/or use the\n");
971 fprintf(stderr, " \"Monitor\" feature to monitor the bug status.\n");
972 return FLAC__STREAM_DECODER_WRITE_ABORT;
975 /* dequeue the frame from the fifo */
976 for(channel = 0; channel < channels; channel++) {
977 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
978 encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
981 encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
982 return FLAC__STREAM_DECODER_WRITE_CONTINUE;
985 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
992 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
996 fprintf(stderr, "\nERROR: verification decoder returned error %d:%s\n", status, FLAC__StreamDecoderErrorStatusString[status]);
999 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1002 /* with VC++ you have to spoon feed it the casting */
1003 double progress = (double)(int64)encoder_wrapper->samples_written / (double)(int64)encoder_wrapper->total_samples_to_encode;
1005 double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1007 fprintf(stderr, "\r%0.2f%% complete: frame %u, wrote %u bytes (%u/%u samples), r=%5.3f",
1008 progress * 100.0, encoder_wrapper->current_frame,
1009 (unsigned)encoder_wrapper->bytes_written, (unsigned)encoder_wrapper->samples_written, (unsigned)encoder_wrapper->total_samples_to_encode,
1011 /* with VC++ you have to spoon feed it the casting */
1012 (double)(int64)encoder_wrapper->bytes_written / ((double)(int64)encoder_wrapper->unencoded_size * progress)
1014 (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress)
1019 bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok)
1021 size_t bytes_read = fread(val, 1, 2, f);
1023 if(bytes_read == 0) {
1025 fprintf(stderr, "ERROR: unexpected EOF\n");
1031 else if(bytes_read < 2) {
1032 fprintf(stderr, "ERROR: unexpected EOF\n");
1036 if(is_big_endian_host) {
1037 byte tmp, *b = (byte*)val;
1038 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1044 bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok)
1046 size_t bytes_read = fread(val, 1, 4, f);
1048 if(bytes_read == 0) {
1050 fprintf(stderr, "ERROR: unexpected EOF\n");
1056 else if(bytes_read < 4) {
1057 fprintf(stderr, "ERROR: unexpected EOF\n");
1061 if(is_big_endian_host) {
1062 byte tmp, *b = (byte*)val;
1063 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1064 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1070 bool write_big_endian_uint16(FILE *f, uint16 val)
1072 if(!is_big_endian_host) {
1073 byte *b = (byte *)&val, tmp;
1074 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1076 return fwrite(&val, 1, 2, f) == 2;
1079 bool write_big_endian_uint64(FILE *f, uint64 val)
1081 if(!is_big_endian_host) {
1082 byte *b = (byte *)&val, tmp;
1083 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1084 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1085 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1086 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1088 return fwrite(&val, 1, 8, f) == 8;