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 */
22 #if defined _WIN32 && !defined __CYGWIN__
23 /* where MSVC puts unlink() */
28 #include <stdio.h> /* for FILE et al. */
29 #include <stdlib.h> /* for malloc */
30 #include <string.h> /* for strcmp() */
37 #define min(x,y) ((x)<(y)?(x):(y))
39 #define CHUNK_OF_SAMPLES 2048
43 FLAC__VERIFY_FAILED_IN_FRAME,
44 FLAC__VERIFY_FAILED_IN_METADATA
47 static const char *verify_code_string[] = {
49 "FLAC__VERIFY_FAILED_IN_FRAME",
50 "FLAC__VERIFY_FAILED_IN_METADATA"
54 int32 *original[FLAC__MAX_CHANNELS];
55 unsigned size; /* of each original[] in samples */
56 unsigned tail; /* in wide samples */
57 const byte *encoded_signal;
58 unsigned encoded_signal_capacity;
59 unsigned encoded_bytes;
62 FLAC__StreamDecoder *decoder;
67 const char *outfilename;
68 FLAC__Encoder *encoder;
71 uint64 unencoded_size;
72 uint64 total_samples_to_encode;
74 uint64 samples_written;
75 uint64 stream_offset; /* i.e. number of bytes before the first byte of the the first frame's header */
76 unsigned current_frame;
77 verify_fifo_struct verify_fifo;
78 FLAC__StreamMetaData_SeekTable seek_table;
79 unsigned first_seek_point_to_check;
80 } encoder_wrapper_struct;
82 static bool is_big_endian_host;
84 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__MAX_BITS_PER_SAMPLE+7)/8)];
85 static signed char *scbuffer = (signed char *)ucbuffer;
86 static uint16 *usbuffer = (uint16 *)ucbuffer;
87 static int16 *ssbuffer = (int16 *)ucbuffer;
89 static int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
90 static int32 *input[FLAC__MAX_CHANNELS];
93 static bool init(encoder_wrapper_struct *encoder_wrapper);
94 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);
95 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);
96 static void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize);
97 static int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r);
98 static void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
99 static FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
100 static void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
101 static FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data);
102 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data);
103 static void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
104 static void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
105 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
106 static bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok);
107 static bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok);
108 static bool write_big_endian_uint16(FILE *f, uint16 val);
109 static bool write_big_endian_uint64(FILE *f, uint64 val);
111 int encode_wav(FILE *infile, const char *infilename, const char *outfilename, 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)
113 encoder_wrapper_struct encoder_wrapper;
114 bool is_unsigned_samples;
115 unsigned channels, bps, sample_rate, data_bytes;
116 size_t bytes_per_wide_sample, bytes_read;
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.outfilename = outfilename;
126 encoder_wrapper.seek_table.points = 0;
127 encoder_wrapper.first_seek_point_to_check = 0;
129 if(0 == strcmp(outfilename, "-")) {
130 encoder_wrapper.fout = stdout;
133 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
134 fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
140 if(!init(&encoder_wrapper))
144 * check the RIFF chunk
146 if(!read_little_endian_uint32(infile, &xx, false))
148 if(xx != 0x46464952) { /* "RIFF" */
149 fprintf(stderr, "ERROR: no RIFF header\n");
152 if(!read_little_endian_uint32(infile, &xx, false))
156 * now process the WAVE chunk
158 if(!read_little_endian_uint32(infile, &xx, true))
160 if(xx != 0x45564157) { /* "WAVE" */
161 fprintf(stderr, "ERROR: no WAVE header\n");
165 /* do the format sub-chunk */
166 if(!read_little_endian_uint32(infile, &xx, false))
168 if(xx != 0x20746d66) { /* "fmt " */
169 fprintf(stderr, "ERROR: no format sub-chunk\n");
173 if(!read_little_endian_uint32(infile, &xx, false))
176 fprintf(stderr, "ERROR: unsupported chunk\n");
179 /* compression code */
180 if(!read_little_endian_uint16(infile, &x, false))
183 fprintf(stderr, "ERROR: unsupported compression type %u\n", (unsigned)x);
186 /* number of channels */
187 if(!read_little_endian_uint16(infile, &x, false))
189 if(x == 0 || x > FLAC__MAX_CHANNELS) {
190 fprintf(stderr, "ERROR: unsupported number channels %u\n", (unsigned)x);
195 if(!read_little_endian_uint32(infile, &xx, false))
197 if(xx == 0 || xx > FLAC__MAX_SAMPLE_RATE) {
198 fprintf(stderr, "ERROR: unsupported sample rate %u\n", (unsigned)xx);
202 /* avg bytes per second (ignored) */
203 if(!read_little_endian_uint32(infile, &xx, false))
205 /* block align (ignored) */
206 if(!read_little_endian_uint16(infile, &x, false))
208 /* bits per sample */
209 if(!read_little_endian_uint16(infile, &x, false))
211 if(x != 8 && x != 16) {
212 fprintf(stderr, "ERROR: unsupported bits per sample %u\n", (unsigned)x);
216 is_unsigned_samples = (x == 8);
218 /* do the data sub-chunk */
219 if(!read_little_endian_uint32(infile, &xx, false))
221 if(xx != 0x61746164) { /* "data" */
222 fprintf(stderr, "ERROR: no data sub-chunk\n");
226 if(!read_little_endian_uint32(infile, &xx, false))
230 bytes_per_wide_sample = channels * (bps >> 3);
233 if(infile != stdin) {
234 if(-1 == fseek(infile, bytes_per_wide_sample * (unsigned)skip, SEEK_CUR)) {
235 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
242 for(left = (int64)skip; left > 0; left -= CHUNK_OF_SAMPLES) {
243 need = min(left, CHUNK_OF_SAMPLES);
244 if(fread(ucbuffer, 1, bytes_per_wide_sample * need, infile) < need) {
245 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
252 encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample - skip;
253 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44; /* 44 for the size of the WAV headers */
255 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))
258 encoder_wrapper.verify_fifo.into_frames = true;
260 while(data_bytes > 0) {
261 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
262 if(bytes_read == 0) {
264 fprintf(stderr, "ERROR reading from %s\n", infilename);
267 else if(feof(infile))
271 if(bytes_read > data_bytes)
272 bytes_read = data_bytes; /* chop off anything after the end of the data chunk */
273 if(bytes_read % bytes_per_wide_sample != 0) {
274 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infilename);
278 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
279 format_input(wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
281 /* 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: */
282 if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
283 fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
286 data_bytes -= bytes_read;
292 if(encoder_wrapper.encoder) {
293 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
294 FLAC__encoder_finish(encoder_wrapper.encoder);
295 FLAC__encoder_free_instance(encoder_wrapper.encoder);
297 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
298 print_stats(&encoder_wrapper);
299 fprintf(stderr, "\n");
301 if(0 != encoder_wrapper.seek_table.points)
302 free(encoder_wrapper.seek_table.points);
304 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
305 fprintf(stderr, "%s: Verify FAILED! (%s) Do not use %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
308 else if(encoder_wrapper.verbose) {
309 fprintf(stderr, "%s: Verify succeeded\n", infilename);
316 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
317 fprintf(stderr, "\n");
318 if(encoder_wrapper.encoder) {
319 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
320 FLAC__encoder_finish(encoder_wrapper.encoder);
321 FLAC__encoder_free_instance(encoder_wrapper.encoder);
323 if(0 != encoder_wrapper.seek_table.points)
324 free(encoder_wrapper.seek_table.points);
326 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
327 fprintf(stderr, "%s: Verify FAILED! (%s) Do not use %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
330 else if(encoder_wrapper.verbose) {
331 fprintf(stderr, "%s: Verify succeeded\n", infilename);
340 int encode_raw(FILE *infile, const char *infilename, const char *outfilename, 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)
342 encoder_wrapper_struct encoder_wrapper;
344 const size_t bytes_per_wide_sample = channels * (bps >> 3);
346 encoder_wrapper.encoder = 0;
347 encoder_wrapper.verify = verify;
348 encoder_wrapper.verbose = verbose;
349 encoder_wrapper.bytes_written = 0;
350 encoder_wrapper.samples_written = 0;
351 encoder_wrapper.outfilename = outfilename;
352 encoder_wrapper.seek_table.points = 0;
353 encoder_wrapper.first_seek_point_to_check = 0;
355 if(0 == strcmp(outfilename, "-")) {
356 encoder_wrapper.fout = stdout;
359 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
360 fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
366 if(!init(&encoder_wrapper))
369 /* get the file length */
370 if(0 != fseek(infile, 0, SEEK_END)) {
371 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
376 if(-1 == (filesize = ftell(infile))) {
377 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
380 encoder_wrapper.unencoded_size = filesize - skip * bytes_per_wide_sample;
381 encoder_wrapper.total_samples_to_encode = filesize / bytes_per_wide_sample - skip;
385 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
386 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
389 if(infile != stdin) {
390 if(-1 == fseek(infile, bytes_per_wide_sample * (unsigned)skip, SEEK_SET)) {
391 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
398 for(left = (int64)skip; left > 0; left -= CHUNK_OF_SAMPLES) {
399 need = min(left, CHUNK_OF_SAMPLES);
400 if(fread(ucbuffer, 1, bytes_per_wide_sample * need, infile) < need) {
401 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infilename);
408 fseek(infile, 0, SEEK_SET);
411 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))
414 encoder_wrapper.verify_fifo.into_frames = true;
416 while(!feof(infile)) {
417 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
418 if(bytes_read == 0) {
420 fprintf(stderr, "ERROR reading from %s\n", infilename);
424 else if(bytes_read % bytes_per_wide_sample != 0) {
425 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infilename);
429 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
430 format_input(wide_samples, is_big_endian, is_unsigned_samples, channels, bps, &encoder_wrapper);
432 /* 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: */
433 if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
434 fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
440 if(encoder_wrapper.encoder) {
441 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
442 FLAC__encoder_finish(encoder_wrapper.encoder);
443 FLAC__encoder_free_instance(encoder_wrapper.encoder);
445 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
446 print_stats(&encoder_wrapper);
447 fprintf(stderr, "\n");
449 if(0 != encoder_wrapper.seek_table.points)
450 free(encoder_wrapper.seek_table.points);
452 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
453 fprintf(stderr, "%s: Verify FAILED! (%s) Do not use %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
456 else if(encoder_wrapper.verbose) {
457 fprintf(stderr, "%s: Verify succeeded\n", infilename);
464 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
465 fprintf(stderr, "\n");
466 if(encoder_wrapper.encoder) {
467 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
468 FLAC__encoder_finish(encoder_wrapper.encoder);
469 FLAC__encoder_free_instance(encoder_wrapper.encoder);
471 if(0 != encoder_wrapper.seek_table.points)
472 free(encoder_wrapper.seek_table.points);
474 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
475 fprintf(stderr, "%s: Verify FAILED! (%s) Do not use %s\n", infilename, verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
478 else if(encoder_wrapper.verbose) {
479 fprintf(stderr, "%s: Verify succeeded\n", infilename);
488 bool init(encoder_wrapper_struct *encoder_wrapper)
493 is_big_endian_host = (*((byte*)(&test)))? false : true;
495 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
496 input[i] = &(in[i][0]);
498 encoder_wrapper->encoder = FLAC__encoder_get_new_instance();
499 if(0 == encoder_wrapper->encoder) {
500 fprintf(stderr, "ERROR creating the encoder instance\n");
507 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)
512 do_mid_side = loose_mid_side = false;
514 if(encoder_wrapper->verify) {
515 /* set up the fifo which will hold the original signal to compare against */
516 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
517 for(i = 0; i < channels; i++) {
518 if(0 == (encoder_wrapper->verify_fifo.original[i] = (int32*)malloc(sizeof(int32) * encoder_wrapper->verify_fifo.size))) {
519 fprintf(stderr, "ERROR allocating verify buffers\n");
523 encoder_wrapper->verify_fifo.tail = 0;
524 encoder_wrapper->verify_fifo.into_frames = false;
525 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
527 /* set up a stream decoder for verification */
528 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_get_new_instance();
529 if(0 == encoder_wrapper->verify_fifo.decoder) {
530 fprintf(stderr, "ERROR creating the verify decoder instance\n");
533 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) {
534 fprintf(stderr, "ERROR initializing decoder, state = %d:%s\n", encoder_wrapper->verify_fifo.decoder->state, FLAC__StreamDecoderStateString[encoder_wrapper->verify_fifo.decoder->state]);
539 if(!convert_to_seek_table(requested_seek_points, num_requested_seek_points, encoder_wrapper->total_samples_to_encode, blocksize, &encoder_wrapper->seek_table)) {
540 fprintf(stderr, "ERROR allocating seek table\n");
544 encoder_wrapper->encoder->streamable_subset = !lax;
545 encoder_wrapper->encoder->channels = channels;
546 encoder_wrapper->encoder->bits_per_sample = bps;
547 encoder_wrapper->encoder->sample_rate = sample_rate;
548 encoder_wrapper->encoder->blocksize = blocksize;
549 encoder_wrapper->encoder->qlp_coeff_precision = qlp_coeff_precision;
550 encoder_wrapper->encoder->max_lpc_order = max_lpc_order;
551 encoder_wrapper->encoder->do_mid_side_stereo = do_mid_side;
552 encoder_wrapper->encoder->loose_mid_side_stereo = loose_mid_side;
553 encoder_wrapper->encoder->do_exhaustive_model_search = do_exhaustive_model_search;
554 encoder_wrapper->encoder->do_qlp_coeff_prec_search = do_qlp_coeff_prec_search;
555 encoder_wrapper->encoder->min_residual_partition_order = min_residual_partition_order;
556 encoder_wrapper->encoder->max_residual_partition_order = max_residual_partition_order;
557 encoder_wrapper->encoder->rice_parameter_search_dist = rice_parameter_search_dist;
558 encoder_wrapper->encoder->total_samples_estimate = encoder_wrapper->total_samples_to_encode;
559 encoder_wrapper->encoder->seek_table = (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0;
560 encoder_wrapper->encoder->padding = padding;
562 if(FLAC__encoder_init(encoder_wrapper->encoder, write_callback, metadata_callback, encoder_wrapper) != FLAC__ENCODER_OK) {
563 fprintf(stderr, "ERROR initializing encoder, state = %d:%s\n", encoder_wrapper->encoder->state, FLAC__EncoderStateString[encoder_wrapper->encoder->state]);
567 /* the above call write all the metadata, so we save the stream offset now */
568 encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
573 bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table)
575 unsigned i, j, real_points, placeholders;
576 char *pt = requested_seek_points, *q;
579 seek_table->num_points = 0;
581 if(num_requested_seek_points == 0)
584 if(num_requested_seek_points < 0) {
585 strcpy(requested_seek_points, "100x<");
586 num_requested_seek_points = 1;
589 /* first count how many individual seek point we may need */
590 real_points = placeholders = 0;
591 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
596 if(0 == strcmp(pt, "X")) { /* -S X */
599 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
600 if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
601 real_points += (unsigned)atoi(pt);
610 pt = requested_seek_points;
612 /* make some space */
613 if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
616 /* initialize the seek_table. we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
617 for(i = 0; i < real_points+placeholders; i++) {
618 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
619 seek_table->points[i].stream_offset = 0;
620 seek_table->points[i].frame_samples = 0;
623 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
628 if(0 == strcmp(pt, "X")) { /* -S X */
629 ; /* we append placeholders later */
631 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
632 if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
634 n = (unsigned)atoi(pt);
635 for(j = 0; j < n; j++)
636 append_point_to_seek_table(seek_table, stream_samples * (uint64)j / (uint64)n, stream_samples, blocksize);
640 append_point_to_seek_table(seek_table, (uint64)atoi(pt), stream_samples, blocksize);
646 /* sort the seekpoints */
647 qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
649 /* uniqify the seekpoints */
651 for(i = j = 0; i < seek_table->num_points; i++) {
653 if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
657 seek_table->points[j++] = seek_table->points[i];
659 seek_table->num_points = j;
661 /* append placeholders */
662 for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
663 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
664 seek_table->num_points += placeholders;
669 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize)
671 const uint64 target_sample = (sample / blocksize) * blocksize;
673 if(stream_samples == 0 || target_sample < stream_samples)
674 seek_table->points[seek_table->num_points++].sample_number = target_sample;
677 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
679 /* we don't just 'return l->sample_number - r->sample_number' since the result (int64) might overflow an 'int' */
680 if(l->sample_number == r->sample_number)
682 else if(l->sample_number < r->sample_number)
688 void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
690 unsigned wide_sample, sample, channel, byte;
693 if(is_unsigned_samples) {
694 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
695 for(channel = 0; channel < channels; channel++, sample++)
696 input[channel][wide_sample] = (int32)ucbuffer[sample] - 0x80;
699 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
700 for(channel = 0; channel < channels; channel++, sample++)
701 input[channel][wide_sample] = (int32)scbuffer[sample];
705 if(is_big_endian != is_big_endian_host) {
707 const unsigned bytes = wide_samples * channels * (bps >> 3);
708 for(byte = 0; byte < bytes; byte += 2) {
709 tmp = ucbuffer[byte];
710 ucbuffer[byte] = ucbuffer[byte+1];
711 ucbuffer[byte+1] = tmp;
714 if(is_unsigned_samples) {
715 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
716 for(channel = 0; channel < channels; channel++, sample++)
717 input[channel][wide_sample] = (int32)usbuffer[sample] - 0x8000;
720 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
721 for(channel = 0; channel < channels; channel++, sample++)
722 input[channel][wide_sample] = (int32)ssbuffer[sample];
728 const unsigned bytes = wide_samples * channels * (bps >> 3);
729 for(byte = 0; byte < bytes; byte += 3) {
730 tmp = ucbuffer[byte];
731 ucbuffer[byte] = ucbuffer[byte+2];
732 ucbuffer[byte+2] = tmp;
735 if(is_unsigned_samples) {
736 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
737 for(channel = 0; channel < channels; channel++, sample++) {
738 input[channel][wide_sample] = ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
739 input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
740 input[channel][wide_sample] |= ucbuffer[byte++];
741 input[channel][wide_sample] -= 0x800000;
745 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
746 for(channel = 0; channel < channels; channel++, sample++) {
747 input[channel][wide_sample] = scbuffer[byte++]; input[channel][wide_sample] <<= 8;
748 input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
749 input[channel][wide_sample] |= ucbuffer[byte++];
757 if(encoder_wrapper->verify) {
758 for(channel = 0; channel < channels; channel++)
759 memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], &input[channel][0], sizeof(int32) * wide_samples);
760 encoder_wrapper->verify_fifo.tail += wide_samples;
761 assert(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
765 FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
767 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
768 unsigned mask = (encoder->do_exhaustive_model_search || encoder->do_qlp_coeff_prec_search)? 0x07 : 0x1f;
770 /* 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) */
771 if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
772 uint64 current_sample = (uint64)current_frame * (uint64)encoder->blocksize, test_sample;
774 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
775 test_sample = encoder_wrapper->seek_table.points[i].sample_number;
776 if(test_sample > current_sample) {
779 else if(test_sample == current_sample) {
780 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
781 encoder_wrapper->seek_table.points[i].frame_samples = encoder->blocksize;
782 encoder_wrapper->first_seek_point_to_check++;
786 encoder_wrapper->first_seek_point_to_check++;
791 encoder_wrapper->bytes_written += bytes;
792 encoder_wrapper->samples_written += samples;
793 encoder_wrapper->current_frame = current_frame;
795 if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
796 print_stats(encoder_wrapper);
798 if(encoder_wrapper->verify) {
799 encoder_wrapper->verify_fifo.encoded_signal = buffer;
800 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
801 if(encoder_wrapper->verify_fifo.into_frames) {
802 if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
803 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
804 return FLAC__ENCODER_WRITE_FATAL_ERROR;
808 if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
809 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
810 return FLAC__ENCODER_WRITE_FATAL_ERROR;
815 if(fwrite(buffer, sizeof(byte), bytes, encoder_wrapper->fout) == bytes)
816 return FLAC__ENCODER_WRITE_OK;
818 return FLAC__ENCODER_WRITE_FATAL_ERROR;
821 void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
823 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
826 const uint64 samples = metadata->data.stream_info.total_samples;
827 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
828 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
830 assert(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
833 * we get called by the encoder when the encoding process has
834 * finished so that we can update the STREAMINFO and SEEKTABLE
838 (void)encoder; /* silence compiler warning about unused parameter */
840 if(encoder_wrapper->fout == stdout)
843 fclose(encoder_wrapper->fout);
844 if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
847 /* all this is based on intimate knowledge of the stream header
848 * layout, but a change to the header format that would break this
849 * would also break all streams encoded in the previous format.
852 if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
853 fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
856 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
857 if(fread(&b, 1, 1, f) != 1) goto framesize_;
858 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
859 b = (b & 0xf0) | (byte)((samples >> 32) & 0x0F);
860 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
861 b = (byte)((samples >> 24) & 0xFF);
862 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
863 b = (byte)((samples >> 16) & 0xFF);
864 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
865 b = (byte)((samples >> 8) & 0xFF);
866 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
867 b = (byte)(samples & 0xFF);
868 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
871 if(-1 == fseek(f, 12, SEEK_SET)) goto seektable_;
872 b = (byte)((min_framesize >> 16) & 0xFF);
873 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
874 b = (byte)((min_framesize >> 8) & 0xFF);
875 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
876 b = (byte)(min_framesize & 0xFF);
877 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
878 b = (byte)((max_framesize >> 16) & 0xFF);
879 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
880 b = (byte)((max_framesize >> 8) & 0xFF);
881 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
882 b = (byte)(max_framesize & 0xFF);
883 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
886 if(encoder_wrapper->seek_table.num_points > 0) {
890 /* convert any unused seek points to placeholders */
891 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
892 if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
894 else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
895 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
898 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
899 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
900 pos += metadata->length;
901 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
902 if(-1 == fseek(f, pos, SEEK_SET)) goto end_;
903 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
904 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
905 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
906 if(!write_big_endian_uint16(f, encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
915 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
917 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
918 const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
921 if(encoded_bytes <= *bytes) {
922 *bytes = encoded_bytes;
923 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
926 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
927 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
928 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
931 return FLAC__STREAM_DECODER_READ_CONTINUE;
934 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
936 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
937 unsigned channel, l, r;
939 for(channel = 0; channel < decoder->channels; channel++) {
940 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], sizeof(int32) * decoder->blocksize)) {
941 fprintf(stderr, "\nERROR: mismatch in decoded data, verify FAILED!\n");
942 fprintf(stderr, " Please submit a bug report to\n");
943 fprintf(stderr, " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
944 fprintf(stderr, " Make sure to include an email contact in the comment and/or use the\n");
945 fprintf(stderr, " \"Monitor\" feature to monitor the bug status.\n");
946 return FLAC__STREAM_DECODER_WRITE_ABORT;
949 /* dequeue the frame from the fifo */
950 for(channel = 0; channel < decoder->channels; channel++) {
951 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
952 encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
955 encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
956 return FLAC__STREAM_DECODER_WRITE_CONTINUE;
959 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
966 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
970 fprintf(stderr, "\nERROR: verification decoder returned error %d:%s\n", status, FLAC__StreamDecoderErrorStatusString[status]);
973 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
976 /* with VC++ you have to spoon feed it the casting */
977 double progress = (double)(int64)encoder_wrapper->samples_written / (double)(int64)encoder_wrapper->total_samples_to_encode;
979 double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
981 fprintf(stderr, "\r%0.2f%% complete: frame %u, wrote %u bytes, %u of %u samples, ratio = %5.3f",
982 progress * 100.0, encoder_wrapper->current_frame,
983 (unsigned)encoder_wrapper->bytes_written, (unsigned)encoder_wrapper->samples_written, (unsigned)encoder_wrapper->total_samples_to_encode,
985 /* with VC++ you have to spoon feed it the casting */
986 (double)(int64)encoder_wrapper->bytes_written / ((double)(int64)encoder_wrapper->unencoded_size * progress)
988 (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress)
993 bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok)
995 size_t bytes_read = fread(val, 1, 2, f);
997 if(bytes_read == 0) {
999 fprintf(stderr, "ERROR: unexpected EOF\n");
1005 else if(bytes_read < 2) {
1006 fprintf(stderr, "ERROR: unexpected EOF\n");
1010 if(is_big_endian_host) {
1011 byte tmp, *b = (byte*)val;
1012 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1018 bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok)
1020 size_t bytes_read = fread(val, 1, 4, f);
1022 if(bytes_read == 0) {
1024 fprintf(stderr, "ERROR: unexpected EOF\n");
1030 else if(bytes_read < 4) {
1031 fprintf(stderr, "ERROR: unexpected EOF\n");
1035 if(is_big_endian_host) {
1036 byte tmp, *b = (byte*)val;
1037 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1038 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1044 bool write_big_endian_uint16(FILE *f, uint16 val)
1046 if(!is_big_endian_host) {
1047 byte *b = (byte *)&val, tmp;
1048 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1050 return fwrite(&val, 1, 2, f) == 2;
1053 bool write_big_endian_uint64(FILE *f, uint64 val)
1055 if(!is_big_endian_host) {
1056 byte *b = (byte *)&val, tmp;
1057 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1058 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1059 tmp = b[2]; b[2] = b[5]; b[3] = tmp;
1060 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1062 return fwrite(&val, 1, 8, f) == 8;