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() */
34 #include "OggFLAC/stream_encoder.h"
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
46 const char *inbasefilename;
48 const char *outfilename;
49 FLAC__StreamEncoder *encoder;
52 FLAC__uint64 unencoded_size;
53 FLAC__uint64 total_samples_to_encode;
54 FLAC__uint64 bytes_written;
55 FLAC__uint64 samples_written;
56 FLAC__uint64 stream_offset; /* i.e. number of bytes before the first byte of the the first frame's header */
57 unsigned current_frame;
58 FLAC__StreamMetadata *seek_table;
59 unsigned first_seek_point_to_check;
60 FLAC__bool verify_failed;
63 OggFLAC__StreamEncoder *ogg_encoder;
65 } encoder_wrapper_struct;
67 static FLAC__bool is_big_endian_host;
69 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
70 static signed char *scbuffer = (signed char *)ucbuffer;
71 static FLAC__uint16 *usbuffer = (FLAC__uint16 *)ucbuffer;
72 static FLAC__int16 *ssbuffer = (FLAC__int16 *)ucbuffer;
74 static FLAC__int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
75 static FLAC__int32 *input[FLAC__MAX_CHANNELS];
78 static FLAC__bool init(encoder_wrapper_struct *encoder_wrapper);
79 static FLAC__bool init_encoder(encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper);
80 static FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, FLAC__StreamMetadata *seek_table);
81 static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps);
82 static FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
83 static void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
84 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
85 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
86 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
87 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
88 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
89 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
90 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
91 static FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val);
94 flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const char *outfilename,
95 const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
97 encoder_wrapper_struct encoder_wrapper;
100 unsigned int channels= 0U, bps= 0U, sample_rate= 0U, sample_frames= 0U;
101 FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
102 int info_align_carry= -1, info_align_zero= -1;
103 enum { NORMAL, DONE, ERROR, MISMATCH } status= NORMAL;
105 FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
107 encoder_wrapper.encoder = 0;
108 encoder_wrapper.verify = options.common.verify;
109 encoder_wrapper.verbose = options.common.verbose;
110 encoder_wrapper.bytes_written = 0;
111 encoder_wrapper.samples_written = 0;
112 encoder_wrapper.stream_offset = 0;
113 encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
114 encoder_wrapper.outfilename = outfilename;
115 encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
116 encoder_wrapper.first_seek_point_to_check = 0;
117 encoder_wrapper.verify_failed = false;
119 encoder_wrapper.use_ogg = options.common.use_ogg;
120 encoder_wrapper.ogg_encoder = 0;
123 if(0 == encoder_wrapper.seek_table) {
124 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
128 (void)infilesize; /* silence compiler warning about unused parameter */
129 (void)lookahead; /* silence compiler warning about unused parameter */
130 (void)lookahead_length; /* silence compiler warning about unused parameter */
132 if(0 == strcmp(outfilename, "-")) {
133 encoder_wrapper.fout = file__get_binary_stdout();
136 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
137 fprintf(stderr, "%s: ERROR: can't open output file %s\n", encoder_wrapper.inbasefilename, outfilename);
144 if(!init(&encoder_wrapper))
147 /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
149 while(status==NORMAL) {
153 /* chunk identifier; really conservative about behavior of fread() and feof() */
154 if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
156 else if(c<4U || feof(infile)) {
157 fprintf(stderr, "%s: ERROR: incomplete chunk identifier\n", encoder_wrapper.inbasefilename);
161 if(status==NORMAL && got_comm_chunk==false && !strncmp(chunk_id, "COMM", 4)) { /* common chunk */
165 /* COMM chunk size */
166 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
169 fprintf(stderr, "%s: ERROR: non-standard 'COMM' chunk has length = %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
173 fprintf(stderr, "%s: WARNING: non-standard 'COMM' chunk has length = %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
174 skip= (xx-18U)+(xx & 1U);
178 /* number of channels */
179 if(!read_big_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
181 else if(x==0U || x>FLAC__MAX_CHANNELS) {
182 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned int)x);
185 else if(options.common.sector_align && x!=2U) {
186 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)x);
193 /* number of sample frames */
194 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
200 /* bits per sample */
201 if(!read_big_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
203 else if(x!=8U && x!=16U && x!=24U) {
204 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned int)x);
207 else if(options.common.sector_align && x!=16U) {
208 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)x);
216 if(!read_sane_extended(infile, &xx, false, encoder_wrapper.inbasefilename))
218 else if(!FLAC__format_sample_rate_is_valid(xx)) {
219 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
222 else if(options.common.sector_align && xx!=44100U) {
223 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
229 /* skip any extra data in the COMM chunk */
230 FLAC__ASSERT(skip<=LONG_MAX);
231 while(status==NORMAL && skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
232 unsigned int need= min(skip, sizeof ucbuffer);
233 if(fread(ucbuffer, 1U, need, infile)<need) {
234 fprintf(stderr, "%s: ERROR during read while skipping extra COMM data\n", encoder_wrapper.inbasefilename);
240 got_comm_chunk= true;
242 else if(status==NORMAL && got_ssnd_chunk==false && !strncmp(chunk_id, "SSND", 4)) { /* sound data chunk */
243 unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
244 size_t bytes_per_frame= channels*(bps>>3);
245 FLAC__bool pad= false;
247 if(status==NORMAL && got_comm_chunk==false) {
248 fprintf(stderr, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", encoder_wrapper.inbasefilename);
253 /* SSND chunk size */
254 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
256 else if(xx!=(sample_frames*bytes_per_frame + 8U)) {
257 fprintf(stderr, "%s: ERROR: SSND chunk size inconsistent with sample frame count\n", encoder_wrapper.inbasefilename);
261 pad= (data_bytes & 1U) ? true : false;
266 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
269 fprintf(stderr, "%s: ERROR: offset is %u; must be 0\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
277 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
280 fprintf(stderr, "%s: ERROR: block size is %u; must be 0\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
286 if(status==NORMAL && options.common.skip>0U) {
287 FLAC__uint64 remaining= options.common.skip*bytes_per_frame;
289 /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
290 /* is guaranteed to be less than LONG_MAX */
291 for(; remaining>0U; remaining-= remaining>(1U<<30) ? remaining : (1U<<30))
293 unsigned long skip= remaining % (1U<<30);
295 FLAC__ASSERT(skip<=LONG_MAX);
296 while(status==NORMAL && skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
297 unsigned int need= min(skip, sizeof ucbuffer);
298 if(fread(ucbuffer, 1U, need, infile)<need) {
299 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
308 data_bytes-= (8U + (unsigned int)options.common.skip*bytes_per_frame); /*@@@ WATCHOUT: 4GB limit */
309 encoder_wrapper.total_samples_to_encode= data_bytes/bytes_per_frame + *options.common.align_reservoir_samples;
310 if(options.common.sector_align) {
311 align_remainder= (unsigned int)(encoder_wrapper.total_samples_to_encode % 588U);
312 if(options.common.is_last_file)
313 encoder_wrapper.total_samples_to_encode+= (588U-align_remainder); /* will pad with zeroes */
315 encoder_wrapper.total_samples_to_encode-= align_remainder; /* will stop short and carry over to next file */
318 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
319 encoder_wrapper.unencoded_size= encoder_wrapper.total_samples_to_encode*bytes_per_frame+54;
321 if(!init_encoder(options.common, channels, bps, sample_rate, &encoder_wrapper))
325 /* first do any samples in the reservoir */
326 if(status==NORMAL && options.common.sector_align && *options.common.align_reservoir_samples>0U) {
328 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
329 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)]);
330 encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
335 /* decrement the data_bytes counter if we need to align the file */
336 if(status==NORMAL && options.common.sector_align) {
337 if(options.common.is_last_file)
338 *options.common.align_reservoir_samples= 0U;
340 *options.common.align_reservoir_samples= align_remainder;
341 data_bytes-= (*options.common.align_reservoir_samples)*bytes_per_frame;
345 /* now do from the file */
346 while(status==NORMAL && data_bytes>0) {
347 size_t bytes_read= fread(ucbuffer, 1U, min(data_bytes, CHUNK_OF_SAMPLES*bytes_per_frame), infile);
351 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
354 else if(feof(infile)) {
355 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);
360 if(bytes_read % bytes_per_frame != 0U) {
361 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
365 unsigned int frames= bytes_read/bytes_per_frame;
366 format_input(input, frames, true, false, channels, bps);
368 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)input, frames)) {
369 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)]);
370 encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
374 data_bytes-= bytes_read;
379 /* now read unaligned samples into reservoir or pad with zeroes if necessary */
380 if(status==NORMAL && options.common.sector_align) {
381 if(options.common.is_last_file) {
382 unsigned int pad_frames= 588U-align_remainder;
384 if(pad_frames<588U) {
387 info_align_zero= pad_frames;
388 for(i= 0U; i<channels; ++i)
389 memset(input[i], 0, pad_frames*(bps>>3));
391 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)input, pad_frames)) {
392 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)]);
393 encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
399 if(*options.common.align_reservoir_samples > 0) {
400 size_t bytes_read= fread(ucbuffer, 1U, (*options.common.align_reservoir_samples)*bytes_per_frame, infile);
402 FLAC__ASSERT(CHUNK_OF_SAMPLES>=588U);
403 if(bytes_read==0U && ferror(infile)) {
404 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
407 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame)
408 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);
410 info_align_carry= *options.common.align_reservoir_samples;
411 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, true, false, channels, bps);
417 if(status==NORMAL && pad==true) {
420 if(fread(&tmp, 1U, 1U, infile)<1U) {
421 fprintf(stderr, "%s: ERROR during read of SSND pad byte\n", encoder_wrapper.inbasefilename);
426 got_ssnd_chunk= true;
428 else if(status==NORMAL) { /* other chunk */
429 if(!strncmp(chunk_id, "COMM", 4))
430 fprintf(stderr, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_wrapper.inbasefilename);
431 else if(!strncmp(chunk_id, "SSND", 4))
432 fprintf(stderr, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_wrapper.inbasefilename);
434 fprintf(stderr, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_wrapper.inbasefilename, chunk_id);
437 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
440 unsigned long skip= xx+(xx & 1U);
442 FLAC__ASSERT(skip<=LONG_MAX);
443 while(status==NORMAL && skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
444 unsigned int need= min(skip, sizeof ucbuffer);
445 if(fread(ucbuffer, 1U, need, infile)<need) {
446 fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_wrapper.inbasefilename);
455 if(got_ssnd_chunk==false && sample_frames!=0U) {
456 fprintf(stderr, "%s: ERROR: missing SSND chunk\n", encoder_wrapper.inbasefilename);
460 if(encoder_wrapper.encoder) {
461 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
462 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
464 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
466 print_stats(&encoder_wrapper);
467 fprintf(stderr, "\n");
470 if(0 != encoder_wrapper.seek_table)
471 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
472 if(options.common.verify) {
473 if(encoder_wrapper.verify_failed) {
474 fprintf(stderr, "Verify FAILED! Do not trust %s\n", outfilename);
483 if(info_align_carry >= 0)
484 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
485 if(info_align_zero >= 0)
486 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
488 else if(status==ERROR)
491 return status==ERROR || status==MISMATCH;
494 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)
496 encoder_wrapper_struct encoder_wrapper;
497 FLAC__bool is_unsigned_samples = false;
498 unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
499 size_t bytes_per_wide_sample, bytes_read;
502 FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
503 unsigned align_remainder = 0;
504 int info_align_carry = -1, info_align_zero = -1;
506 FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
508 encoder_wrapper.encoder = 0;
509 encoder_wrapper.verify = options.common.verify;
510 encoder_wrapper.verbose = options.common.verbose;
511 encoder_wrapper.bytes_written = 0;
512 encoder_wrapper.samples_written = 0;
513 encoder_wrapper.stream_offset = 0;
514 encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
515 encoder_wrapper.outfilename = outfilename;
516 encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
517 encoder_wrapper.first_seek_point_to_check = 0;
518 encoder_wrapper.verify_failed = false;
520 encoder_wrapper.use_ogg = options.common.use_ogg;
521 encoder_wrapper.ogg_encoder = 0;
525 (void)lookahead_length;
527 if(0 == encoder_wrapper.seek_table) {
528 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
532 if(0 == strcmp(outfilename, "-")) {
533 encoder_wrapper.fout = file__get_binary_stdout();
536 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
537 fprintf(stderr, "%s: ERROR: can't open output file %s\n", encoder_wrapper.inbasefilename, outfilename);
544 if(!init(&encoder_wrapper))
548 * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
550 while(!feof(infile)) {
551 if(!read_little_endian_uint32(infile, &xx, true, encoder_wrapper.inbasefilename))
555 if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
556 /* fmt sub-chunk size */
557 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
560 fprintf(stderr, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
563 else if(xx != 16 && xx != 18) {
564 fprintf(stderr, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
567 /* compression code */
568 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
571 fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
574 /* number of channels */
575 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
577 if(x == 0 || x > FLAC__MAX_CHANNELS) {
578 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
581 else if(options.common.sector_align && x != 2) {
582 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)x);
587 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
589 if(!FLAC__format_sample_rate_is_valid(xx)) {
590 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
593 else if(options.common.sector_align && xx != 44100) {
594 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)xx);
598 /* avg bytes per second (ignored) */
599 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
601 /* block align (ignored) */
602 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
604 /* bits per sample */
605 if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
607 if(x != 8 && x != 16 && x != 24) {
608 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
611 else if(options.common.sector_align && x != 16) {
612 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)x);
616 is_unsigned_samples = (x == 8);
618 /* skip any extra data in the fmt sub-chunk */
622 for(left = data_bytes; left > 0; ) {
623 need = min(left, CHUNK_OF_SAMPLES);
624 if(fread(ucbuffer, 1U, need, infile) < need) {
625 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
632 got_fmt_chunk = true;
634 else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
636 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
640 bytes_per_wide_sample = channels * (bps >> 3);
642 if(options.common.skip > 0) {
643 if(fseek(infile, bytes_per_wide_sample * (unsigned)options.common.skip, SEEK_CUR) < 0) {
644 /* can't seek input, read ahead manually... */
646 for(left = (unsigned)options.common.skip; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
647 need = min(left, CHUNK_OF_SAMPLES);
648 if(fread(ucbuffer, bytes_per_wide_sample, need, infile) < need) {
649 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
657 data_bytes -= (unsigned)options.common.skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
658 encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample + *options.common.align_reservoir_samples;
659 if(options.common.sector_align) {
660 align_remainder = (unsigned)(encoder_wrapper.total_samples_to_encode % 588);
661 if(options.common.is_last_file)
662 encoder_wrapper.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
664 encoder_wrapper.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
667 /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
668 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44;
670 if(!init_encoder(options.common, channels, bps, sample_rate, &encoder_wrapper))
674 * first do any samples in the reservoir
676 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
677 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
678 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)]);
679 encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
685 * decrement the data_bytes counter if we need to align the file
687 if(options.common.sector_align) {
688 if(options.common.is_last_file) {
689 *options.common.align_reservoir_samples = 0;
692 *options.common.align_reservoir_samples = align_remainder;
693 data_bytes -= (*options.common.align_reservoir_samples) * bytes_per_wide_sample;
698 * now do from the file
700 while(data_bytes > 0) {
701 bytes_read = fread(ucbuffer, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
702 if(bytes_read == 0) {
704 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
707 else if(feof(infile)) {
708 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);
713 if(bytes_read % bytes_per_wide_sample != 0) {
714 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
718 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
719 format_input(input, wide_samples, false, is_unsigned_samples, channels, bps);
721 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
722 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)]);
723 encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
726 data_bytes -= bytes_read;
732 * now read unaligned samples into reservoir or pad with zeroes if necessary
734 if(options.common.sector_align) {
735 if(options.common.is_last_file) {
736 unsigned wide_samples = 588 - align_remainder;
737 if(wide_samples < 588) {
740 info_align_zero = wide_samples;
741 data_bytes = wide_samples * (bps >> 3);
742 for(channel = 0; channel < channels; channel++)
743 memset(input[channel], 0, data_bytes);
745 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
746 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)]);
747 encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
753 if(*options.common.align_reservoir_samples > 0) {
754 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
755 bytes_read = fread(ucbuffer, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
756 if(bytes_read == 0 && ferror(infile)) {
757 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
760 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
761 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);
765 info_align_carry = *options.common.align_reservoir_samples;
766 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, is_unsigned_samples, channels, bps);
772 got_data_chunk = true;
775 if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
776 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_wrapper.inbasefilename);
778 else if(xx == 0x61746164) { /* "data" */
780 fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_wrapper.inbasefilename);
782 else if(!got_fmt_chunk) {
783 fprintf(stderr, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_wrapper.inbasefilename);
791 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));
794 if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
796 if(fseek(infile, xx, SEEK_CUR) < 0) {
797 /* can't seek input, read ahead manually... */
799 const unsigned chunk = sizeof(ucbuffer);
800 for(left = xx; left > 0; ) {
801 need = min(left, chunk);
802 if(fread(ucbuffer, 1, need, infile) < need) {
803 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_wrapper.inbasefilename);
812 if(encoder_wrapper.encoder) {
813 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
814 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
816 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
817 print_stats(&encoder_wrapper);
818 fprintf(stderr, "\n");
820 if(0 != encoder_wrapper.seek_table)
821 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
822 if(options.common.verify) {
823 if(encoder_wrapper.verify_failed) {
824 fprintf(stderr, "Verify FAILED! Do not trust %s\n", outfilename);
828 if(info_align_carry >= 0)
829 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
830 if(info_align_zero >= 0)
831 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
836 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
837 fprintf(stderr, "\n");
838 if(encoder_wrapper.encoder) {
839 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
840 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
842 if(0 != encoder_wrapper.seek_table)
843 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
844 if(options.common.verify) {
845 if(encoder_wrapper.verify_failed) {
846 fprintf(stderr, "Verify FAILED! Do not trust %s\n", outfilename);
856 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)
858 encoder_wrapper_struct encoder_wrapper;
860 const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
861 unsigned align_remainder = 0;
862 int info_align_carry = -1, info_align_zero = -1;
864 FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
865 FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
866 FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
867 FLAC__ASSERT(!options.common.sector_align || options.sample_rate == 44100);
868 FLAC__ASSERT(!options.common.sector_align || infilesize >= 0);
870 encoder_wrapper.encoder = 0;
871 encoder_wrapper.verify = options.common.verify;
872 encoder_wrapper.verbose = options.common.verbose;
873 encoder_wrapper.bytes_written = 0;
874 encoder_wrapper.samples_written = 0;
875 encoder_wrapper.stream_offset = 0;
876 encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
877 encoder_wrapper.outfilename = outfilename;
878 encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
879 encoder_wrapper.first_seek_point_to_check = 0;
880 encoder_wrapper.verify_failed = false;
882 encoder_wrapper.use_ogg = options.common.use_ogg;
883 encoder_wrapper.ogg_encoder = 0;
886 if(0 == encoder_wrapper.seek_table) {
887 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
891 if(0 == strcmp(outfilename, "-")) {
892 encoder_wrapper.fout = file__get_binary_stdout();
895 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
896 fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
903 if(!init(&encoder_wrapper))
906 /* get the file length */
908 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
911 if(options.common.sector_align) {
912 FLAC__ASSERT(options.common.skip == 0);
913 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
914 align_remainder = (unsigned)(encoder_wrapper.total_samples_to_encode % 588);
915 if(options.common.is_last_file)
916 encoder_wrapper.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
918 encoder_wrapper.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
921 encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - options.common.skip;
924 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample;
927 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
928 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
930 if(options.common.skip > 0) {
931 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)options.common.skip;
932 if(skip_bytes > lookahead_length) {
933 skip_bytes -= lookahead_length;
934 lookahead_length = 0;
935 if(fseek(infile, (long)skip_bytes, SEEK_CUR) < 0) {
936 /* can't seek input, read ahead manually... */
938 const unsigned chunk = sizeof(ucbuffer);
939 for(left = skip_bytes; left > 0; ) {
940 need = min(left, chunk);
941 if(fread(ucbuffer, 1, need, infile) < need) {
942 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
950 lookahead += skip_bytes;
951 lookahead_length -= skip_bytes;
955 if(!init_encoder(options.common, options.channels, options.bps, options.sample_rate, &encoder_wrapper))
959 * first do any samples in the reservoir
961 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
962 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
963 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)]);
964 encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
970 * decrement infilesize if we need to align the file
972 if(options.common.sector_align) {
973 FLAC__ASSERT(infilesize >= 0);
974 if(options.common.is_last_file) {
975 *options.common.align_reservoir_samples = 0;
978 *options.common.align_reservoir_samples = align_remainder;
979 infilesize -= (long)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
984 * now do from the file
986 while(!feof(infile)) {
987 if(lookahead_length > 0) {
988 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
989 memcpy(ucbuffer, lookahead, lookahead_length);
990 bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
992 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
995 lookahead_length = 0;
998 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
1000 if(bytes_read == 0) {
1001 if(ferror(infile)) {
1002 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
1006 else if(bytes_read % bytes_per_wide_sample != 0) {
1007 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
1011 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1012 format_input(input, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
1014 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
1015 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)]);
1016 encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
1023 * now read unaligned samples into reservoir or pad with zeroes if necessary
1025 if(options.common.sector_align) {
1026 if(options.common.is_last_file) {
1027 unsigned wide_samples = 588 - align_remainder;
1028 if(wide_samples < 588) {
1029 unsigned channel, data_bytes;
1031 info_align_zero = wide_samples;
1032 data_bytes = wide_samples * (options.bps >> 3);
1033 for(channel = 0; channel < options.channels; channel++)
1034 memset(input[channel], 0, data_bytes);
1036 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
1037 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)]);
1038 encoder_wrapper.verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper.encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
1044 if(*options.common.align_reservoir_samples > 0) {
1045 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1046 bytes_read = fread(ucbuffer, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
1047 if(bytes_read == 0 && ferror(infile)) {
1048 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
1051 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
1052 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);
1055 info_align_carry = *options.common.align_reservoir_samples;
1056 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, options.is_unsigned_samples, options.channels, options.bps);
1062 if(encoder_wrapper.encoder) {
1063 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
1064 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
1066 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
1067 print_stats(&encoder_wrapper);
1068 fprintf(stderr, "\n");
1070 if(0 != encoder_wrapper.seek_table)
1071 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
1072 if(options.common.verify) {
1073 if(encoder_wrapper.verify_failed) {
1074 fprintf(stderr, "Verify FAILED! Do not trust %s\n", outfilename);
1078 if(info_align_carry >= 0)
1079 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
1080 if(info_align_zero >= 0)
1081 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
1086 if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
1087 fprintf(stderr, "\n");
1088 if(encoder_wrapper.encoder) {
1089 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
1090 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
1092 if(0 != encoder_wrapper.seek_table)
1093 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
1094 if(options.common.verify) {
1095 if(encoder_wrapper.verify_failed) {
1096 fprintf(stderr, "Verify FAILED! Do not trust %s\n", outfilename);
1102 unlink(outfilename);
1106 FLAC__bool init(encoder_wrapper_struct *encoder_wrapper)
1109 FLAC__uint32 test = 1;
1111 is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
1113 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1114 input[i] = &(in[i][0]);
1116 encoder_wrapper->encoder = FLAC__stream_encoder_new();
1117 if(0 == encoder_wrapper->encoder) {
1118 fprintf(stderr, "%s: ERROR creating the encoder instance\n", encoder_wrapper->inbasefilename);
1125 FLAC__bool init_encoder(encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper)
1127 unsigned num_metadata;
1128 FLAC__StreamMetadata padding;
1129 FLAC__StreamMetadata *metadata[2];
1132 options.do_mid_side = options.loose_mid_side = false;
1134 if(!convert_to_seek_table(options.requested_seek_points, options.num_requested_seek_points, encoder_wrapper->total_samples_to_encode, encoder_wrapper->seek_table)) {
1135 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper->inbasefilename);
1140 if(encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1141 encoder_wrapper->seek_table->is_last = false; /* the encoder will set this for us */
1142 metadata[num_metadata++] = encoder_wrapper->seek_table;
1144 if(options.padding > 0) {
1145 padding.is_last = false; /* the encoder will set this for us */
1146 padding.type = FLAC__METADATA_TYPE_PADDING;
1147 padding.length = (unsigned)options.padding;
1148 metadata[num_metadata++] = &padding;
1151 FLAC__stream_encoder_set_verify(encoder_wrapper->encoder, options.verify);
1152 FLAC__stream_encoder_set_streamable_subset(encoder_wrapper->encoder, !options.lax);
1153 FLAC__stream_encoder_set_do_mid_side_stereo(encoder_wrapper->encoder, options.do_mid_side);
1154 FLAC__stream_encoder_set_loose_mid_side_stereo(encoder_wrapper->encoder, options.loose_mid_side);
1155 FLAC__stream_encoder_set_channels(encoder_wrapper->encoder, channels);
1156 FLAC__stream_encoder_set_bits_per_sample(encoder_wrapper->encoder, bps);
1157 FLAC__stream_encoder_set_sample_rate(encoder_wrapper->encoder, sample_rate);
1158 FLAC__stream_encoder_set_blocksize(encoder_wrapper->encoder, options.blocksize);
1159 FLAC__stream_encoder_set_max_lpc_order(encoder_wrapper->encoder, options.max_lpc_order);
1160 FLAC__stream_encoder_set_qlp_coeff_precision(encoder_wrapper->encoder, options.qlp_coeff_precision);
1161 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder_wrapper->encoder, options.do_qlp_coeff_prec_search);
1162 FLAC__stream_encoder_set_do_escape_coding(encoder_wrapper->encoder, options.do_escape_coding);
1163 FLAC__stream_encoder_set_do_exhaustive_model_search(encoder_wrapper->encoder, options.do_exhaustive_model_search);
1164 FLAC__stream_encoder_set_min_residual_partition_order(encoder_wrapper->encoder, options.min_residual_partition_order);
1165 FLAC__stream_encoder_set_max_residual_partition_order(encoder_wrapper->encoder, options.max_residual_partition_order);
1166 FLAC__stream_encoder_set_rice_parameter_search_dist(encoder_wrapper->encoder, options.rice_parameter_search_dist);
1167 FLAC__stream_encoder_set_total_samples_estimate(encoder_wrapper->encoder, encoder_wrapper->total_samples_to_encode);
1168 FLAC__stream_encoder_set_metadata(encoder_wrapper->encoder, (num_metadata > 0)? metadata : 0, num_metadata);
1169 FLAC__stream_encoder_set_write_callback(encoder_wrapper->encoder, write_callback);
1170 FLAC__stream_encoder_set_metadata_callback(encoder_wrapper->encoder, metadata_callback);
1171 FLAC__stream_encoder_set_client_data(encoder_wrapper->encoder, encoder_wrapper);
1173 if(FLAC__stream_encoder_init(encoder_wrapper->encoder) != FLAC__STREAM_ENCODER_OK) {
1174 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)]);
1175 encoder_wrapper->verify_failed = (FLAC__stream_encoder_get_state(encoder_wrapper->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA);
1179 /* the above call writes all the metadata, so we save the stream offset now */
1180 encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
1185 FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, FLAC__StreamMetadata *seek_table)
1187 unsigned i, real_points, placeholders;
1188 char *pt = requested_seek_points, *q;
1190 if(num_requested_seek_points == 0)
1193 if(num_requested_seek_points < 0) {
1194 strcpy(requested_seek_points, "100x<");
1195 num_requested_seek_points = 1;
1198 /* first count how many individual seek points we may need */
1199 real_points = placeholders = 0;
1200 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
1201 q = strchr(pt, '<');
1202 FLAC__ASSERT(0 != q);
1205 if(0 == strcmp(pt, "X")) { /* -S X */
1208 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
1209 if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
1210 real_points += (unsigned)atoi(pt);
1219 pt = requested_seek_points;
1221 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
1222 q = strchr(pt, '<');
1223 FLAC__ASSERT(0 != q);
1226 if(0 == strcmp(pt, "X")) { /* -S X */
1227 if(!FLAC__metadata_object_seektable_template_append_placeholders(seek_table, 1))
1230 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
1231 if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
1232 if(!FLAC__metadata_object_seektable_template_append_spaced_points(seek_table, atoi(pt), stream_samples))
1237 FLAC__uint64 n = (unsigned)atoi(pt);
1238 if(!FLAC__metadata_object_seektable_template_append_point(seek_table, n))
1245 if(!FLAC__metadata_object_seektable_template_sort(seek_table, /*compact=*/true))
1251 void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps)
1253 unsigned wide_sample, sample, channel, byte;
1256 if(is_unsigned_samples) {
1257 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1258 for(channel = 0; channel < channels; channel++, sample++)
1259 dest[channel][wide_sample] = (FLAC__int32)ucbuffer[sample] - 0x80;
1262 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1263 for(channel = 0; channel < channels; channel++, sample++)
1264 dest[channel][wide_sample] = (FLAC__int32)scbuffer[sample];
1267 else if(bps == 16) {
1268 if(is_big_endian != is_big_endian_host) {
1270 const unsigned bytes = wide_samples * channels * (bps >> 3);
1271 for(byte = 0; byte < bytes; byte += 2) {
1272 tmp = ucbuffer[byte];
1273 ucbuffer[byte] = ucbuffer[byte+1];
1274 ucbuffer[byte+1] = tmp;
1277 if(is_unsigned_samples) {
1278 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1279 for(channel = 0; channel < channels; channel++, sample++)
1280 dest[channel][wide_sample] = (FLAC__int32)usbuffer[sample] - 0x8000;
1283 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1284 for(channel = 0; channel < channels; channel++, sample++)
1285 dest[channel][wide_sample] = (FLAC__int32)ssbuffer[sample];
1288 else if(bps == 24) {
1289 if(!is_big_endian) {
1291 const unsigned bytes = wide_samples * channels * (bps >> 3);
1292 for(byte = 0; byte < bytes; byte += 3) {
1293 tmp = ucbuffer[byte];
1294 ucbuffer[byte] = ucbuffer[byte+2];
1295 ucbuffer[byte+2] = tmp;
1298 if(is_unsigned_samples) {
1299 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1300 for(channel = 0; channel < channels; channel++, sample++) {
1301 dest[channel][wide_sample] = ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1302 dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1303 dest[channel][wide_sample] |= ucbuffer[byte++];
1304 dest[channel][wide_sample] -= 0x800000;
1308 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1309 for(channel = 0; channel < channels; channel++, sample++) {
1310 dest[channel][wide_sample] = scbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1311 dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1312 dest[channel][wide_sample] |= ucbuffer[byte++];
1321 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
1323 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1324 const unsigned mask = (FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
1326 /* 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) */
1327 if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1328 /*@@@ WATCHOUT: assumes the encoder is fixed-blocksize, which will be true indefinitely: */
1329 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1330 const FLAC__uint64 frame_first_sample = (FLAC__uint64)current_frame * (FLAC__uint64)blocksize;
1331 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
1332 FLAC__uint64 test_sample;
1334 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1335 test_sample = encoder_wrapper->seek_table->data.seek_table.points[i].sample_number;
1336 if(test_sample > frame_last_sample) {
1339 else if(test_sample >= frame_first_sample) {
1340 encoder_wrapper->seek_table->data.seek_table.points[i].sample_number = frame_first_sample;
1341 encoder_wrapper->seek_table->data.seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
1342 encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples = blocksize;
1343 encoder_wrapper->first_seek_point_to_check++;
1344 /* DO NOT: "break;" and here's why:
1345 * The seektable template may contain more than one target
1346 * sample for any given frame; we will keep looping, generating
1347 * duplicate seekpoints for them, and we'll clean it up later,
1348 * just before writing the seektable back to the metadata.
1352 encoder_wrapper->first_seek_point_to_check++;
1357 encoder_wrapper->bytes_written += bytes;
1358 encoder_wrapper->samples_written += samples;
1359 encoder_wrapper->current_frame = current_frame;
1361 if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
1362 print_stats(encoder_wrapper);
1364 if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_wrapper->fout) == bytes)
1365 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1367 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1370 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
1372 encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1374 FILE *f = encoder_wrapper->fout;
1375 const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
1376 const unsigned min_framesize = metadata->data.stream_info.min_framesize;
1377 const unsigned max_framesize = metadata->data.stream_info.max_framesize;
1379 FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
1382 * If we are writing to an ogg stream, there is no need to go back
1383 * and update the STREAMINFO or SEEKTABLE blocks; the values we would
1384 * update are not necessary with Ogg as the transport. We can't do
1385 * it reliably anyway without knowing the Ogg structure.
1387 #ifdef FLAC__HAS_OGG
1388 if(encoder_wrapper->use_ogg)
1393 * we get called by the encoder when the encoding process has
1394 * finished so that we can update the STREAMINFO and SEEKTABLE
1398 (void)encoder; /* silence compiler warning about unused parameter */
1401 fclose(encoder_wrapper->fout);
1402 if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
1406 /* all this is based on intimate knowledge of the stream header
1407 * layout, but a change to the header format that would break this
1408 * would also break all streams encoded in the previous format.
1411 if(-1 == fseek(f, 26, SEEK_SET)) goto end_;
1412 fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
1414 /* if we get this far we know we can seek so no need to check the
1415 * return value from fseek()
1417 fseek(f, 21, SEEK_SET);
1418 if(fread(&b, 1, 1, f) != 1) goto framesize_;
1419 fseek(f, 21, SEEK_SET);
1420 b = (b & 0xf0) | (FLAC__byte)((samples >> 32) & 0x0F);
1421 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1422 b = (FLAC__byte)((samples >> 24) & 0xFF);
1423 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1424 b = (FLAC__byte)((samples >> 16) & 0xFF);
1425 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1426 b = (FLAC__byte)((samples >> 8) & 0xFF);
1427 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1428 b = (FLAC__byte)(samples & 0xFF);
1429 if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1432 fseek(f, 12, SEEK_SET);
1433 b = (FLAC__byte)((min_framesize >> 16) & 0xFF);
1434 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1435 b = (FLAC__byte)((min_framesize >> 8) & 0xFF);
1436 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1437 b = (FLAC__byte)(min_framesize & 0xFF);
1438 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1439 b = (FLAC__byte)((max_framesize >> 16) & 0xFF);
1440 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1441 b = (FLAC__byte)((max_framesize >> 8) & 0xFF);
1442 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1443 b = (FLAC__byte)(max_framesize & 0xFF);
1444 if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1447 if(encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1451 (void)FLAC__metadata_object_seektable_template_sort(encoder_wrapper->seek_table, /*compact=*/false);
1453 FLAC__ASSERT(FLAC__metadata_object_seektable_is_legal(encoder_wrapper->seek_table));
1455 /* convert any unused seek points to placeholders */
1456 for(i = 0; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1457 if(encoder_wrapper->seek_table->data.seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
1459 else if(encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples == 0)
1460 encoder_wrapper->seek_table->data.seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
1463 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
1464 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1465 pos += metadata->length;
1466 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1467 fseek(f, pos, SEEK_SET);
1468 for(i = 0; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1469 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table->data.seek_table.points[i].sample_number)) goto end_;
1470 if(!write_big_endian_uint64(f, encoder_wrapper->seek_table->data.seek_table.points[i].stream_offset)) goto end_;
1471 if(!write_big_endian_uint16(f, (FLAC__uint16)encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples)) goto end_;
1481 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
1483 fprintf(stderr, "\n%s: ERROR: mismatch in decoded data, verify FAILED!\n", encoder_wrapper->inbasefilename);
1484 fprintf(stderr, " Please submit a bug report to\n");
1485 fprintf(stderr, " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1486 fprintf(stderr, " Make sure to include an email contact in the comment and/or use the\n");
1487 fprintf(stderr, " \"Monitor\" feature to monitor the bug status.\n");
1489 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);
1493 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1495 #if defined _MSC_VER || defined __MINGW32__
1496 /* with VC++ you have to spoon feed it the casting */
1497 const double progress = (double)(FLAC__int64)encoder_wrapper->samples_written / (double)(FLAC__int64)encoder_wrapper->total_samples_to_encode;
1498 const double ratio = (double)(FLAC__int64)encoder_wrapper->bytes_written / ((double)(FLAC__int64)encoder_wrapper->unencoded_size * progress);
1500 const double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1501 const double ratio = (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress);
1504 if(encoder_wrapper->samples_written == encoder_wrapper->total_samples_to_encode) {
1505 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1506 encoder_wrapper->inbasefilename,
1507 encoder_wrapper->verify? (encoder_wrapper->verify_failed? " Verify FAILED!" : " Verify OK,") : "",
1508 (unsigned)encoder_wrapper->bytes_written,
1513 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_wrapper->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1517 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1519 size_t bytes_read = fread(val, 1, 2, f);
1521 if(bytes_read == 0) {
1523 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1529 else if(bytes_read < 2) {
1530 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1534 if(is_big_endian_host) {
1535 FLAC__byte tmp, *b = (FLAC__byte*)val;
1536 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1542 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1544 size_t bytes_read = fread(val, 1, 4, f);
1546 if(bytes_read == 0) {
1548 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1554 else if(bytes_read < 4) {
1555 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1559 if(is_big_endian_host) {
1560 FLAC__byte tmp, *b = (FLAC__byte*)val;
1561 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1562 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1569 read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1571 unsigned char buf[4];
1572 size_t bytes_read= fread(buf, 1, 2, f);
1574 if(bytes_read==0U && eof_ok)
1576 else if(bytes_read<2U) {
1577 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1581 /* this is independent of host endianness */
1582 *val= (FLAC__uint16)(buf[0])<<8 | buf[1];
1588 read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1590 unsigned char buf[4];
1591 size_t bytes_read= fread(buf, 1, 4, f);
1593 if(bytes_read==0U && eof_ok)
1595 else if(bytes_read<4U) {
1596 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1600 /* this is independent of host endianness */
1601 *val= (FLAC__uint32)(buf[0])<<24 | (FLAC__uint32)(buf[1])<<16 |
1602 (FLAC__uint32)(buf[2])<<8 | buf[3];
1608 read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1609 /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
1610 * convert it into an integral value and store in 'val'. Return false if only
1611 * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f' and 'eof_ok' is
1612 * false, or if the value is negative, between zero and one, or too large to be
1613 * represented by 'val'; return true otherwise.
1617 unsigned char buf[10];
1618 size_t bytes_read= fread(buf, 1U, 10U, f);
1619 FLAC__int16 e= ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
1620 FLAC__int16 shift= 63-e;
1623 if(bytes_read==0U && eof_ok)
1625 else if(bytes_read<10U) {
1626 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1629 else if((buf[0]>>7)==1U || e<0 || e>63) {
1630 fprintf(stderr, "%s: ERROR: invalid floating-point value\n", fn);
1634 for(i= 0U; i<8U; ++i)
1635 p|= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
1636 *val= (FLAC__uint32)(p>>shift)+(p>>(shift-1) & 0x1);
1641 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
1643 if(!is_big_endian_host) {
1644 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1645 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1647 return fwrite(&val, 1, 2, f) == 2;
1650 FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val)
1652 if(!is_big_endian_host) {
1653 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1654 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1655 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1656 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1657 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1659 return fwrite(&val, 1, 8, f) == 8;