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;
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 rice_optimization_level, 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(const char *infile, const char *outfile, 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 rice_optimization_level, 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;
115 bool is_unsigned_samples;
116 unsigned channels, bps, sample_rate, data_bytes;
117 size_t bytes_per_wide_sample, bytes_read;
121 encoder_wrapper.encoder = 0;
122 encoder_wrapper.verify = verify;
123 encoder_wrapper.verbose = verbose;
124 encoder_wrapper.bytes_written = 0;
125 encoder_wrapper.samples_written = 0;
126 encoder_wrapper.outfile = outfile;
127 encoder_wrapper.seek_table.points = 0;
128 encoder_wrapper.first_seek_point_to_check = 0;
130 if(0 == strcmp(infile, "-")) {
134 if(0 == (fin = fopen(infile, "rb"))) {
135 fprintf(stderr, "ERROR: can't open input file %s\n", infile);
139 if(0 == strcmp(outfile, "-")) {
140 encoder_wrapper.fout = stdout;
143 if(0 == (encoder_wrapper.fout = fopen(outfile, "wb"))) {
144 fprintf(stderr, "ERROR: can't open output file %s\n", outfile);
150 if(!init(&encoder_wrapper))
154 * check the RIFF chunk
156 if(!read_little_endian_uint32(fin, &xx, false))
158 if(xx != 0x46464952) { /* "RIFF" */
159 fprintf(stderr, "ERROR: no RIFF header\n");
162 if(!read_little_endian_uint32(fin, &xx, false))
166 * now process the WAVE chunk
168 if(!read_little_endian_uint32(fin, &xx, true))
170 if(xx != 0x45564157) { /* "WAVE" */
171 fprintf(stderr, "ERROR: no WAVE header\n");
175 /* do the format sub-chunk */
176 if(!read_little_endian_uint32(fin, &xx, false))
178 if(xx != 0x20746d66) { /* "fmt " */
179 fprintf(stderr, "ERROR: no format sub-chunk\n");
183 if(!read_little_endian_uint32(fin, &xx, false))
186 fprintf(stderr, "ERROR: unsupported chunk\n");
189 /* compression code */
190 if(!read_little_endian_uint16(fin, &x, false))
193 fprintf(stderr, "ERROR: unsupported compression type %u\n", (unsigned)x);
196 /* number of channels */
197 if(!read_little_endian_uint16(fin, &x, false))
199 if(x == 0 || x > FLAC__MAX_CHANNELS) {
200 fprintf(stderr, "ERROR: unsupported number channels %u\n", (unsigned)x);
205 if(!read_little_endian_uint32(fin, &xx, false))
207 if(xx == 0 || xx > FLAC__MAX_SAMPLE_RATE) {
208 fprintf(stderr, "ERROR: unsupported sample rate %u\n", (unsigned)xx);
212 /* avg bytes per second (ignored) */
213 if(!read_little_endian_uint32(fin, &xx, false))
215 /* block align (ignored) */
216 if(!read_little_endian_uint16(fin, &x, false))
218 /* bits per sample */
219 if(!read_little_endian_uint16(fin, &x, false))
221 if(x != 8 && x != 16) {
222 fprintf(stderr, "ERROR: unsupported bits per sample %u\n", (unsigned)x);
226 is_unsigned_samples = (x == 8);
228 /* do the data sub-chunk */
229 if(!read_little_endian_uint32(fin, &xx, false))
231 if(xx != 0x61746164) { /* "data" */
232 fprintf(stderr, "ERROR: no data sub-chunk\n");
236 if(!read_little_endian_uint32(fin, &xx, false))
240 bytes_per_wide_sample = channels * (bps >> 3);
244 if(-1 == fseek(fin, bytes_per_wide_sample * (unsigned)skip, SEEK_CUR)) {
245 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
252 for(left = (int64)skip; left > 0; left -= CHUNK_OF_SAMPLES) {
253 need = min(left, CHUNK_OF_SAMPLES);
254 if(fread(ucbuffer, 1, bytes_per_wide_sample * need, fin) < need) {
255 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
262 encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample - skip;
263 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44; /* 44 for the size of the WAV headers */
265 if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, do_qlp_coeff_prec_search, rice_optimization_level, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, requested_seek_points, num_requested_seek_points, &encoder_wrapper))
268 encoder_wrapper.verify_fifo.into_frames = true;
270 while(data_bytes > 0) {
271 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, fin);
272 if(bytes_read == 0) {
274 fprintf(stderr, "ERROR reading from %s\n", infile);
281 if(bytes_read > data_bytes)
282 bytes_read = data_bytes; /* chop off anything after the end of the data chunk */
283 if(bytes_read % bytes_per_wide_sample != 0) {
284 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infile);
288 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
289 format_input(wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
291 /* 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: */
292 if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
293 fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
296 data_bytes -= bytes_read;
302 if(encoder_wrapper.encoder) {
303 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
304 FLAC__encoder_finish(encoder_wrapper.encoder);
305 FLAC__encoder_free_instance(encoder_wrapper.encoder);
307 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
308 print_stats(&encoder_wrapper);
311 if(0 != encoder_wrapper.seek_table.points)
312 free(encoder_wrapper.seek_table.points);
314 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
315 printf("Verify FAILED! (%s) Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
319 printf("Verify succeeded\n");
325 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
327 if(encoder_wrapper.encoder) {
328 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
329 FLAC__encoder_finish(encoder_wrapper.encoder);
330 FLAC__encoder_free_instance(encoder_wrapper.encoder);
332 if(0 != encoder_wrapper.seek_table.points)
333 free(encoder_wrapper.seek_table.points);
335 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
336 printf("Verify FAILED! (%s) Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
340 printf("Verify succeeded\n");
348 int encode_raw(const char *infile, const char *outfile, 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 rice_optimization_level, 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)
350 encoder_wrapper_struct encoder_wrapper;
353 const size_t bytes_per_wide_sample = channels * (bps >> 3);
355 encoder_wrapper.encoder = 0;
356 encoder_wrapper.verify = verify;
357 encoder_wrapper.verbose = verbose;
358 encoder_wrapper.bytes_written = 0;
359 encoder_wrapper.samples_written = 0;
360 encoder_wrapper.outfile = outfile;
361 encoder_wrapper.seek_table.points = 0;
362 encoder_wrapper.first_seek_point_to_check = 0;
364 if(0 == strcmp(infile, "-")) {
368 if(0 == (fin = fopen(infile, "rb"))) {
369 fprintf(stderr, "ERROR: can't open input file %s\n", infile);
373 if(0 == strcmp(outfile, "-")) {
374 encoder_wrapper.fout = stdout;
377 if(0 == (encoder_wrapper.fout = fopen(outfile, "wb"))) {
378 fprintf(stderr, "ERROR: can't open output file %s\n", outfile);
384 if(!init(&encoder_wrapper))
387 /* get the file length */
388 if(0 != fseek(fin, 0, SEEK_END)) {
389 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
394 if(-1 == (filesize = ftell(fin))) {
395 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
398 encoder_wrapper.unencoded_size = filesize - skip * bytes_per_wide_sample;
399 encoder_wrapper.total_samples_to_encode = filesize / bytes_per_wide_sample - skip;
405 if(-1 == fseek(fin, bytes_per_wide_sample * (unsigned)skip, SEEK_SET)) {
406 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
413 for(left = (int64)skip; left > 0; left -= CHUNK_OF_SAMPLES) {
414 need = min(left, CHUNK_OF_SAMPLES);
415 if(fread(ucbuffer, 1, bytes_per_wide_sample * need, fin) < need) {
416 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
423 fseek(fin, 0, SEEK_SET);
426 if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, do_qlp_coeff_prec_search, rice_optimization_level, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, requested_seek_points, num_requested_seek_points, &encoder_wrapper))
429 encoder_wrapper.verify_fifo.into_frames = true;
432 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, fin);
433 if(bytes_read == 0) {
435 fprintf(stderr, "ERROR reading from %s\n", infile);
439 else if(bytes_read % bytes_per_wide_sample != 0) {
440 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infile);
444 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
445 format_input(wide_samples, is_big_endian, is_unsigned_samples, channels, bps, &encoder_wrapper);
447 /* 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: */
448 if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
449 fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
455 if(encoder_wrapper.encoder) {
456 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
457 FLAC__encoder_finish(encoder_wrapper.encoder);
458 FLAC__encoder_free_instance(encoder_wrapper.encoder);
460 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
461 print_stats(&encoder_wrapper);
464 if(0 != encoder_wrapper.seek_table.points)
465 free(encoder_wrapper.seek_table.points);
467 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
468 printf("Verify FAILED! (%s) Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
472 printf("Verify succeeded\n");
478 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
480 if(encoder_wrapper.encoder) {
481 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
482 FLAC__encoder_finish(encoder_wrapper.encoder);
483 FLAC__encoder_free_instance(encoder_wrapper.encoder);
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 printf("Verify FAILED! (%s) Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
493 printf("Verify succeeded\n");
501 bool init(encoder_wrapper_struct *encoder_wrapper)
506 is_big_endian_host = (*((byte*)(&test)))? false : true;
508 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
509 input[i] = &(in[i][0]);
511 encoder_wrapper->encoder = FLAC__encoder_get_new_instance();
512 if(0 == encoder_wrapper->encoder) {
513 fprintf(stderr, "ERROR creating the encoder instance\n");
520 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 rice_optimization_level, 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)
525 do_mid_side = loose_mid_side = false;
527 if(encoder_wrapper->verify) {
528 /* set up the fifo which will hold the original signal to compare against */
529 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
530 for(i = 0; i < channels; i++) {
531 if(0 == (encoder_wrapper->verify_fifo.original[i] = (int32*)malloc(sizeof(int32) * encoder_wrapper->verify_fifo.size))) {
532 fprintf(stderr, "ERROR allocating verify buffers\n");
536 encoder_wrapper->verify_fifo.tail = 0;
537 encoder_wrapper->verify_fifo.into_frames = false;
538 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
540 /* set up a stream decoder for verification */
541 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_get_new_instance();
542 if(0 == encoder_wrapper->verify_fifo.decoder) {
543 fprintf(stderr, "ERROR creating the verify decoder instance\n");
546 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) {
547 fprintf(stderr, "ERROR initializing decoder, state = %d:%s\n", encoder_wrapper->verify_fifo.decoder->state, FLAC__StreamDecoderStateString[encoder_wrapper->verify_fifo.decoder->state]);
552 if(!convert_to_seek_table(requested_seek_points, num_requested_seek_points, encoder_wrapper->total_samples_to_encode, blocksize, &encoder_wrapper->seek_table)) {
553 fprintf(stderr, "ERROR allocating seek table\n");
557 if(encoder_wrapper->verbose && encoder_wrapper->seek_table.num_points > 0) {
558 if(encoder_wrapper->total_samples_to_encode > 0)
559 printf("seek points (%llu total samples):", encoder_wrapper->total_samples_to_encode);
561 printf("seek points (total samples unknown):");
562 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
563 if(encoder_wrapper->seek_table.points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
564 printf(" %llu", encoder_wrapper->seek_table.points[i].sample_number);
571 encoder_wrapper->encoder->streamable_subset = !lax;
572 encoder_wrapper->encoder->channels = channels;
573 encoder_wrapper->encoder->bits_per_sample = bps;
574 encoder_wrapper->encoder->sample_rate = sample_rate;
575 encoder_wrapper->encoder->blocksize = blocksize;
576 encoder_wrapper->encoder->qlp_coeff_precision = qlp_coeff_precision;
577 encoder_wrapper->encoder->max_lpc_order = max_lpc_order;
578 encoder_wrapper->encoder->do_mid_side_stereo = do_mid_side;
579 encoder_wrapper->encoder->loose_mid_side_stereo = loose_mid_side;
580 encoder_wrapper->encoder->do_exhaustive_model_search = do_exhaustive_model_search;
581 encoder_wrapper->encoder->do_qlp_coeff_prec_search = do_qlp_coeff_prec_search;
582 encoder_wrapper->encoder->rice_optimization_level = rice_optimization_level;
583 encoder_wrapper->encoder->total_samples_estimate = encoder_wrapper->total_samples_to_encode;
584 encoder_wrapper->encoder->seek_table = (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0;
585 encoder_wrapper->encoder->padding = padding;
587 if(FLAC__encoder_init(encoder_wrapper->encoder, write_callback, metadata_callback, encoder_wrapper) != FLAC__ENCODER_OK) {
588 fprintf(stderr, "ERROR initializing encoder, state = %d:%s\n", encoder_wrapper->encoder->state, FLAC__EncoderStateString[encoder_wrapper->encoder->state]);
592 /* the above call write all the metadata, so we save the stream offset now */
593 encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
598 bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table)
600 unsigned i, j, real_points, placeholders;
601 char *pt = requested_seek_points, *q;
604 seek_table->num_points = 0;
606 if(num_requested_seek_points == 0)
609 if(num_requested_seek_points < 0) {
610 strcpy(requested_seek_points, "100x<");
611 num_requested_seek_points = 1;
614 /* first count how many individual seek point we may need */
615 real_points = placeholders = 0;
616 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
621 if(0 == strcmp(pt, "X")) { /* -S X */
624 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
625 if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
626 real_points += (unsigned)atoi(pt);
635 pt = requested_seek_points;
637 /* make some space */
638 if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
641 /* initialize the seek_table. we set frame_samples to zero to signify the points have not yet been hit by a frame write yet. */
642 for(i = 0; i < real_points+placeholders; i++) {
643 seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
644 seek_table->points[i].stream_offset = 0;
645 seek_table->points[i].frame_samples = 0;
648 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
653 if(0 == strcmp(pt, "X")) { /* -S X */
654 ; /* we append placeholders later */
656 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
657 if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
659 n = (unsigned)atoi(pt);
660 for(j = 0; j < n; j++)
661 append_point_to_seek_table(seek_table, stream_samples * (uint64)j / (uint64)n, stream_samples, blocksize);
665 append_point_to_seek_table(seek_table, (uint64)atoi(pt), stream_samples, blocksize);
671 /* sort the seekpoints */
672 qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
674 /* uniqify the seekpoints */
676 for(i = j = 0; i < seek_table->num_points; i++) {
678 if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
682 seek_table->points[j++] = seek_table->points[i];
684 seek_table->num_points = j;
686 /* append placeholders */
687 for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
688 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
689 seek_table->num_points += placeholders;
694 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize)
696 const uint64 target_sample = (sample / blocksize) * blocksize;
698 if(stream_samples == 0 || target_sample < stream_samples)
699 seek_table->points[seek_table->num_points++].sample_number = target_sample;
702 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
704 /* we don't just 'return l->sample_number - r->sample_number' since the result (int64) might overflow an 'int' */
705 if(l->sample_number == r->sample_number)
707 else if(l->sample_number < r->sample_number)
713 void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
715 unsigned wide_sample, sample, channel, byte;
718 if(is_unsigned_samples) {
719 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
720 for(channel = 0; channel < channels; channel++, sample++)
721 input[channel][wide_sample] = (int32)ucbuffer[sample] - 0x80;
724 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
725 for(channel = 0; channel < channels; channel++, sample++)
726 input[channel][wide_sample] = (int32)scbuffer[sample];
730 if(is_big_endian != is_big_endian_host) {
732 const unsigned bytes = wide_samples * channels * (bps >> 3);
733 for(byte = 0; byte < bytes; byte += 2) {
734 tmp = ucbuffer[byte];
735 ucbuffer[byte] = ucbuffer[byte+1];
736 ucbuffer[byte+1] = tmp;
739 if(is_unsigned_samples) {
740 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
741 for(channel = 0; channel < channels; channel++, sample++)
742 input[channel][wide_sample] = (int32)usbuffer[sample] - 0x8000;
745 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
746 for(channel = 0; channel < channels; channel++, sample++)
747 input[channel][wide_sample] = (int32)ssbuffer[sample];
753 const unsigned bytes = wide_samples * channels * (bps >> 3);
754 for(byte = 0; byte < bytes; byte += 3) {
755 tmp = ucbuffer[byte];
756 ucbuffer[byte] = ucbuffer[byte+2];
757 ucbuffer[byte+2] = tmp;
760 if(is_unsigned_samples) {
761 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
762 for(channel = 0; channel < channels; channel++, sample++) {
763 input[channel][wide_sample] = ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
764 input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
765 input[channel][wide_sample] |= ucbuffer[byte++];
766 input[channel][wide_sample] -= 0x800000;
770 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
771 for(channel = 0; channel < channels; channel++, sample++) {
772 input[channel][wide_sample] = scbuffer[byte++]; input[channel][wide_sample] <<= 8;
773 input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
774 input[channel][wide_sample] |= ucbuffer[byte++];
782 if(encoder_wrapper->verify) {
783 for(channel = 0; channel < channels; channel++)
784 memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], &input[channel][0], sizeof(int32) * wide_samples);
785 encoder_wrapper->verify_fifo.tail += wide_samples;
786 assert(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
790 FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
792 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
793 unsigned mask = (encoder->do_exhaustive_model_search || encoder->do_qlp_coeff_prec_search)? 0x07 : 0x1f;
795 /* mark the current seek point if hit (if stream_offset == 0 that means we're still writing metadata and haven't hit the first frame yet) */
796 if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table.num_points > 0) {
797 uint64 current_sample = (uint64)current_frame * (uint64)encoder->blocksize, test_sample;
799 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table.num_points; i++) {
800 test_sample = encoder_wrapper->seek_table.points[i].sample_number;
801 if(test_sample > current_sample) {
804 else if(test_sample == current_sample) {
805 encoder_wrapper->seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
806 encoder_wrapper->seek_table.points[i].frame_samples = encoder->blocksize;
807 encoder_wrapper->first_seek_point_to_check++;
811 encoder_wrapper->first_seek_point_to_check++;
816 encoder_wrapper->bytes_written += bytes;
817 encoder_wrapper->samples_written += samples;
818 encoder_wrapper->current_frame = current_frame;
820 if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
821 print_stats(encoder_wrapper);
823 if(encoder_wrapper->verify) {
824 encoder_wrapper->verify_fifo.encoded_signal = buffer;
825 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
826 if(encoder_wrapper->verify_fifo.into_frames) {
827 if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
828 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
829 return FLAC__ENCODER_WRITE_FATAL_ERROR;
833 if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
834 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
835 return FLAC__ENCODER_WRITE_FATAL_ERROR;
840 if(fwrite(buffer, sizeof(byte), bytes, encoder_wrapper->fout) == bytes)
841 return FLAC__ENCODER_WRITE_OK;
843 return FLAC__ENCODER_WRITE_FATAL_ERROR;
846 void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
848 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
851 const uint64 samples = metadata->data.stream_info.total_samples;
852 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
853 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
855 assert(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
858 * we get called by the encoder when the encoding process has
859 * finished so that we can update the STREAMINFO and SEEKTABLE
863 (void)encoder; /* silence compiler warning about unused parameter */
865 if(encoder_wrapper->fout == stdout)
868 fclose(encoder_wrapper->fout);
869 if(0 == (f = fopen(encoder_wrapper->outfile, "r+b")))
872 /* all this is based on intimate knowledge of the stream header
873 * layout, but a change to the header format that would break this
874 * would also break all streams encoded in the previous format.
877 if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
878 fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
881 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
882 if(fread(&b, 1, 1, f) != 1) goto framesize_;
883 if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
884 b = (b & 0xf0) | (byte)((samples >> 32) & 0x0F);
885 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
886 b = (byte)((samples >> 24) & 0xFF);
887 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
888 b = (byte)((samples >> 16) & 0xFF);
889 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
890 b = (byte)((samples >> 8) & 0xFF);
891 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
892 b = (byte)(samples & 0xFF);
893 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
896 if(-1 == fseek(f, 12, SEEK_SET)) goto seektable_;
897 b = (byte)((min_framesize >> 16) & 0xFF);
898 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
899 b = (byte)((min_framesize >> 8) & 0xFF);
900 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
901 b = (byte)(min_framesize & 0xFF);
902 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
903 b = (byte)((max_framesize >> 16) & 0xFF);
904 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
905 b = (byte)((max_framesize >> 8) & 0xFF);
906 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
907 b = (byte)(max_framesize & 0xFF);
908 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
911 if(encoder_wrapper->seek_table.num_points > 0) {
915 /* convert any unused seek points to placeholders */
916 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
917 if(encoder_wrapper->seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
919 else if(encoder_wrapper->seek_table.points[i].frame_samples == 0)
920 encoder_wrapper->seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
923 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
924 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
925 pos += metadata->length;
926 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
927 if(-1 == fseek(f, pos, SEEK_SET)) goto end_;
928 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
929 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].sample_number)) goto end_;
930 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table.points[i].stream_offset)) goto end_;
931 if(!write_big_endian_uint16(f, encoder_wrapper->seek_table.points[i].frame_samples)) goto end_;
940 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
942 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
943 const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
946 if(encoded_bytes <= *bytes) {
947 *bytes = encoded_bytes;
948 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
951 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
952 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
953 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
956 return FLAC__STREAM_DECODER_READ_CONTINUE;
959 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
961 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
962 unsigned channel, l, r;
964 for(channel = 0; channel < decoder->channels; channel++) {
965 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], sizeof(int32) * decoder->blocksize)) {
966 fprintf(stderr, "\nERROR: mismatch in decoded data, verify FAILED!\n");
967 fprintf(stderr, " Please submit a bug report to http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
968 return FLAC__STREAM_DECODER_WRITE_ABORT;
971 /* dequeue the frame from the fifo */
972 for(channel = 0; channel < decoder->channels; channel++) {
973 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
974 encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
977 encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
978 return FLAC__STREAM_DECODER_WRITE_CONTINUE;
981 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
988 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
992 fprintf(stderr, "\nERROR: verification decoder returned error %d:%s\n", status, FLAC__StreamDecoderErrorStatusString[status]);
995 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
998 /* with VC++ you have to spoon feed it the casting */
999 double progress = (double)(int64)encoder_wrapper->samples_written / (double)(int64)encoder_wrapper->total_samples_to_encode;
1001 double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1003 printf("\r%0.2f%% complete: frame %u, wrote %u bytes, %u of %u samples, ratio = %5.3f",
1004 progress * 100.0, encoder_wrapper->current_frame,
1005 (unsigned)encoder_wrapper->bytes_written, (unsigned)encoder_wrapper->samples_written, (unsigned)encoder_wrapper->total_samples_to_encode,
1007 /* with VC++ you have to spoon feed it the casting */
1008 (double)(int64)encoder_wrapper->bytes_written / ((double)(int64)encoder_wrapper->unencoded_size * progress)
1010 (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress)
1016 bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok)
1018 size_t bytes_read = fread(val, 1, 2, f);
1020 if(bytes_read == 0) {
1022 fprintf(stderr, "ERROR: unexpected EOF\n");
1028 else if(bytes_read < 2) {
1029 fprintf(stderr, "ERROR: unexpected EOF\n");
1033 if(is_big_endian_host) {
1034 byte tmp, *b = (byte*)val;
1035 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1041 bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok)
1043 size_t bytes_read = fread(val, 1, 4, f);
1045 if(bytes_read == 0) {
1047 fprintf(stderr, "ERROR: unexpected EOF\n");
1053 else if(bytes_read < 4) {
1054 fprintf(stderr, "ERROR: unexpected EOF\n");
1058 if(is_big_endian_host) {
1059 byte tmp, *b = (byte*)val;
1060 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1061 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1067 bool write_big_endian_uint16(FILE *f, uint16 val)
1069 if(!is_big_endian_host) {
1070 byte *b = (byte *)&val, tmp;
1071 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1073 return fwrite(&val, 1, 2, f) == 2;
1076 bool write_big_endian_uint64(FILE *f, uint64 val)
1078 if(!is_big_endian_host) {
1079 byte *b = (byte *)&val, tmp;
1080 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1081 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1082 tmp = b[2]; b[2] = b[5]; b[3] = tmp;
1083 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1085 return fwrite(&val, 1, 8, f) == 8;