1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002 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 <limits.h> /* for LONG_MAX */
26 #include <math.h> /* for floor() */
27 #include <stdio.h> /* for FILE et al. */
28 #include <stdlib.h> /* for malloc */
29 #include <string.h> /* for strcmp() */
40 #define min(x,y) ((x)<(y)?(x):(y))
42 /* this MUST be >= 588 so that sector aligning can take place with one read */
43 #define CHUNK_OF_SAMPLES 2048
47 FLAC__VERIFY_FAILED_IN_FRAME,
48 FLAC__VERIFY_FAILED_IN_METADATA
51 static const char *verify_code_string[] = {
53 "FLAC__VERIFY_FAILED_IN_FRAME",
54 "FLAC__VERIFY_FAILED_IN_METADATA"
59 ENCODER_IN_METADATA = 1,
64 FLAC__int32 *original[FLAC__MAX_CHANNELS];
65 unsigned size; /* of each original[] in samples */
66 unsigned tail; /* in wide samples */
67 const FLAC__byte *encoded_signal;
68 unsigned encoded_signal_capacity;
69 unsigned encoded_bytes;
70 EncodeState encode_state;
71 FLAC__bool needs_magic_hack;
73 FLAC__StreamDecoder *decoder;
84 const char *inbasefilename;
86 const char *outfilename;
87 FLAC__StreamEncoder *encoder;
90 FLAC__uint64 unencoded_size;
91 FLAC__uint64 total_samples_to_encode;
92 FLAC__uint64 bytes_written;
93 FLAC__uint64 samples_written;
94 FLAC__uint64 stream_offset; /* i.e. number of bytes before the first byte of the the first frame's header */
95 unsigned current_frame;
96 verify_fifo_struct verify_fifo;
97 FLAC__StreamMetadata *seek_table;
98 unsigned first_seek_point_to_check;
103 } encoder_wrapper_struct;
105 static FLAC__bool is_big_endian_host;
107 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
108 static signed char *scbuffer = (signed char *)ucbuffer;
109 static FLAC__uint16 *usbuffer = (FLAC__uint16 *)ucbuffer;
110 static FLAC__int16 *ssbuffer = (FLAC__int16 *)ucbuffer;
112 static FLAC__int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
113 static FLAC__int32 *input[FLAC__MAX_CHANNELS];
116 static FLAC__bool init(encoder_wrapper_struct *encoder_wrapper);
117 static FLAC__bool init_encoder(encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper);
118 static FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, FLAC__StreamMetadata *seek_table);
119 static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
120 static void append_to_verify_fifo(encoder_wrapper_struct *encoder_wrapper, const FLAC__int32 * const input[], unsigned channels, unsigned wide_samples);
121 static FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
122 static void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
123 static FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
124 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
125 static void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
126 static void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
127 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
128 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
129 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
130 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
131 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
132 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
133 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
134 static FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val);
137 flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const char *outfilename,
138 const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
140 encoder_wrapper_struct encoder_wrapper;
143 unsigned int channels= 0U, bps= 0U, sample_rate= 0U, sample_frames= 0U;
144 FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
145 int info_align_carry= -1, info_align_zero= -1;
146 enum { NORMAL, DONE, ERROR, MISMATCH } status= NORMAL;
148 FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
150 encoder_wrapper.encoder = 0;
151 encoder_wrapper.verify = options.common.verify;
152 encoder_wrapper.verbose = options.common.verbose;
153 encoder_wrapper.bytes_written = 0;
154 encoder_wrapper.samples_written = 0;
155 encoder_wrapper.stream_offset = 0;
156 encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
157 encoder_wrapper.outfilename = outfilename;
158 encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
159 encoder_wrapper.first_seek_point_to_check = 0;
161 encoder_wrapper.use_ogg = options.common.use_ogg;
164 if(0 == encoder_wrapper.seek_table) {
165 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
169 (void)infilesize; /* silence compiler warning about unused parameter */
170 (void)lookahead; /* silence compiler warning about unused parameter */
171 (void)lookahead_length; /* silence compiler warning about unused parameter */
173 if(0 == strcmp(outfilename, "-")) {
174 encoder_wrapper.fout = file__get_binary_stdout();
177 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
178 fprintf(stderr, "%s: ERROR: can't open output file %s\n", encoder_wrapper.inbasefilename, outfilename);
185 if(!init(&encoder_wrapper))
188 /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
190 while(status==NORMAL) {
194 /* chunk identifier; really conservative about behavior of fread() and feof() */
195 if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
197 else if(c<4U || feof(infile)) {
198 fprintf(stderr, "%s: ERROR: incomplete chunk identifier\n", encoder_wrapper.inbasefilename);
202 if(status==NORMAL && got_comm_chunk==false && !strncmp(chunk_id, "COMM", 4)) { /* common chunk */
206 /* COMM chunk size */
207 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
210 fprintf(stderr, "%s: ERROR: non-standard 'COMM' chunk has length = %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
214 fprintf(stderr, "%s: WARNING: non-standard 'COMM' chunk has length = %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
215 skip= (xx-18U)+(xx & 1U);
219 /* number of channels */
220 if(!read_big_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
222 else if(x==0U || x>FLAC__MAX_CHANNELS) {
223 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned int)x);
226 else if(options.common.sector_align && x!=2U) {
227 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)x);
234 /* number of sample frames */
235 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
241 /* bits per sample */
242 if(!read_big_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
244 else if(x!=8U && x!=16U && x!=24U) {
245 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned int)x);
248 else if(options.common.sector_align && x!=16U) {
249 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)x);
257 if(!read_sane_extended(infile, &xx, false, encoder_wrapper.inbasefilename))
259 else if(!FLAC__format_sample_rate_is_valid(xx)) {
260 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
263 else if(options.common.sector_align && xx!=44100U) {
264 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
270 /* skip any extra data in the COMM chunk */
271 FLAC__ASSERT(skip<=LONG_MAX);
272 while(status==NORMAL && skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
273 unsigned int need= min(skip, sizeof ucbuffer);
274 if(fread(ucbuffer, 1U, need, infile)<need) {
275 fprintf(stderr, "%s: ERROR during read while skipping extra COMM data\n", encoder_wrapper.inbasefilename);
281 got_comm_chunk= true;
283 else if(status==NORMAL && got_ssnd_chunk==false && !strncmp(chunk_id, "SSND", 4)) { /* sound data chunk */
284 unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
285 size_t bytes_per_frame= channels*(bps>>3);
286 FLAC__bool pad= false;
288 if(status==NORMAL && got_comm_chunk==false) {
289 fprintf(stderr, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", encoder_wrapper.inbasefilename);
294 /* SSND chunk size */
295 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
297 else if(xx!=(sample_frames*bytes_per_frame + 8U)) {
298 fprintf(stderr, "%s: ERROR: SSND chunk size inconsistent with sample frame count\n", encoder_wrapper.inbasefilename);
302 pad= (data_bytes & 1U) ? true : false;
307 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
310 fprintf(stderr, "%s: ERROR: offset is %u; must be 0\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
318 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
321 fprintf(stderr, "%s: ERROR: block size is %u; must be 0\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
327 if(status==NORMAL && options.common.skip>0U) {
328 FLAC__uint64 remaining= options.common.skip*bytes_per_frame;
330 /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
331 /* is guaranteed to be less than LONG_MAX */
332 for(; remaining>0U; remaining-= remaining>(1U<<30) ? remaining : (1U<<30))
334 unsigned long skip= remaining % (1U<<30);
336 FLAC__ASSERT(skip<=LONG_MAX);
337 while(status==NORMAL && skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
338 unsigned int need= min(skip, sizeof ucbuffer);
339 if(fread(ucbuffer, 1U, need, infile)<need) {
340 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
349 data_bytes-= (8U + (unsigned int)options.common.skip*bytes_per_frame); /*@@@ WATCHOUT: 4GB limit */
350 encoder_wrapper.total_samples_to_encode= data_bytes/bytes_per_frame + *options.common.align_reservoir_samples;
351 if(options.common.sector_align) {
352 align_remainder= (unsigned int)(encoder_wrapper.total_samples_to_encode % 588U);
353 if(options.common.is_last_file)
354 encoder_wrapper.total_samples_to_encode+= (588U-align_remainder); /* will pad with zeroes */
356 encoder_wrapper.total_samples_to_encode-= align_remainder; /* will stop short and carry over to next file */
359 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
360 encoder_wrapper.unencoded_size= encoder_wrapper.total_samples_to_encode*bytes_per_frame+54;
362 if(!init_encoder(options.common, channels, bps, sample_rate, &encoder_wrapper))
365 encoder_wrapper.verify_fifo.encode_state = ENCODER_IN_AUDIO;
368 /* first do any samples in the reservoir */
369 if(status==NORMAL && options.common.sector_align && *options.common.align_reservoir_samples>0U) {
370 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 *const *)options.common.align_reservoir, channels, *options.common.align_reservoir_samples);
372 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
373 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
378 /* decrement the data_bytes counter if we need to align the file */
379 if(status==NORMAL && options.common.sector_align) {
380 if(options.common.is_last_file)
381 *options.common.align_reservoir_samples= 0U;
383 *options.common.align_reservoir_samples= align_remainder;
384 data_bytes-= (*options.common.align_reservoir_samples)*bytes_per_frame;
388 /* now do from the file */
389 while(status==NORMAL && data_bytes>0) {
390 size_t bytes_read= fread(ucbuffer, 1U, min(data_bytes, CHUNK_OF_SAMPLES*bytes_per_frame), infile);
394 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
397 else if(feof(infile)) {
398 fprintf(stderr, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned int)encoder_wrapper.total_samples_to_encode, (unsigned int)encoder_wrapper.samples_written);
403 if(bytes_read % bytes_per_frame != 0U) {
404 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
408 unsigned int frames= bytes_read/bytes_per_frame;
409 format_input(input, frames, true, false, channels, bps, &encoder_wrapper);
411 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)input, frames)) {
412 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
416 data_bytes-= bytes_read;
421 /* now read unaligned samples into reservoir or pad with zeroes if necessary */
422 if(status==NORMAL && options.common.sector_align) {
423 if(options.common.is_last_file) {
424 unsigned int pad_frames= 588U-align_remainder;
426 if(pad_frames<588U) {
429 info_align_zero= pad_frames;
430 for(i= 0U; i<channels; ++i)
431 memset(input[i], 0, pad_frames*(bps>>3));
432 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 *const *)input, channels, pad_frames);
434 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)input, pad_frames)) {
435 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
441 if(*options.common.align_reservoir_samples > 0) {
442 size_t bytes_read= fread(ucbuffer, 1U, (*options.common.align_reservoir_samples)*bytes_per_frame, infile);
444 FLAC__ASSERT(CHUNK_OF_SAMPLES>=588U);
445 if(bytes_read==0U && ferror(infile)) {
446 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
449 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame)
450 fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned int)bytes_read, (unsigned int)encoder_wrapper.total_samples_to_encode, (unsigned int)encoder_wrapper.samples_written);
452 info_align_carry= *options.common.align_reservoir_samples;
453 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, true, false, channels, bps, &encoder_wrapper);
459 if(status==NORMAL && pad==true) {
462 if(fread(&tmp, 1U, 1U, infile)<1U) {
463 fprintf(stderr, "%s: ERROR during read of SSND pad byte\n", encoder_wrapper.inbasefilename);
468 got_ssnd_chunk= true;
470 else if(status==NORMAL) { /* other chunk */
471 if(!strncmp(chunk_id, "COMM", 4))
472 fprintf(stderr, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_wrapper.inbasefilename);
473 else if(!strncmp(chunk_id, "SSND", 4))
474 fprintf(stderr, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_wrapper.inbasefilename);
476 fprintf(stderr, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_wrapper.inbasefilename, chunk_id);
479 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
482 unsigned long skip= xx+(xx & 1U);
484 FLAC__ASSERT(skip<=LONG_MAX);
485 while(status==NORMAL && skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
486 unsigned int need= min(skip, sizeof ucbuffer);
487 if(fread(ucbuffer, 1U, need, infile)<need) {
488 fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_wrapper.inbasefilename);
497 if(got_ssnd_chunk==false && sample_frames!=0U) {
498 fprintf(stderr, "%s: ERROR: missing SSND chunk\n", encoder_wrapper.inbasefilename);
502 if(encoder_wrapper.encoder) {
503 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
504 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
506 if(encoder_wrapper.use_ogg)
507 ogg_stream_clear(&encoder_wrapper.ogg.os);
510 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
512 print_stats(&encoder_wrapper);
513 fprintf(stderr, "\n");
516 if(0 != encoder_wrapper.seek_table)
517 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
518 if(options.common.verify) {
519 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
520 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
521 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
522 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
531 if(info_align_carry >= 0)
532 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
533 if(info_align_zero >= 0)
534 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
536 else if(status==ERROR)
539 return status==ERROR || status==MISMATCH;
542 int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
544 encoder_wrapper_struct encoder_wrapper;
545 FLAC__bool is_unsigned_samples = false;
546 unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
547 size_t bytes_per_wide_sample, bytes_read;
550 FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
551 unsigned align_remainder = 0;
552 int info_align_carry = -1, info_align_zero = -1;
554 FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
556 encoder_wrapper.encoder = 0;
557 encoder_wrapper.verify = options.common.verify;
558 encoder_wrapper.verbose = options.common.verbose;
559 encoder_wrapper.bytes_written = 0;
560 encoder_wrapper.samples_written = 0;
561 encoder_wrapper.stream_offset = 0;
562 encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
563 encoder_wrapper.outfilename = outfilename;
564 encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
565 encoder_wrapper.first_seek_point_to_check = 0;
567 encoder_wrapper.use_ogg = options.common.use_ogg;
571 (void)lookahead_length;
573 if(0 == encoder_wrapper.seek_table) {
574 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
578 if(0 == strcmp(outfilename, "-")) {
579 encoder_wrapper.fout = file__get_binary_stdout();
582 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
583 fprintf(stderr, "%s: ERROR: can't open output file %s\n", encoder_wrapper.inbasefilename, outfilename);
590 if(!init(&encoder_wrapper))
594 * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
596 while(!feof(infile)) {
597 if(!read_little_endian_uint32(infile, &xx, true, encoder_wrapper.inbasefilename))
601 if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
602 /* fmt sub-chunk size */
603 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
606 fprintf(stderr, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
609 else if(xx != 16 && xx != 18) {
610 fprintf(stderr, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
613 /* compression code */
614 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
617 fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
620 /* number of channels */
621 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
623 if(x == 0 || x > FLAC__MAX_CHANNELS) {
624 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
627 else if(options.common.sector_align && x != 2) {
628 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)x);
633 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
635 if(!FLAC__format_sample_rate_is_valid(xx)) {
636 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
639 else if(options.common.sector_align && xx != 44100) {
640 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)xx);
644 /* avg bytes per second (ignored) */
645 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
647 /* block align (ignored) */
648 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
650 /* bits per sample */
651 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
653 if(x != 8 && x != 16 && x != 24) {
654 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
657 else if(options.common.sector_align && x != 16) {
658 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)x);
662 is_unsigned_samples = (x == 8);
664 /* skip any extra data in the fmt sub-chunk */
668 for(left = data_bytes; left > 0; ) {
669 need = min(left, CHUNK_OF_SAMPLES);
670 if(fread(ucbuffer, 1U, need, infile) < need) {
671 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
678 got_fmt_chunk = true;
680 else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
682 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
686 bytes_per_wide_sample = channels * (bps >> 3);
688 if(options.common.skip > 0) {
689 if(fseek(infile, bytes_per_wide_sample * (unsigned)options.common.skip, SEEK_CUR) < 0) {
690 /* can't seek input, read ahead manually... */
692 for(left = (unsigned)options.common.skip; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
693 need = min(left, CHUNK_OF_SAMPLES);
694 if(fread(ucbuffer, bytes_per_wide_sample, need, infile) < need) {
695 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
703 data_bytes -= (unsigned)options.common.skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
704 encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample + *options.common.align_reservoir_samples;
705 if(options.common.sector_align) {
706 align_remainder = (unsigned)(encoder_wrapper.total_samples_to_encode % 588);
707 if(options.common.is_last_file)
708 encoder_wrapper.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
710 encoder_wrapper.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
713 /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
714 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44;
716 if(!init_encoder(options.common, channels, bps, sample_rate, &encoder_wrapper))
719 encoder_wrapper.verify_fifo.encode_state = ENCODER_IN_AUDIO;
722 * first do any samples in the reservoir
724 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
725 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 * const *)options.common.align_reservoir, channels, *options.common.align_reservoir_samples);
727 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
728 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
734 * decrement the data_bytes counter if we need to align the file
736 if(options.common.sector_align) {
737 if(options.common.is_last_file) {
738 *options.common.align_reservoir_samples = 0;
741 *options.common.align_reservoir_samples = align_remainder;
742 data_bytes -= (*options.common.align_reservoir_samples) * bytes_per_wide_sample;
747 * now do from the file
749 while(data_bytes > 0) {
750 bytes_read = fread(ucbuffer, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
751 if(bytes_read == 0) {
753 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
756 else if(feof(infile)) {
757 fprintf(stderr, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
762 if(bytes_read % bytes_per_wide_sample != 0) {
763 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
767 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
768 format_input(input, wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
770 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
771 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
774 data_bytes -= bytes_read;
780 * now read unaligned samples into reservoir or pad with zeroes if necessary
782 if(options.common.sector_align) {
783 if(options.common.is_last_file) {
784 unsigned wide_samples = 588 - align_remainder;
785 if(wide_samples < 588) {
788 info_align_zero = wide_samples;
789 data_bytes = wide_samples * (bps >> 3);
790 for(channel = 0; channel < channels; channel++)
791 memset(input[channel], 0, data_bytes);
792 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 * const *)input, channels, wide_samples);
794 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
795 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
801 if(*options.common.align_reservoir_samples > 0) {
802 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
803 bytes_read = fread(ucbuffer, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
804 if(bytes_read == 0 && ferror(infile)) {
805 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
808 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
809 fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
813 info_align_carry = *options.common.align_reservoir_samples;
814 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
820 got_data_chunk = true;
823 if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
824 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_wrapper.inbasefilename);
826 else if(xx == 0x61746164) { /* "data" */
828 fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_wrapper.inbasefilename);
830 else if(!got_fmt_chunk) {
831 fprintf(stderr, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_wrapper.inbasefilename);
839 fprintf(stderr, "%s: WARNING: skipping unknown sub-chunk '%c%c%c%c'\n", encoder_wrapper.inbasefilename, (char)(xx&255), (char)((xx>>8)&255), (char)((xx>>16)&255), (char)(xx>>24));
842 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
844 if(fseek(infile, xx, SEEK_CUR) < 0) {
845 /* can't seek input, read ahead manually... */
847 const unsigned chunk = sizeof(ucbuffer);
848 for(left = xx; left > 0; ) {
849 need = min(left, chunk);
850 if(fread(ucbuffer, 1, need, infile) < need) {
851 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_wrapper.inbasefilename);
860 if(encoder_wrapper.encoder) {
861 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
862 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
864 if(encoder_wrapper.use_ogg)
865 ogg_stream_clear(&encoder_wrapper.ogg.os);
868 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
869 print_stats(&encoder_wrapper);
870 fprintf(stderr, "\n");
872 if(0 != encoder_wrapper.seek_table)
873 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
874 if(options.common.verify) {
875 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
876 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
877 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
878 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
882 if(info_align_carry >= 0)
883 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
884 if(info_align_zero >= 0)
885 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
890 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
891 fprintf(stderr, "\n");
892 if(encoder_wrapper.encoder) {
893 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
894 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
896 if(encoder_wrapper.use_ogg)
897 ogg_stream_clear(&encoder_wrapper.ogg.os);
900 if(0 != encoder_wrapper.seek_table)
901 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
902 if(options.common.verify) {
903 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
904 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
905 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
906 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
916 int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, raw_encode_options_t options)
918 encoder_wrapper_struct encoder_wrapper;
920 const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
921 unsigned align_remainder = 0;
922 int info_align_carry = -1, info_align_zero = -1;
924 FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
925 FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
926 FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
927 FLAC__ASSERT(!options.common.sector_align || options.sample_rate == 44100);
928 FLAC__ASSERT(!options.common.sector_align || infilesize >= 0);
930 encoder_wrapper.encoder = 0;
931 encoder_wrapper.verify = options.common.verify;
932 encoder_wrapper.verbose = options.common.verbose;
933 encoder_wrapper.bytes_written = 0;
934 encoder_wrapper.samples_written = 0;
935 encoder_wrapper.stream_offset = 0;
936 encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
937 encoder_wrapper.outfilename = outfilename;
938 encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
939 encoder_wrapper.first_seek_point_to_check = 0;
941 encoder_wrapper.use_ogg = options.common.use_ogg;
944 if(0 == encoder_wrapper.seek_table) {
945 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
949 if(0 == strcmp(outfilename, "-")) {
950 encoder_wrapper.fout = file__get_binary_stdout();
953 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
954 fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
961 if(!init(&encoder_wrapper))
964 /* get the file length */
966 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
969 if(options.common.sector_align) {
970 FLAC__ASSERT(options.common.skip == 0);
971 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
972 align_remainder = (unsigned)(encoder_wrapper.total_samples_to_encode % 588);
973 if(options.common.is_last_file)
974 encoder_wrapper.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
976 encoder_wrapper.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
979 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - options.common.skip;
982 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample;
985 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
986 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
988 if(options.common.skip > 0) {
989 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)options.common.skip;
990 if(skip_bytes > lookahead_length) {
991 skip_bytes -= lookahead_length;
992 lookahead_length = 0;
993 if(fseek(infile, (long)skip_bytes, SEEK_CUR) < 0) {
994 /* can't seek input, read ahead manually... */
996 const unsigned chunk = sizeof(ucbuffer);
997 for(left = skip_bytes; left > 0; ) {
998 need = min(left, chunk);
999 if(fread(ucbuffer, 1, need, infile) < need) {
1000 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
1008 lookahead += skip_bytes;
1009 lookahead_length -= skip_bytes;
1013 if(!init_encoder(options.common, options.channels, options.bps, options.sample_rate, &encoder_wrapper))
1016 encoder_wrapper.verify_fifo.encode_state = ENCODER_IN_AUDIO;
1019 * first do any samples in the reservoir
1021 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
1022 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 * const *)options.common.align_reservoir, options.channels, *options.common.align_reservoir_samples);
1024 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
1025 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
1031 * decrement infilesize if we need to align the file
1033 if(options.common.sector_align) {
1034 FLAC__ASSERT(infilesize >= 0);
1035 if(options.common.is_last_file) {
1036 *options.common.align_reservoir_samples = 0;
1039 *options.common.align_reservoir_samples = align_remainder;
1040 infilesize -= (long)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
1045 * now do from the file
1047 while(!feof(infile)) {
1048 if(lookahead_length > 0) {
1049 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1050 memcpy(ucbuffer, lookahead, lookahead_length);
1051 bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
1052 if(ferror(infile)) {
1053 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
1056 lookahead_length = 0;
1059 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
1061 if(bytes_read == 0) {
1062 if(ferror(infile)) {
1063 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
1067 else if(bytes_read % bytes_per_wide_sample != 0) {
1068 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
1072 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1073 format_input(input, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, &encoder_wrapper);
1075 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
1076 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
1083 * now read unaligned samples into reservoir or pad with zeroes if necessary
1085 if(options.common.sector_align) {
1086 if(options.common.is_last_file) {
1087 unsigned wide_samples = 588 - align_remainder;
1088 if(wide_samples < 588) {
1089 unsigned channel, data_bytes;
1091 info_align_zero = wide_samples;
1092 data_bytes = wide_samples * (options.bps >> 3);
1093 for(channel = 0; channel < options.channels; channel++)
1094 memset(input[channel], 0, data_bytes);
1095 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 * const *)input, options.channels, wide_samples);
1097 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
1098 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
1104 if(*options.common.align_reservoir_samples > 0) {
1105 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1106 bytes_read = fread(ucbuffer, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
1107 if(bytes_read == 0 && ferror(infile)) {
1108 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
1111 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
1112 fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
1115 info_align_carry = *options.common.align_reservoir_samples;
1116 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, options.is_unsigned_samples, options.channels, options.bps, &encoder_wrapper);
1122 if(encoder_wrapper.encoder) {
1123 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
1124 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
1125 #ifdef FLAC__HAS_OGG
1126 if(encoder_wrapper.use_ogg)
1127 ogg_stream_clear(&encoder_wrapper.ogg.os);
1130 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
1131 print_stats(&encoder_wrapper);
1132 fprintf(stderr, "\n");
1134 if(0 != encoder_wrapper.seek_table)
1135 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
1136 if(options.common.verify) {
1137 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
1138 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
1139 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
1140 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
1144 if(info_align_carry >= 0)
1145 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
1146 if(info_align_zero >= 0)
1147 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
1152 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
1153 fprintf(stderr, "\n");
1154 if(encoder_wrapper.encoder) {
1155 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
1156 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
1157 #ifdef FLAC__HAS_OGG
1158 if(encoder_wrapper.use_ogg)
1159 ogg_stream_clear(&encoder_wrapper.ogg.os);
1162 if(0 != encoder_wrapper.seek_table)
1163 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
1164 if(options.common.verify) {
1165 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
1166 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
1167 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
1168 fprintf(stderr, "Verify FAILED! (%s) Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
1174 unlink(outfilename);
1178 FLAC__bool init(encoder_wrapper_struct *encoder_wrapper)
1181 FLAC__uint32 test = 1;
1183 is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
1185 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1186 input[i] = &(in[i][0]);
1188 encoder_wrapper->encoder = FLAC__stream_encoder_new();
1189 if(0 == encoder_wrapper->encoder) {
1190 fprintf(stderr, "%s: ERROR creating the encoder instance\n", encoder_wrapper->inbasefilename);
1194 #ifdef FLAC__HAS_OGG
1195 if(encoder_wrapper->use_ogg) {
1196 if(ogg_stream_init(&encoder_wrapper->ogg.os, 0) != 0) {
1197 fprintf(stderr, "%s: ERROR initializing the Ogg stream\n", encoder_wrapper->inbasefilename);
1198 FLAC__stream_encoder_delete(encoder_wrapper->encoder);
1207 FLAC__bool init_encoder(encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper)
1209 unsigned i, num_metadata;
1210 FLAC__StreamMetadata padding;
1211 FLAC__StreamMetadata *metadata[2];
1214 options.do_mid_side = options.loose_mid_side = false;
1216 if(encoder_wrapper->verify) {
1217 /* set up the fifo which will hold the original signal to compare against */
1218 encoder_wrapper->verify_fifo.size = options.blocksize + CHUNK_OF_SAMPLES;
1219 for(i = 0; i < channels; i++) {
1220 if(0 == (encoder_wrapper->verify_fifo.original[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder_wrapper->verify_fifo.size))) {
1221 fprintf(stderr, "%s: ERROR allocating verify buffers\n", encoder_wrapper->inbasefilename);
1225 encoder_wrapper->verify_fifo.tail = 0;
1226 encoder_wrapper->verify_fifo.encode_state = ENCODER_IN_MAGIC;
1227 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
1229 /* set up a stream decoder for verification */
1230 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_new();
1231 if(0 == encoder_wrapper->verify_fifo.decoder) {
1232 fprintf(stderr, "%s: ERROR creating the verify decoder instance\n", encoder_wrapper->inbasefilename);
1235 FLAC__stream_decoder_set_read_callback(encoder_wrapper->verify_fifo.decoder, verify_read_callback);
1236 FLAC__stream_decoder_set_write_callback(encoder_wrapper->verify_fifo.decoder, verify_write_callback);
1237 FLAC__stream_decoder_set_metadata_callback(encoder_wrapper->verify_fifo.decoder, verify_metadata_callback);
1238 FLAC__stream_decoder_set_error_callback(encoder_wrapper->verify_fifo.decoder, verify_error_callback);
1239 FLAC__stream_decoder_set_client_data(encoder_wrapper->verify_fifo.decoder, encoder_wrapper);
1240 if(FLAC__stream_decoder_init(encoder_wrapper->verify_fifo.decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
1241 fprintf(stderr, "%s: ERROR initializing decoder, state = %d:%s\n", encoder_wrapper->inbasefilename, FLAC__stream_decoder_get_state(encoder_wrapper->verify_fifo.decoder), FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(encoder_wrapper->verify_fifo.decoder)]);
1246 if(!convert_to_seek_table(options.requested_seek_points, options.num_requested_seek_points, encoder_wrapper->total_samples_to_encode, encoder_wrapper->seek_table)) {
1247 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper->inbasefilename);
1252 if(encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1253 encoder_wrapper->seek_table->is_last = false; /* the encoder will set this for us */
1254 metadata[num_metadata++] = encoder_wrapper->seek_table;
1256 if(options.padding > 0) {
1257 padding.is_last = false; /* the encoder will set this for us */
1258 padding.type = FLAC__METADATA_TYPE_PADDING;
1259 padding.length = (unsigned)options.padding;
1260 metadata[num_metadata++] = &padding;
1263 FLAC__stream_encoder_set_streamable_subset(encoder_wrapper->encoder, !options.lax);
1264 FLAC__stream_encoder_set_do_mid_side_stereo(encoder_wrapper->encoder, options.do_mid_side);
1265 FLAC__stream_encoder_set_loose_mid_side_stereo(encoder_wrapper->encoder, options.loose_mid_side);
1266 FLAC__stream_encoder_set_channels(encoder_wrapper->encoder, channels);
1267 FLAC__stream_encoder_set_bits_per_sample(encoder_wrapper->encoder, bps);
1268 FLAC__stream_encoder_set_sample_rate(encoder_wrapper->encoder, sample_rate);
1269 FLAC__stream_encoder_set_blocksize(encoder_wrapper->encoder, options.blocksize);
1270 FLAC__stream_encoder_set_max_lpc_order(encoder_wrapper->encoder, options.max_lpc_order);
1271 FLAC__stream_encoder_set_qlp_coeff_precision(encoder_wrapper->encoder, options.qlp_coeff_precision);
1272 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder_wrapper->encoder, options.do_qlp_coeff_prec_search);
1273 FLAC__stream_encoder_set_do_escape_coding(encoder_wrapper->encoder, options.do_escape_coding);
1274 FLAC__stream_encoder_set_do_exhaustive_model_search(encoder_wrapper->encoder, options.do_exhaustive_model_search);
1275 FLAC__stream_encoder_set_min_residual_partition_order(encoder_wrapper->encoder, options.min_residual_partition_order);
1276 FLAC__stream_encoder_set_max_residual_partition_order(encoder_wrapper->encoder, options.max_residual_partition_order);
1277 FLAC__stream_encoder_set_rice_parameter_search_dist(encoder_wrapper->encoder, options.rice_parameter_search_dist);
1278 FLAC__stream_encoder_set_total_samples_estimate(encoder_wrapper->encoder, encoder_wrapper->total_samples_to_encode);
1279 FLAC__stream_encoder_set_metadata(encoder_wrapper->encoder, (num_metadata > 0)? metadata : 0, num_metadata);
1280 FLAC__stream_encoder_set_write_callback(encoder_wrapper->encoder, write_callback);
1281 FLAC__stream_encoder_set_metadata_callback(encoder_wrapper->encoder, metadata_callback);
1282 FLAC__stream_encoder_set_client_data(encoder_wrapper->encoder, encoder_wrapper);
1284 if(FLAC__stream_encoder_init(encoder_wrapper->encoder) != FLAC__STREAM_ENCODER_OK) {
1285 fprintf(stderr, "%s: ERROR initializing encoder, state = %d:%s\n", encoder_wrapper->inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper->encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper->encoder)]);
1289 /* the above call writes all the metadata, so we save the stream offset now */
1290 encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
1295 FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, FLAC__StreamMetadata *seek_table)
1297 unsigned i, real_points, placeholders;
1298 char *pt = requested_seek_points, *q;
1300 if(num_requested_seek_points == 0)
1303 if(num_requested_seek_points < 0) {
1304 strcpy(requested_seek_points, "100x<");
1305 num_requested_seek_points = 1;
1308 /* first count how many individual seek points we may need */
1309 real_points = placeholders = 0;
1310 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
1311 q = strchr(pt, '<');
1312 FLAC__ASSERT(0 != q);
1315 if(0 == strcmp(pt, "X")) { /* -S X */
1318 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
1319 if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
1320 real_points += (unsigned)atoi(pt);
1329 pt = requested_seek_points;
1331 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
1332 q = strchr(pt, '<');
1333 FLAC__ASSERT(0 != q);
1336 if(0 == strcmp(pt, "X")) { /* -S X */
1337 if(!FLAC__metadata_object_seektable_template_append_placeholders(seek_table, 1))
1340 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
1341 if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
1342 if(!FLAC__metadata_object_seektable_template_append_spaced_points(seek_table, atoi(pt), stream_samples))
1347 FLAC__uint64 n = (unsigned)atoi(pt);
1348 if(!FLAC__metadata_object_seektable_template_append_point(seek_table, n))
1355 if(!FLAC__metadata_object_seektable_template_sort(seek_table, /*compact=*/true))
1361 void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
1363 unsigned wide_sample, sample, channel, byte;
1366 if(is_unsigned_samples) {
1367 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1368 for(channel = 0; channel < channels; channel++, sample++)
1369 dest[channel][wide_sample] = (FLAC__int32)ucbuffer[sample] - 0x80;
1372 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1373 for(channel = 0; channel < channels; channel++, sample++)
1374 dest[channel][wide_sample] = (FLAC__int32)scbuffer[sample];
1377 else if(bps == 16) {
1378 if(is_big_endian != is_big_endian_host) {
1380 const unsigned bytes = wide_samples * channels * (bps >> 3);
1381 for(byte = 0; byte < bytes; byte += 2) {
1382 tmp = ucbuffer[byte];
1383 ucbuffer[byte] = ucbuffer[byte+1];
1384 ucbuffer[byte+1] = tmp;
1387 if(is_unsigned_samples) {
1388 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1389 for(channel = 0; channel < channels; channel++, sample++)
1390 dest[channel][wide_sample] = (FLAC__int32)usbuffer[sample] - 0x8000;
1393 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1394 for(channel = 0; channel < channels; channel++, sample++)
1395 dest[channel][wide_sample] = (FLAC__int32)ssbuffer[sample];
1398 else if(bps == 24) {
1399 if(!is_big_endian) {
1401 const unsigned bytes = wide_samples * channels * (bps >> 3);
1402 for(byte = 0; byte < bytes; byte += 3) {
1403 tmp = ucbuffer[byte];
1404 ucbuffer[byte] = ucbuffer[byte+2];
1405 ucbuffer[byte+2] = tmp;
1408 if(is_unsigned_samples) {
1409 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1410 for(channel = 0; channel < channels; channel++, sample++) {
1411 dest[channel][wide_sample] = ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1412 dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1413 dest[channel][wide_sample] |= ucbuffer[byte++];
1414 dest[channel][wide_sample] -= 0x800000;
1418 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1419 for(channel = 0; channel < channels; channel++, sample++) {
1420 dest[channel][wide_sample] = scbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1421 dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1422 dest[channel][wide_sample] |= ucbuffer[byte++];
1430 append_to_verify_fifo(encoder_wrapper, (const FLAC__int32 * const *)dest, channels, wide_samples);
1433 void append_to_verify_fifo(encoder_wrapper_struct *encoder_wrapper, const FLAC__int32 * const input[], unsigned channels, unsigned wide_samples)
1435 if(encoder_wrapper->verify) {
1437 for(channel = 0; channel < channels; channel++)
1438 memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], input[channel], sizeof(FLAC__int32) * wide_samples);
1439 encoder_wrapper->verify_fifo.tail += wide_samples;
1440 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
1444 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
1446 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1447 const unsigned mask = (FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
1449 /* 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) */
1450 if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1451 /*@@@ WATCHOUT: assumes the encoder is fixed-blocksize, which will be true indefinitely: */
1452 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1453 const FLAC__uint64 frame_first_sample = (FLAC__uint64)current_frame * (FLAC__uint64)blocksize;
1454 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
1455 FLAC__uint64 test_sample;
1457 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1458 test_sample = encoder_wrapper->seek_table->data.seek_table.points[i].sample_number;
1459 if(test_sample > frame_last_sample) {
1462 else if(test_sample >= frame_first_sample) {
1463 encoder_wrapper->seek_table->data.seek_table.points[i].sample_number = frame_first_sample;
1464 encoder_wrapper->seek_table->data.seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
1465 encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples = blocksize;
1466 encoder_wrapper->first_seek_point_to_check++;
1467 /* DO NOT: "break;" and here's why:
1468 * The seektable template may contain more than one target
1469 * sample for any given frame; we will keep looping, generating
1470 * duplicate seekpoints for them, and we'll clean it up later,
1471 * just before writing the seektable back to the metadata.
1475 encoder_wrapper->first_seek_point_to_check++;
1480 encoder_wrapper->bytes_written += bytes;
1481 encoder_wrapper->samples_written += samples;
1482 encoder_wrapper->current_frame = current_frame;
1484 if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
1485 print_stats(encoder_wrapper);
1487 if(encoder_wrapper->verify) {
1488 encoder_wrapper->verify_fifo.encoded_signal = buffer;
1489 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
1490 if(encoder_wrapper->verify_fifo.encode_state > ENCODER_IN_MAGIC) {
1491 if(!FLAC__stream_decoder_process_single(encoder_wrapper->verify_fifo.decoder)) {
1492 encoder_wrapper->verify_fifo.result = encoder_wrapper->verify_fifo.encode_state > ENCODER_IN_METADATA? FLAC__VERIFY_FAILED_IN_FRAME : FLAC__VERIFY_FAILED_IN_METADATA;
1494 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1498 encoder_wrapper->verify_fifo.encode_state = ENCODER_IN_METADATA;
1499 encoder_wrapper->verify_fifo.needs_magic_hack = true;
1503 #ifdef FLAC__HAS_OGG
1504 if(encoder_wrapper->use_ogg) {
1507 memset(&op, 0, sizeof(op));
1508 op.packet = (unsigned char *)buffer;
1509 op.granulepos = encoder_wrapper->samples_written - 1;
1511 * this depends on the behavior of libFLAC that we will get one
1512 * write_callback first with all the metadata (and 'samples'
1513 * will be 0), then one write_callback for each frame.
1515 op.packetno = (samples == 0? -1 : (int)encoder_wrapper->current_frame);
1518 if (encoder_wrapper->bytes_written == bytes)
1521 if (encoder_wrapper->total_samples_to_encode == encoder_wrapper->samples_written)
1524 ogg_stream_packetin(&encoder_wrapper->ogg.os, &op);
1526 while(ogg_stream_pageout(&encoder_wrapper->ogg.os, &encoder_wrapper->ogg.og) != 0) {
1528 written = fwrite(encoder_wrapper->ogg.og.header, 1, encoder_wrapper->ogg.og.header_len, encoder_wrapper->fout);
1529 if (written != encoder_wrapper->ogg.og.header_len)
1530 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1532 written = fwrite(encoder_wrapper->ogg.og.body, 1, encoder_wrapper->ogg.og.body_len, encoder_wrapper->fout);
1533 if (written != encoder_wrapper->ogg.og.body_len)
1534 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1537 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1542 if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_wrapper->fout) == bytes)
1543 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1545 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1549 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
1551 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1553 FILE *f = encoder_wrapper->fout;
1554 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
1555 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
1556 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
1558 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
1561 * If we are writing to an ogg stream, there is no need to go back
1562 * and update the STREAMINFO or SEEKTABLE blocks; the values we would
1563 * update are not necessary with Ogg as the transport. We can't do
1564 * it reliably anyway without knowing the Ogg structure.
1566 #ifdef FLAC__HAS_OGG
1567 if(encoder_wrapper->use_ogg)
1572 * we get called by the encoder when the encoding process has
1573 * finished so that we can update the STREAMINFO and SEEKTABLE
1577 (void)encoder; /* silence compiler warning about unused parameter */
1580 fclose(encoder_wrapper->fout);
1581 if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
1585 /* all this is based on intimate knowledge of the stream header
1586 * layout, but a change to the header format that would break this
1587 * would also break all streams encoded in the previous format.
1590 if(-1 == fseek(f, 26, SEEK_SET)) goto end_;
1591 fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
1593 /* if we get this far we know we can seek so no need to check the
1594 * return value from fseek()
1596 fseek(f, 21, SEEK_SET);
1597 if(fread(&b, 1, 1, f) != 1) goto framesize_;
1598 fseek(f, 21, SEEK_SET);
1599 b = (b & 0xf0) | (FLAC__byte)((samples >> 32) & 0x0F);
1600 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1601 b = (FLAC__byte)((samples >> 24) & 0xFF);
1602 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1603 b = (FLAC__byte)((samples >> 16) & 0xFF);
1604 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1605 b = (FLAC__byte)((samples >> 8) & 0xFF);
1606 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1607 b = (FLAC__byte)(samples & 0xFF);
1608 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1611 fseek(f, 12, SEEK_SET);
1612 b = (FLAC__byte)((min_framesize >> 16) & 0xFF);
1613 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1614 b = (FLAC__byte)((min_framesize >> 8) & 0xFF);
1615 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1616 b = (FLAC__byte)(min_framesize & 0xFF);
1617 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1618 b = (FLAC__byte)((max_framesize >> 16) & 0xFF);
1619 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1620 b = (FLAC__byte)((max_framesize >> 8) & 0xFF);
1621 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1622 b = (FLAC__byte)(max_framesize & 0xFF);
1623 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1626 if(encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1630 (void)FLAC__metadata_object_seektable_template_sort(encoder_wrapper->seek_table, /*compact=*/false);
1632 FLAC__ASSERT(FLAC__metadata_object_seektable_is_legal(encoder_wrapper->seek_table));
1634 /* convert any unused seek points to placeholders */
1635 for(i = 0; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1636 if(encoder_wrapper->seek_table->data.seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
1638 else if(encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples == 0)
1639 encoder_wrapper->seek_table->data.seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
1642 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
1643 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1644 pos += metadata->length;
1645 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1646 fseek(f, pos, SEEK_SET);
1647 for(i = 0; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1648 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table->data.seek_table.points[i].sample_number)) goto end_;
1649 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table->data.seek_table.points[i].stream_offset)) goto end_;
1650 if(!write_big_endian_uint16(f, (FLAC__uint16)encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples)) goto end_;
1659 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
1661 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1662 const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
1665 if(encoder_wrapper->verify_fifo.needs_magic_hack) {
1666 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
1667 *bytes = FLAC__STREAM_SYNC_LENGTH;
1668 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
1669 encoder_wrapper->verify_fifo.needs_magic_hack = false;
1672 if(encoded_bytes <= *bytes) {
1673 *bytes = encoded_bytes;
1674 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1677 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1678 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
1679 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
1683 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
1686 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
1688 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1689 unsigned channel, l, r;
1690 const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
1691 const unsigned bytes_per_block = sizeof(FLAC__int32) * FLAC__stream_decoder_get_blocksize(decoder);
1693 for(channel = 0; channel < channels; channel++) {
1694 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], bytes_per_block)) {
1695 unsigned sample = 0;
1696 int expect = 0, got = 0;
1697 fprintf(stderr, "\n%s: ERROR: mismatch in decoded data, verify FAILED!\n", encoder_wrapper->inbasefilename);
1698 fprintf(stderr, " Please submit a bug report to\n");
1699 fprintf(stderr, " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1700 fprintf(stderr, " Make sure to include an email contact in the comment and/or use the\n");
1701 fprintf(stderr, " \"Monitor\" feature to monitor the bug status.\n");
1702 for(l = 0, r = FLAC__stream_decoder_get_blocksize(decoder); l < r; l++) {
1703 if(buffer[channel][l] != encoder_wrapper->verify_fifo.original[channel][l]) {
1705 expect = (int)encoder_wrapper->verify_fifo.original[channel][l];
1706 got = (int)buffer[channel][l];
1710 FLAC__ASSERT(l < r);
1711 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1712 fprintf(stderr, " Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)frame->header.number.sample_number + sample, (unsigned)frame->header.number.sample_number / FLAC__stream_decoder_get_blocksize(decoder), channel, sample, expect, got); /*@@@ WATCHOUT: 4GB limit */
1713 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1716 /* dequeue the frame from the fifo */
1717 for(channel = 0; channel < channels; channel++) {
1718 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
1719 encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
1722 encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
1723 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1726 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1733 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1735 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1737 fprintf(stderr, "\n%s: ERROR: verification decoder returned error %d:%s\n", encoder_wrapper->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1740 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1742 #if defined _MSC_VER || defined __MINGW32__
1743 /* with VC++ you have to spoon feed it the casting */
1744 const double progress = (double)(FLAC__int64)encoder_wrapper->samples_written / (double)(FLAC__int64)encoder_wrapper->total_samples_to_encode;
1745 const double ratio = (double)(FLAC__int64)encoder_wrapper->bytes_written / ((double)(FLAC__int64)encoder_wrapper->unencoded_size * progress);
1747 const double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1748 const double ratio = (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress);
1751 if(encoder_wrapper->samples_written == encoder_wrapper->total_samples_to_encode) {
1752 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1753 encoder_wrapper->inbasefilename,
1754 encoder_wrapper->verify? (encoder_wrapper->verify_fifo.result == FLAC__VERIFY_OK? " Verify OK," : " Verify FAILED!") : "",
1755 (unsigned)encoder_wrapper->bytes_written,
1760 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_wrapper->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1764 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1766 size_t bytes_read = fread(val, 1, 2, f);
1768 if(bytes_read == 0) {
1770 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1776 else if(bytes_read < 2) {
1777 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1781 if(is_big_endian_host) {
1782 FLAC__byte tmp, *b = (FLAC__byte*)val;
1783 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1789 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1791 size_t bytes_read = fread(val, 1, 4, f);
1793 if(bytes_read == 0) {
1795 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1801 else if(bytes_read < 4) {
1802 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1806 if(is_big_endian_host) {
1807 FLAC__byte tmp, *b = (FLAC__byte*)val;
1808 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1809 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1816 read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1818 unsigned char buf[4];
1819 size_t bytes_read= fread(buf, 1, 2, f);
1821 if(bytes_read==0U && eof_ok)
1823 else if(bytes_read<2U) {
1824 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1828 /* this is independent of host endianness */
1829 *val= (FLAC__uint16)(buf[0])<<8 | buf[1];
1835 read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1837 unsigned char buf[4];
1838 size_t bytes_read= fread(buf, 1, 4, f);
1840 if(bytes_read==0U && eof_ok)
1842 else if(bytes_read<4U) {
1843 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1847 /* this is independent of host endianness */
1848 *val= (FLAC__uint32)(buf[0])<<24 | (FLAC__uint32)(buf[1])<<16 |
1849 (FLAC__uint32)(buf[2])<<8 | buf[3];
1855 read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1856 /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
1857 * convert it into an integral value and store in 'val'. Return false if only
1858 * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f' and 'eof_ok' is
1859 * false, or if the value is negative, between zero and one, or too large to be
1860 * represented by 'val'; return true otherwise.
1864 unsigned char buf[10];
1865 size_t bytes_read= fread(buf, 1U, 10U, f);
1866 FLAC__int16 e= ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
1867 FLAC__int16 shift= 63-e;
1870 if(bytes_read==0U && eof_ok)
1872 else if(bytes_read<10U) {
1873 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1876 else if((buf[0]>>7)==1U || e<0 || e>63) {
1877 fprintf(stderr, "%s: ERROR: invalid floating-point value\n", fn);
1881 for(i= 0U; i<8U; ++i)
1882 p|= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
1883 *val= (FLAC__uint32)(p>>shift)+(p>>(shift-1) & 0x1);
1888 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
1890 if(!is_big_endian_host) {
1891 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1892 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1894 return fwrite(&val, 1, 2, f) == 2;
1897 FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val)
1899 if(!is_big_endian_host) {
1900 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1901 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1902 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1903 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1904 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1906 return fwrite(&val, 1, 8, f) == 8;