1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006 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.
23 #if defined _WIN32 && !defined __CYGWIN__
24 /* where MSVC puts unlink() */
29 #if defined _MSC_VER || defined __MINGW32__
30 #include <sys/types.h> /* for off_t */
31 #if _MSC_VER <= 1200 /* @@@ [2G limit] */
37 #include <limits.h> /* for LONG_MAX */
38 #include <math.h> /* for floor() */
39 #include <stdio.h> /* for FILE etc. */
40 #include <stdlib.h> /* for malloc */
41 #include <string.h> /* for strcmp(), strerror( */
43 #include "share/grabbag.h"
47 #include "OggFLAC/stream_encoder.h"
53 #define min(x,y) ((x)<(y)?(x):(y))
57 #define max(x,y) ((x)>(y)?(x):(y))
59 /* this MUST be >= 588 so that sector aligning can take place with one read */
60 #define CHUNK_OF_SAMPLES 2048
68 const char *inbasefilename;
69 const char *outfilename;
72 FLAC__uint64 until; /* a value of 0 mean end-of-stream (i.e. --until=-0) */
73 FLAC__bool replay_gain;
75 unsigned bits_per_sample;
77 FLAC__uint64 unencoded_size;
78 FLAC__uint64 total_samples_to_encode;
79 FLAC__uint64 bytes_written;
80 FLAC__uint64 samples_written;
85 FLAC__StreamEncoder *flac;
87 OggFLAC__StreamEncoder *ogg;
92 FLAC__StreamMetadata *seek_table_template;
95 /* this is data attached to the FLAC decoder when encoding from a FLAC file */
97 EncoderSession *encoder_session;
99 const FLAC__byte *lookahead;
100 unsigned lookahead_length;
101 size_t num_metadata_blocks;
102 FLAC__StreamMetadata *metadata_blocks[1024]; /*@@@ BAD MAGIC number */
103 FLAC__uint64 samples_left_to_process;
104 FLAC__bool fatal_error;
107 const int FLAC_ENCODE__DEFAULT_PADDING = 8192;
109 static FLAC__bool is_big_endian_host_;
111 static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
112 static signed char *scbuffer_ = (signed char *)ucbuffer_;
113 static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_;
114 static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_;
116 static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
117 static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
121 * unpublished debug routines from the FLAC libs
123 extern FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
124 extern FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
125 extern FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
127 extern FLAC__bool OggFLAC__stream_encoder_disable_constant_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
128 extern FLAC__bool OggFLAC__stream_encoder_disable_fixed_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
129 extern FLAC__bool OggFLAC__stream_encoder_disable_verbatim_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
135 static FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FILE *infile, const char *infilename, const char *outfilename);
136 static void EncoderSession_destroy(EncoderSession *e);
137 static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero);
138 static int EncoderSession_finish_error(EncoderSession *e);
139 static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, FLAC__uint32 channel_mask, unsigned channels, unsigned bps, unsigned sample_rate, FLACDecoderData *flac_decoder_data);
140 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
141 static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
142 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
143 static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata);
144 static FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift, size_t *channel_map);
145 static void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
146 static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
147 static FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
148 static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
149 static FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
150 static FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data);
151 static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
152 static void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
153 static void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
154 static FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset);
155 static void print_stats(const EncoderSession *encoder_session);
156 static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
157 static void print_error_with_state(const EncoderSession *e, const char *message);
158 static void print_verify_error(EncoderSession *e);
159 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
160 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
161 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
162 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
163 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
164 static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
165 static unsigned count_channel_mask_bits(FLAC__uint32 mask);
166 static unsigned limit_channel_mask(FLAC__uint32 mask, unsigned channels);
171 int flac__encode_aif(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options, FLAC__bool is_aifc)
173 EncoderSession encoder_session;
176 unsigned int channels= 0U, bps= 0U, shift= 0U, sample_rate= 0U, sample_frames= 0U;
177 size_t channel_map[FLAC__MAX_CHANNELS];
178 FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
179 int info_align_carry= -1, info_align_zero= -1;
180 FLAC__bool is_big_endian_pcm = true;
182 (void)infilesize; /* silence compiler warning about unused parameter */
183 (void)lookahead; /* silence compiler warning about unused parameter */
184 (void)lookahead_length; /* silence compiler warning about unused parameter */
187 EncoderSession_construct(
190 options.common.use_ogg,
194 options.common.verify,
202 /* initialize default channel map that preserves channel order */
205 for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++)
209 /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
213 char chunk_id[5] = { '\0', '\0', '\0', '\0', '\0' }; /* one extra byte for terminating NUL so we can also treat it like a C string */
215 /* chunk identifier; really conservative about behavior of fread() and feof() */
216 if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
218 else if(c<4U || feof(infile)) {
219 flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", encoder_session.inbasefilename);
220 return EncoderSession_finish_error(&encoder_session);
223 if(got_comm_chunk==false && !memcmp(chunk_id, "COMM", 4)) { /* common chunk */
225 const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18);
227 /* COMM chunk size */
228 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
229 return EncoderSession_finish_error(&encoder_session);
230 else if(xx<minimum_comm_size) {
231 flac__utils_printf(stderr, 1, "%s: ERROR: non-standard %s 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx);
232 return EncoderSession_finish_error(&encoder_session);
234 else if(!is_aifc && xx!=minimum_comm_size) {
235 flac__utils_printf(stderr, 1, "%s: WARNING: non-standard %s 'COMM' chunk has length = %u, expected %u\n", encoder_session.inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx, minimum_comm_size);
237 skip= (xx-minimum_comm_size)+(xx & 1U);
239 /* number of channels */
240 if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
241 return EncoderSession_finish_error(&encoder_session);
242 else if(x==0U || x>FLAC__MAX_CHANNELS) {
243 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned int)x);
244 return EncoderSession_finish_error(&encoder_session);
246 else if(x>2U && !options.common.channel_map_none) {
247 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u for AIFF\n", encoder_session.inbasefilename, (unsigned int)x);
248 return EncoderSession_finish_error(&encoder_session);
250 else if(options.common.sector_align && x!=2U) {
251 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
252 return EncoderSession_finish_error(&encoder_session);
256 /* number of sample frames */
257 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
258 return EncoderSession_finish_error(&encoder_session);
261 /* bits per sample */
262 if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
263 return EncoderSession_finish_error(&encoder_session);
264 else if(x<4U || x>24U) {
265 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, (unsigned int)x);
266 return EncoderSession_finish_error(&encoder_session);
268 else if(options.common.sector_align && x!=16U) {
269 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits-per-sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
270 return EncoderSession_finish_error(&encoder_session);
273 shift= (bps%8)? 8-(bps%8) : 0; /* SSND data is always byte-aligned, left-justified but format_input() will double-check */
277 if(!read_sane_extended(infile, &xx, false, encoder_session.inbasefilename))
278 return EncoderSession_finish_error(&encoder_session);
279 else if(!FLAC__format_sample_rate_is_valid(xx)) {
280 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned int)xx);
281 return EncoderSession_finish_error(&encoder_session);
283 else if(options.common.sector_align && xx!=44100U) {
284 flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)xx);
285 return EncoderSession_finish_error(&encoder_session);
289 /* check compression type for AIFF-C */
291 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
292 return EncoderSession_finish_error(&encoder_session);
293 if(xx == 0x736F7774) /* "sowt" */
294 is_big_endian_pcm = false;
295 else if(xx == 0x4E4F4E45) /* "NONE" */
296 ; /* nothing to do, we already default to big-endian */
298 flac__utils_printf(stderr, 1, "%s: ERROR: can't handle AIFF-C compression type \"%c%c%c%c\"\n", encoder_session.inbasefilename, (char)(xx>>24), (char)((xx>>16)&8), (char)((xx>>8)&8), (char)(xx&8));
299 return EncoderSession_finish_error(&encoder_session);
303 /* set channel mapping */
304 /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
305 /* front left, front right, center, LFE, back left, back right, surround left, surround right */
306 /* specs say the channel ordering is:
308 * ___________________________________________________
312 * quad (ambiguous with 4ch) Fl Fr Bl Br
315 * l:left r:right c:center Fl:front-left Fr:front-right Bl:back-left Br:back-right Lc:left-center Rc:right-center S:surround
316 * so we only have unambiguous mappings for 2, 3, and 5 channels
319 options.common.channel_map_none ||
320 channels == 1 || /* 1 channel: (mono) */
321 channels == 2 || /* 2 channels: left, right */
322 channels == 3 || /* 3 channels: left, right, center */
323 channels == 5 /* 5 channels: front left, front right, center, surround left, surround right */
325 /* keep default channel order */
328 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u for AIFF\n", encoder_session.inbasefilename, channels);
329 return EncoderSession_finish_error(&encoder_session);
332 /* skip any extra data in the COMM chunk */
333 if(!fskip_ahead(infile, skip)) {
334 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping extra COMM data\n", encoder_session.inbasefilename);
335 return EncoderSession_finish_error(&encoder_session);
339 * now that we know the sample rate, canonicalize the
340 * --skip string to a number of samples:
342 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, sample_rate);
343 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
344 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
345 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
347 got_comm_chunk= true;
349 else if(got_ssnd_chunk==false && !memcmp(chunk_id, "SSND", 4)) { /* sound data chunk */
350 unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
351 size_t bytes_per_frame= channels*(bps>>3);
352 FLAC__uint64 total_samples_in_input, trim = 0;
353 FLAC__bool pad= false;
355 if(got_comm_chunk==false) {
356 flac__utils_printf(stderr, 1, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", encoder_session.inbasefilename);
357 return EncoderSession_finish_error(&encoder_session);
360 /* SSND chunk size */
361 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
362 return EncoderSession_finish_error(&encoder_session);
364 pad= (data_bytes & 1U) ? true : false;
365 data_bytes-= 8U; /* discount the offset and block size fields */
368 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
369 return EncoderSession_finish_error(&encoder_session);
374 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
375 return EncoderSession_finish_error(&encoder_session);
377 flac__utils_printf(stderr, 1, "%s: ERROR: block size is %u; must be 0\n", encoder_session.inbasefilename, (unsigned int)xx);
378 return EncoderSession_finish_error(&encoder_session);
382 /* skip any SSND offset bytes */
383 FLAC__ASSERT(offset<=LONG_MAX);
384 if(!fskip_ahead(infile, offset)) {
385 flac__utils_printf(stderr, 1, "%s: ERROR: skipping offset in SSND chunk\n", encoder_session.inbasefilename);
386 return EncoderSession_finish_error(&encoder_session);
388 if(data_bytes!=(sample_frames*bytes_per_frame)) {
389 flac__utils_printf(stderr, 1, "%s: ERROR: SSND chunk size inconsistent with sample frame count\n", encoder_session.inbasefilename);
390 return EncoderSession_finish_error(&encoder_session);
393 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
394 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
395 total_samples_in_input = data_bytes / bytes_per_frame + *options.common.align_reservoir_samples;
398 * now that we know the input size, canonicalize the
399 * --until string to an absolute sample number:
401 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, sample_rate, encoder_session.skip, total_samples_in_input))
402 return EncoderSession_finish_error(&encoder_session);
403 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
404 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
406 if(encoder_session.skip>0U) {
407 if(!fskip_ahead(infile, encoder_session.skip*bytes_per_frame)) {
408 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
409 return EncoderSession_finish_error(&encoder_session);
413 data_bytes-= (unsigned int)encoder_session.skip*bytes_per_frame; /*@@@ WATCHOUT: 4GB limit */
414 encoder_session.total_samples_to_encode= total_samples_in_input - encoder_session.skip;
415 if(encoder_session.until > 0) {
416 trim = total_samples_in_input - encoder_session.until;
417 FLAC__ASSERT(total_samples_in_input > 0);
418 FLAC__ASSERT(!options.common.sector_align);
419 data_bytes-= (unsigned int)trim*bytes_per_frame;
420 encoder_session.total_samples_to_encode-= trim;
422 if(options.common.sector_align) {
423 align_remainder= (unsigned int)(encoder_session.total_samples_to_encode % 588U);
424 if(options.common.is_last_file)
425 encoder_session.total_samples_to_encode+= (588U-align_remainder); /* will pad with zeroes */
427 encoder_session.total_samples_to_encode-= align_remainder; /* will stop short and carry over to next file */
430 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
431 encoder_session.unencoded_size= encoder_session.total_samples_to_encode*bytes_per_frame+54;
433 if(!EncoderSession_init_encoder(&encoder_session, options.common, /*channel_mask=*/0, channels, bps-shift, sample_rate, /*flac_decoder_data=*/0))
434 return EncoderSession_finish_error(&encoder_session);
436 /* first do any samples in the reservoir */
437 if(options.common.sector_align && *options.common.align_reservoir_samples>0U) {
439 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
440 print_error_with_state(&encoder_session, "ERROR during encoding");
441 return EncoderSession_finish_error(&encoder_session);
445 /* decrement the data_bytes counter if we need to align the file */
446 if(options.common.sector_align) {
447 if(options.common.is_last_file)
448 *options.common.align_reservoir_samples= 0U;
450 *options.common.align_reservoir_samples= align_remainder;
451 data_bytes-= (*options.common.align_reservoir_samples)*bytes_per_frame;
455 /* now do from the file */
456 while(data_bytes>0) {
457 size_t bytes_read= fread(ucbuffer_, 1U, min(data_bytes, CHUNK_OF_SAMPLES*bytes_per_frame), infile);
461 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
462 return EncoderSession_finish_error(&encoder_session);
464 else if(feof(infile)) {
465 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned int)encoder_session.total_samples_to_encode, (unsigned int)encoder_session.samples_written);
470 if(bytes_read % bytes_per_frame != 0U) {
471 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
472 return EncoderSession_finish_error(&encoder_session);
475 unsigned int frames= bytes_read/bytes_per_frame;
476 if(!format_input(input_, frames, is_big_endian_pcm, /*is_unsigned_samples=*/false, channels, bps, shift, channel_map))
477 return EncoderSession_finish_error(&encoder_session);
479 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, frames)) {
480 print_error_with_state(&encoder_session, "ERROR during encoding");
481 return EncoderSession_finish_error(&encoder_session);
484 data_bytes-= bytes_read;
490 FLAC__ASSERT(!options.common.sector_align);
491 if(!fskip_ahead(infile, trim*bytes_per_frame)) {
492 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
493 return EncoderSession_finish_error(&encoder_session);
497 /* now read unaligned samples into reservoir or pad with zeroes if necessary */
498 if(options.common.sector_align) {
499 if(options.common.is_last_file) {
500 unsigned int pad_frames= 588U-align_remainder;
502 if(pad_frames<588U) {
505 info_align_zero= pad_frames;
506 for(i= 0U; i<channels; ++i)
507 memset(input_[i], 0, sizeof(input_[0][0])*pad_frames);
509 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, pad_frames)) {
510 print_error_with_state(&encoder_session, "ERROR during encoding");
511 return EncoderSession_finish_error(&encoder_session);
516 if(*options.common.align_reservoir_samples > 0) {
517 size_t bytes_read= fread(ucbuffer_, 1U, (*options.common.align_reservoir_samples)*bytes_per_frame, infile);
519 FLAC__ASSERT(CHUNK_OF_SAMPLES>=588U);
520 if(bytes_read==0U && ferror(infile)) {
521 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
522 return EncoderSession_finish_error(&encoder_session);
524 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame) {
525 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned int)bytes_read, (unsigned int)encoder_session.total_samples_to_encode, (unsigned int)encoder_session.samples_written);
528 info_align_carry= *options.common.align_reservoir_samples;
529 if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, is_big_endian_pcm, /*is_unsigned_samples=*/false, channels, bps, shift, channel_map))
530 return EncoderSession_finish_error(&encoder_session);
539 if(fread(&tmp, 1U, 1U, infile)<1U) {
540 flac__utils_printf(stderr, 1, "%s: ERROR during read of SSND pad byte\n", encoder_session.inbasefilename);
541 return EncoderSession_finish_error(&encoder_session);
545 got_ssnd_chunk= true;
547 else { /* other chunk */
548 if(!memcmp(chunk_id, "COMM", 4)) {
549 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_session.inbasefilename);
551 else if(!memcmp(chunk_id, "SSND", 4)) {
552 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_session.inbasefilename);
555 flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_session.inbasefilename, chunk_id);
559 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
560 return EncoderSession_finish_error(&encoder_session);
562 unsigned long skip= xx+(xx & 1U);
564 FLAC__ASSERT(skip<=LONG_MAX);
565 if(!fskip_ahead(infile, skip)) {
566 fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_session.inbasefilename);
567 return EncoderSession_finish_error(&encoder_session);
573 if(got_ssnd_chunk==false && sample_frames!=0U) {
574 flac__utils_printf(stderr, 1, "%s: ERROR: missing SSND chunk\n", encoder_session.inbasefilename);
575 return EncoderSession_finish_error(&encoder_session);
578 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
581 int flac__encode_wav(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
583 EncoderSession encoder_session;
584 FLAC__bool is_unsigned_samples = false;
585 unsigned channels = 0, bps = 0, sample_rate = 0, shift = 0;
586 size_t bytes_per_wide_sample, bytes_read;
587 size_t channel_map[FLAC__MAX_CHANNELS];
588 FLAC__uint16 x, format; /* format is the wFormatTag word from the 'fmt ' chunk */
589 FLAC__uint32 xx, channel_mask = 0;
590 FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
591 unsigned align_remainder = 0;
592 int info_align_carry = -1, info_align_zero = -1;
596 (void)lookahead_length;
599 EncoderSession_construct(
602 options.common.use_ogg,
606 options.common.verify,
614 /* initialize default channel map that preserves channel order */
617 for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++)
622 * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
624 while(!feof(infile)) {
625 if(!read_little_endian_uint32(infile, &xx, true, encoder_session.inbasefilename))
626 return EncoderSession_finish_error(&encoder_session);
629 if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
630 unsigned block_align, data_bytes;
633 * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
634 * http://windowssdk.msdn.microsoft.com/en-us/library/ms713497.aspx
635 * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/audio_r/hh/Audio_r/aud-prop_d40f094e-44f9-4baa-8a15-03e4fb369501.xml.asp
638 * 4 byte: subchunk size
639 * 2 byte: format type: 1 for WAVE_FORMAT_PCM, 65534 for WAVE_FORMAT_EXTENSIBLE
641 * 4 byte: sample rate (Hz)
642 * 4 byte: avg bytes per sec
643 * 2 byte: block align
644 * 2 byte: bits per sample (not necessarily all significant)
646 * 2 byte: extension size in bytes (usually 0 for WAVEFORMATEX and 22 for WAVEFORMATEXTENSIBLE with PCM)
647 * WAVEFORMATEXTENSIBLE adds
648 * 2 byte: valid bits per sample
649 * 4 byte: channel mask
650 * 16 byte: subformat GUID, first 2 bytes have format type, 1 being PCM
652 * Current spec says WAVEFORMATEX with PCM must have bps == 8 or 16, or any multiple of 8 for WAVEFORMATEXTENSIBLE.
653 * Lots of old broken WAVEs/apps have don't follow it, e.g. 20 bps but a block align of 3/6 for mono/stereo.
655 * Block align for WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE is also supposed to be channels*bps/8
657 * If the channel mask has more set bits than # of channels, the extra MSBs are ignored.
658 * If the channel mask has less set bits than # of channels, the extra channels are unassigned to any speaker.
660 * Data is supposed to be unsigned for bps <= 8 else signed.
663 /* fmt sub-chunk size */
664 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
665 return EncoderSession_finish_error(&encoder_session);
667 if(data_bytes < 16) {
668 flac__utils_printf(stderr, 1, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, data_bytes);
669 return EncoderSession_finish_error(&encoder_session);
672 if(!read_little_endian_uint16(infile, &format, false, encoder_session.inbasefilename))
673 return EncoderSession_finish_error(&encoder_session);
674 if(format != 1 /*WAVE_FORMAT_PCM*/ && format != 65534 /*WAVE_FORMAT_EXTENSIBLE*/) {
675 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", encoder_session.inbasefilename, (unsigned)format);
676 return EncoderSession_finish_error(&encoder_session);
678 /* number of channels */
679 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
680 return EncoderSession_finish_error(&encoder_session);
681 channels = (unsigned)x;
682 if(channels == 0 || channels > FLAC__MAX_CHANNELS) {
683 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u\n", encoder_session.inbasefilename, channels);
684 return EncoderSession_finish_error(&encoder_session);
686 else if(options.common.sector_align && channels != 2) {
687 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, channels);
688 return EncoderSession_finish_error(&encoder_session);
691 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
692 return EncoderSession_finish_error(&encoder_session);
694 if(!FLAC__format_sample_rate_is_valid(sample_rate)) {
695 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, sample_rate);
696 return EncoderSession_finish_error(&encoder_session);
698 else if(options.common.sector_align && sample_rate != 44100) {
699 flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, sample_rate);
700 return EncoderSession_finish_error(&encoder_session);
702 /* avg bytes per second (ignored) */
703 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
704 return EncoderSession_finish_error(&encoder_session);
706 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
707 return EncoderSession_finish_error(&encoder_session);
708 block_align = (unsigned)x;
709 /* bits per sample */
710 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
711 return EncoderSession_finish_error(&encoder_session);
713 is_unsigned_samples = (bps <= 8);
715 if(bps != 8 && bps != 16) {
716 if(bps == 24 || bps == 32) {
717 /* let these slide with a warning since they're unambiguous */
718 flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file has format type %u but bits-per-sample=%u\n", encoder_session.inbasefilename, (unsigned)format, bps);
721 /* @@@ we could add an option to specify left- or right-justified blocks so we knew how to set 'shift' */
722 flac__utils_printf(stderr, 1, "%s: ERROR: legacy WAVE file has format type %u but bits-per-sample=%u\n", encoder_session.inbasefilename, (unsigned)format, bps);
723 return EncoderSession_finish_error(&encoder_session);
726 #if 0 /* @@@ reinstate once we can get an answer about whether the samples are left- or right-justified */
727 if((bps+7)/8 * channels == block_align) {
729 /* assume legacy file is byte aligned with some LSBs zero; this is double-checked in format_input() */
730 flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", encoder_session.inbasefilename, (unsigned)format, block_align, bps, channels);
731 shift = 8 - (bps % 8);
738 flac__utils_printf(stderr, 1, "%s: ERROR: illegal WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", encoder_session.inbasefilename, (unsigned)format, block_align, bps, channels);
739 return EncoderSession_finish_error(&encoder_session);
744 if(channels > 2 && !options.common.channel_map_none) {
745 flac__utils_printf(stderr, 1, "%s: ERROR: WAVE has >2 channels but is not WAVE_FORMAT_EXTENSIBLE; cannot assign channels\n", encoder_session.inbasefilename);
746 return EncoderSession_finish_error(&encoder_session);
748 FLAC__ASSERT(data_bytes >= 16);
752 if(data_bytes < 40) {
753 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with size %u\n", encoder_session.inbasefilename, data_bytes);
754 return EncoderSession_finish_error(&encoder_session);
757 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
758 return EncoderSession_finish_error(&encoder_session);
760 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with cbSize %u\n", encoder_session.inbasefilename, (unsigned)x);
761 return EncoderSession_finish_error(&encoder_session);
764 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
765 return EncoderSession_finish_error(&encoder_session);
766 if((unsigned)x > bps) {
767 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", encoder_session.inbasefilename, (unsigned)x, bps);
768 return EncoderSession_finish_error(&encoder_session);
770 shift = bps - (unsigned)x;
772 if(!read_little_endian_uint32(infile, &channel_mask, false, encoder_session.inbasefilename))
773 return EncoderSession_finish_error(&encoder_session);
774 /* for mono/stereo and unassigned channels, we fake the mask */
775 if(channel_mask == 0) {
777 channel_mask = 0x0001;
778 else if(channels == 2)
779 channel_mask = 0x0003;
781 /* set channel mapping */
782 /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
783 /* front left, front right, center, LFE, back left, back right, surround left, surround right */
784 /* the default mapping is sufficient for 1-6 channels and 7-8 are currently unspecified anyway */
786 /* @@@ example for dolby/vorbis order, for reference later in case it becomes important */
788 options.common.channel_map_none ||
789 channel_mask == 0x0001 || /* 1 channel: (mono) */
790 channel_mask == 0x0003 || /* 2 channels: front left, front right */
791 channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
792 channel_mask == 0x0603 /* 4 channels: front left, front right, side left, side right */
794 /* keep default channel order */
797 channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
798 channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
799 channel_mask == 0x0607 /* 5 channels: front left, front right, front center, side left, side right */
801 /* to dolby order: front left, center, front right [, surround left, surround right ] */
806 channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
807 channel_mask == 0x060f /* 6 channels: front left, front right, front center, LFE, side left, side right */
809 /* to dolby order: front left, center, front right, surround left, surround right, LFE */
818 options.common.channel_map_none ||
819 channel_mask == 0x0001 || /* 1 channel: (mono) */
820 channel_mask == 0x0003 || /* 2 channels: front left, front right */
821 channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
822 channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
823 channel_mask == 0x0603 || /* 4 channels: front left, front right, side left, side right */
824 channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
825 channel_mask == 0x0607 || /* 5 channels: front left, front right, front center, side left, side right */
826 channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
827 channel_mask == 0x060f /* 6 channels: front left, front right, front center, LFE, side left, side right */
829 /* keep default channel order */
833 flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk with unsupported channel mask=0x%04X\n", encoder_session.inbasefilename, (unsigned)channel_mask);
834 return EncoderSession_finish_error(&encoder_session);
836 if(!options.common.channel_map_none) {
837 if(count_channel_mask_bits(channel_mask) < channels) {
838 flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has unassigned channels (#channels=%u)\n", encoder_session.inbasefilename, (unsigned)channel_mask, channels);
839 return EncoderSession_finish_error(&encoder_session);
842 /* supporting this is too difficult with channel mapping; e.g. what if mask is 0x003f but #channels=4?
843 * there would be holes in the order that would have to be filled in, or the mask would have to be
844 * limited and the logic above rerun to see if it still fits into the FLAC mapping.
846 else if(count_channel_mask_bits(channel_mask) > channels)
847 channel_mask = limit_channel_mask(channel_mask, channels);
849 else if(count_channel_mask_bits(channel_mask) > channels) {
850 flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has extra bits for non-existant channels (#channels=%u)\n", encoder_session.inbasefilename, (unsigned)channel_mask, channels);
851 return EncoderSession_finish_error(&encoder_session);
855 /* first part of GUID */
856 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
857 return EncoderSession_finish_error(&encoder_session);
859 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE chunk with non-PCM format %u\n", encoder_session.inbasefilename, (unsigned)x);
860 return EncoderSession_finish_error(&encoder_session);
865 if(bps-shift < 4 || bps-shift > 24) {
866 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, bps-shift);
867 return EncoderSession_finish_error(&encoder_session);
869 else if(options.common.sector_align && bps-shift != 16) {
870 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits-per-sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, bps-shift);
871 return EncoderSession_finish_error(&encoder_session);
874 /* skip any extra data in the fmt sub-chunk */
875 if(!fskip_ahead(infile, data_bytes)) {
876 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping extra 'fmt' data\n", encoder_session.inbasefilename);
877 return EncoderSession_finish_error(&encoder_session);
881 * now that we know the sample rate, canonicalize the
882 * --skip string to a number of samples:
884 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, sample_rate);
885 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
886 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
887 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
889 got_fmt_chunk = true;
891 else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
892 FLAC__uint64 total_samples_in_input, trim = 0;
893 FLAC__bool pad = false;
897 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
898 return EncoderSession_finish_error(&encoder_session);
900 pad = (data_bytes & 1U) ? true : false;
902 bytes_per_wide_sample = channels * (bps >> 3);
904 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
905 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
906 total_samples_in_input = data_bytes / bytes_per_wide_sample + *options.common.align_reservoir_samples;
909 * now that we know the input size, canonicalize the
910 * --until string to an absolute sample number:
912 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, sample_rate, encoder_session.skip, total_samples_in_input))
913 return EncoderSession_finish_error(&encoder_session);
914 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
915 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
917 if(encoder_session.skip > 0) {
918 if(!fskip_ahead(infile, encoder_session.skip * bytes_per_wide_sample)) {
919 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
920 return EncoderSession_finish_error(&encoder_session);
924 data_bytes -= (unsigned)encoder_session.skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
925 encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
926 if(encoder_session.until > 0) {
927 trim = total_samples_in_input - encoder_session.until;
928 FLAC__ASSERT(total_samples_in_input > 0);
929 FLAC__ASSERT(!options.common.sector_align);
930 data_bytes -= (unsigned int)trim * bytes_per_wide_sample;
931 encoder_session.total_samples_to_encode -= trim;
933 if(options.common.sector_align) {
934 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
935 if(options.common.is_last_file)
936 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
938 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
941 /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
942 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample + 44;
944 if(!EncoderSession_init_encoder(&encoder_session, options.common, channel_mask, channels, bps-shift, sample_rate, /*flac_decoder_data=*/0))
945 return EncoderSession_finish_error(&encoder_session);
948 * first do any samples in the reservoir
950 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
951 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
952 print_error_with_state(&encoder_session, "ERROR during encoding");
953 return EncoderSession_finish_error(&encoder_session);
958 * decrement the data_bytes counter if we need to align the file
960 if(options.common.sector_align) {
961 if(options.common.is_last_file) {
962 *options.common.align_reservoir_samples = 0;
965 *options.common.align_reservoir_samples = align_remainder;
966 data_bytes -= (*options.common.align_reservoir_samples) * bytes_per_wide_sample;
971 * now do from the file
973 while(data_bytes > 0) {
974 bytes_read = fread(ucbuffer_, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
975 if(bytes_read == 0) {
977 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
978 return EncoderSession_finish_error(&encoder_session);
980 else if(feof(infile)) {
981 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
986 if(bytes_read % bytes_per_wide_sample != 0) {
987 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
988 return EncoderSession_finish_error(&encoder_session);
991 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
992 if(!format_input(input_, wide_samples, /*is_big_endian=*/false, is_unsigned_samples, channels, bps, shift, channel_map))
993 return EncoderSession_finish_error(&encoder_session);
995 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
996 print_error_with_state(&encoder_session, "ERROR during encoding");
997 return EncoderSession_finish_error(&encoder_session);
999 data_bytes -= bytes_read;
1005 FLAC__ASSERT(!options.common.sector_align);
1006 if(!fskip_ahead(infile, trim * bytes_per_wide_sample)) {
1007 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1008 return EncoderSession_finish_error(&encoder_session);
1013 * now read unaligned samples into reservoir or pad with zeroes if necessary
1015 if(options.common.sector_align) {
1016 if(options.common.is_last_file) {
1017 unsigned wide_samples = 588 - align_remainder;
1018 if(wide_samples < 588) {
1021 info_align_zero = wide_samples;
1022 for(channel = 0; channel < channels; channel++)
1023 memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
1025 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1026 print_error_with_state(&encoder_session, "ERROR during encoding");
1027 return EncoderSession_finish_error(&encoder_session);
1032 if(*options.common.align_reservoir_samples > 0) {
1033 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1034 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
1035 if(bytes_read == 0 && ferror(infile)) {
1036 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1037 return EncoderSession_finish_error(&encoder_session);
1039 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
1040 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
1043 info_align_carry = *options.common.align_reservoir_samples;
1044 if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, /*is_big_endian=*/false, is_unsigned_samples, channels, bps, shift, channel_map))
1045 return EncoderSession_finish_error(&encoder_session);
1054 if(fread(&tmp, 1U, 1U, infile) < 1U) {
1055 flac__utils_printf(stderr, 1, "%s: ERROR during read of data pad byte\n", encoder_session.inbasefilename);
1056 return EncoderSession_finish_error(&encoder_session);
1060 got_data_chunk = true;
1063 if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
1064 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_session.inbasefilename);
1066 else if(xx == 0x61746164) { /* "data" */
1067 if(got_data_chunk) {
1068 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_session.inbasefilename);
1070 else if(!got_fmt_chunk) {
1071 flac__utils_printf(stderr, 1, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_session.inbasefilename);
1072 return EncoderSession_finish_error(&encoder_session);
1079 flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown sub-chunk '%c%c%c%c'\n", encoder_session.inbasefilename, (char)(xx&255), (char)((xx>>8)&255), (char)((xx>>16)&255), (char)(xx>>24));
1081 /* sub-chunk size */
1082 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
1083 return EncoderSession_finish_error(&encoder_session);
1085 unsigned long skip = xx+(xx & 1U);
1087 FLAC__ASSERT(skip<=LONG_MAX);
1088 if(!fskip_ahead(infile, skip)) {
1089 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_session.inbasefilename);
1090 return EncoderSession_finish_error(&encoder_session);
1096 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
1099 int flac__encode_raw(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, raw_encode_options_t options)
1101 EncoderSession encoder_session;
1103 const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
1104 unsigned align_remainder = 0;
1105 int info_align_carry = -1, info_align_zero = -1;
1106 FLAC__uint64 total_samples_in_input = 0;
1108 FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
1109 FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
1110 FLAC__ASSERT(!options.common.sector_align || options.sample_rate == 44100);
1111 FLAC__ASSERT(!options.common.sector_align || infilesize >= 0);
1112 FLAC__ASSERT(!options.common.replay_gain || options.channels <= 2);
1113 FLAC__ASSERT(!options.common.replay_gain || grabbag__replaygain_is_valid_sample_frequency(options.sample_rate));
1116 EncoderSession_construct(
1118 #ifdef FLAC__HAS_OGG
1119 options.common.use_ogg,
1123 options.common.verify,
1132 * now that we know the sample rate, canonicalize the
1133 * --skip string to a number of samples:
1135 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, options.sample_rate);
1136 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
1137 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
1138 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
1141 total_samples_in_input = 0;
1143 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
1144 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
1145 total_samples_in_input = (FLAC__uint64)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
1149 * now that we know the input size, canonicalize the
1150 * --until strings to a number of samples:
1152 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, options.sample_rate, encoder_session.skip, total_samples_in_input))
1153 return EncoderSession_finish_error(&encoder_session);
1154 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
1155 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
1157 infilesize -= (off_t)encoder_session.skip * bytes_per_wide_sample;
1158 encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
1159 if(encoder_session.until > 0) {
1160 const FLAC__uint64 trim = total_samples_in_input - encoder_session.until;
1161 FLAC__ASSERT(total_samples_in_input > 0);
1162 FLAC__ASSERT(!options.common.sector_align);
1163 infilesize -= (off_t)trim * bytes_per_wide_sample;
1164 encoder_session.total_samples_to_encode -= trim;
1166 if(infilesize >= 0 && options.common.sector_align) {
1167 FLAC__ASSERT(encoder_session.skip == 0);
1168 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
1169 if(options.common.is_last_file)
1170 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
1172 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
1174 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample;
1176 if(encoder_session.total_samples_to_encode <= 0)
1177 flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n");
1179 if(encoder_session.skip > 0) {
1180 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)encoder_session.skip;
1181 if(skip_bytes > lookahead_length) {
1182 skip_bytes -= lookahead_length;
1183 lookahead_length = 0;
1184 if(!fskip_ahead(infile, skip_bytes)) {
1185 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1186 return EncoderSession_finish_error(&encoder_session);
1190 lookahead += skip_bytes;
1191 lookahead_length -= skip_bytes;
1195 if(!EncoderSession_init_encoder(&encoder_session, options.common, /*channel_mask=*/0, options.channels, options.bps, options.sample_rate, /*flac_decoder_data=*/0))
1196 return EncoderSession_finish_error(&encoder_session);
1199 * first do any samples in the reservoir
1201 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
1202 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
1203 print_error_with_state(&encoder_session, "ERROR during encoding");
1204 return EncoderSession_finish_error(&encoder_session);
1209 * decrement infilesize if we need to align the file
1211 if(options.common.sector_align) {
1212 FLAC__ASSERT(infilesize >= 0);
1213 if(options.common.is_last_file) {
1214 *options.common.align_reservoir_samples = 0;
1217 *options.common.align_reservoir_samples = align_remainder;
1218 infilesize -= (off_t)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
1219 FLAC__ASSERT(infilesize >= 0);
1224 * now do from the file
1226 if(infilesize < 0) {
1227 while(!feof(infile)) {
1228 if(lookahead_length > 0) {
1229 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1230 memcpy(ucbuffer_, lookahead, lookahead_length);
1231 bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
1232 if(ferror(infile)) {
1233 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1234 return EncoderSession_finish_error(&encoder_session);
1236 lookahead_length = 0;
1239 bytes_read = fread(ucbuffer_, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
1241 if(bytes_read == 0) {
1242 if(ferror(infile)) {
1243 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1244 return EncoderSession_finish_error(&encoder_session);
1247 else if(bytes_read % bytes_per_wide_sample != 0) {
1248 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1249 return EncoderSession_finish_error(&encoder_session);
1252 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1253 if(!format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0, /*channel_map=*/0))
1254 return EncoderSession_finish_error(&encoder_session);
1256 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1257 print_error_with_state(&encoder_session, "ERROR during encoding");
1258 return EncoderSession_finish_error(&encoder_session);
1264 const FLAC__uint64 max_input_bytes = infilesize;
1265 FLAC__uint64 total_input_bytes_read = 0;
1266 while(total_input_bytes_read < max_input_bytes) {
1268 size_t wanted = (CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1269 wanted = (size_t) min((FLAC__uint64)wanted, max_input_bytes - total_input_bytes_read);
1271 if(lookahead_length > 0) {
1272 FLAC__ASSERT(lookahead_length <= wanted);
1273 memcpy(ucbuffer_, lookahead, lookahead_length);
1274 wanted -= lookahead_length;
1275 bytes_read = lookahead_length;
1277 bytes_read += fread(ucbuffer_+lookahead_length, sizeof(unsigned char), wanted, infile);
1278 if(ferror(infile)) {
1279 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1280 return EncoderSession_finish_error(&encoder_session);
1283 lookahead_length = 0;
1286 bytes_read = fread(ucbuffer_, sizeof(unsigned char), wanted, infile);
1289 if(bytes_read == 0) {
1290 if(ferror(infile)) {
1291 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1292 return EncoderSession_finish_error(&encoder_session);
1294 else if(feof(infile)) {
1295 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
1296 total_input_bytes_read = max_input_bytes;
1300 if(bytes_read % bytes_per_wide_sample != 0) {
1301 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1302 return EncoderSession_finish_error(&encoder_session);
1305 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1306 if(!format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0, /*channel_map=*/0))
1307 return EncoderSession_finish_error(&encoder_session);
1309 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1310 print_error_with_state(&encoder_session, "ERROR during encoding");
1311 return EncoderSession_finish_error(&encoder_session);
1313 total_input_bytes_read += bytes_read;
1320 * now read unaligned samples into reservoir or pad with zeroes if necessary
1322 if(options.common.sector_align) {
1323 if(options.common.is_last_file) {
1324 unsigned wide_samples = 588 - align_remainder;
1325 if(wide_samples < 588) {
1328 info_align_zero = wide_samples;
1329 for(channel = 0; channel < options.channels; channel++)
1330 memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
1332 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1333 print_error_with_state(&encoder_session, "ERROR during encoding");
1334 return EncoderSession_finish_error(&encoder_session);
1339 if(*options.common.align_reservoir_samples > 0) {
1340 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1341 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
1342 if(bytes_read == 0 && ferror(infile)) {
1343 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1344 return EncoderSession_finish_error(&encoder_session);
1346 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
1347 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
1350 info_align_carry = *options.common.align_reservoir_samples;
1351 if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0, /*channel_map=*/0))
1352 return EncoderSession_finish_error(&encoder_session);
1358 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
1361 int flac__encode_flac(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, flac_encode_options_t options)
1363 EncoderSession encoder_session;
1364 FLAC__StreamDecoder *decoder = 0;
1365 FLACDecoderData decoder_data;
1370 EncoderSession_construct(
1372 #ifdef FLAC__HAS_OGG
1373 options.common.use_ogg,
1377 options.common.verify,
1385 decoder_data.encoder_session = &encoder_session;
1386 decoder_data.filesize = (infilesize == (off_t)(-1)? 0 : infilesize);
1387 decoder_data.lookahead = lookahead;
1388 decoder_data.lookahead_length = lookahead_length;
1389 decoder_data.num_metadata_blocks = 0;
1390 decoder_data.samples_left_to_process = 0;
1391 decoder_data.fatal_error = false;
1394 * set up FLAC decoder for the input
1396 if (0 == (decoder = FLAC__stream_decoder_new())) {
1397 flac__utils_printf(stderr, 1, "%s: ERROR: creating decoder for FLAC input\n", encoder_session.inbasefilename);
1398 return EncoderSession_finish_error(&encoder_session);
1401 FLAC__stream_decoder_set_md5_checking(decoder, false) &&
1402 FLAC__stream_decoder_set_metadata_respond_all(decoder)
1404 flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", encoder_session.inbasefilename);
1405 goto fubar1; /*@@@ yuck */
1408 if (FLAC__stream_decoder_init_stream(decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/&decoder_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
1409 flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
1410 goto fubar1; /*@@@ yuck */
1413 if (!FLAC__stream_decoder_process_until_end_of_metadata(decoder) || decoder_data.fatal_error) {
1414 if (decoder_data.fatal_error)
1415 flac__utils_printf(stderr, 1, "%s: ERROR: out of memory or too many metadata blocks while reading metadata in FLAC input\n", encoder_session.inbasefilename);
1417 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
1418 goto fubar1; /*@@@ yuck */
1421 if (decoder_data.num_metadata_blocks == 0) {
1422 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, got no metadata blocks\n", encoder_session.inbasefilename);
1423 goto fubar2; /*@@@ yuck */
1425 else if (decoder_data.metadata_blocks[0]->type != FLAC__METADATA_TYPE_STREAMINFO) {
1426 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, first metadata block is not STREAMINFO\n", encoder_session.inbasefilename);
1427 goto fubar2; /*@@@ yuck */
1429 else if (decoder_data.metadata_blocks[0]->data.stream_info.total_samples == 0) {
1430 flac__utils_printf(stderr, 1, "%s: ERROR: FLAC input has STREAMINFO with unknown total samples which is not supported\n", encoder_session.inbasefilename);
1431 goto fubar2; /*@@@ yuck */
1435 * now that we have the STREAMINFO and know the sample rate,
1436 * canonicalize the --skip string to a number of samples:
1438 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate);
1439 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
1440 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
1441 FLAC__ASSERT(!options.common.sector_align); /* --sector-align with FLAC input is not supported */
1444 FLAC__uint64 total_samples_in_input, trim = 0;
1446 total_samples_in_input = decoder_data.metadata_blocks[0]->data.stream_info.total_samples;
1449 * now that we know the input size, canonicalize the
1450 * --until string to an absolute sample number:
1452 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate, encoder_session.skip, total_samples_in_input))
1453 goto fubar2; /*@@@ yuck */
1454 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
1456 encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
1457 if(encoder_session.until > 0) {
1458 trim = total_samples_in_input - encoder_session.until;
1459 FLAC__ASSERT(total_samples_in_input > 0);
1460 encoder_session.total_samples_to_encode -= trim;
1463 encoder_session.unencoded_size = decoder_data.filesize;
1465 /* (channel mask will get copied over from the source VORBIS_COMMENT if it exists) */
1466 if(!EncoderSession_init_encoder(&encoder_session, options.common, /*channel_mask=*/0, decoder_data.metadata_blocks[0]->data.stream_info.channels, decoder_data.metadata_blocks[0]->data.stream_info.bits_per_sample, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate, &decoder_data))
1467 return EncoderSession_finish_error(&encoder_session);
1470 * have to wait until the FLAC encoder is set up for writing
1471 * before any seeking in the input FLAC file, because the seek
1472 * itself will usually call the decoder's write callback, and
1473 * our decoder's write callback passes samples to our FLAC
1476 decoder_data.samples_left_to_process = encoder_session.total_samples_to_encode;
1477 if(encoder_session.skip > 0) {
1478 if(!FLAC__stream_decoder_seek_absolute(decoder, encoder_session.skip)) {
1479 flac__utils_printf(stderr, 1, "%s: ERROR while skipping samples, FLAC decoder state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
1480 goto fubar2; /*@@@ yuck */
1485 * now do samples from the file
1487 while(!decoder_data.fatal_error && decoder_data.samples_left_to_process > 0) {
1488 if(!FLAC__stream_decoder_process_single(decoder)) {
1489 flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
1490 goto fubar2; /*@@@ yuck */
1495 FLAC__stream_decoder_delete(decoder);
1496 retval = EncoderSession_finish_ok(&encoder_session, -1, -1);
1497 /* have to wail until encoder is completely finished before deleting because of the final step of writing the seekpoint offsets */
1498 for(i = 0; i < decoder_data.num_metadata_blocks; i++)
1499 free(decoder_data.metadata_blocks[i]);
1503 for(i = 0; i < decoder_data.num_metadata_blocks; i++)
1504 free(decoder_data.metadata_blocks[i]);
1506 FLAC__stream_decoder_delete(decoder);
1507 return EncoderSession_finish_error(&encoder_session);
1510 FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FILE *infile, const char *infilename, const char *outfilename)
1513 FLAC__uint32 test = 1;
1516 * initialize globals
1519 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
1521 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1522 input_[i] = &(in_[i][0]);
1526 * initialize instance
1529 #ifdef FLAC__HAS_OGG
1530 e->use_ogg = use_ogg;
1536 e->is_stdout = (0 == strcmp(outfilename, "-"));
1538 e->inbasefilename = grabbag__file_get_basename(infilename);
1539 e->outfilename = outfilename;
1541 e->skip = 0; /* filled in later after the sample_rate is known */
1542 e->unencoded_size = 0;
1543 e->total_samples_to_encode = 0;
1544 e->bytes_written = 0;
1545 e->samples_written = 0;
1549 e->encoder.flac = 0;
1550 #ifdef FLAC__HAS_OGG
1555 e->seek_table_template = 0;
1557 if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1558 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1562 #ifdef FLAC__HAS_OGG
1564 e->encoder.ogg = OggFLAC__stream_encoder_new();
1565 if(0 == e->encoder.ogg) {
1566 flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1567 EncoderSession_destroy(e);
1573 e->encoder.flac = FLAC__stream_encoder_new();
1574 if(0 == e->encoder.flac) {
1575 flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1576 EncoderSession_destroy(e);
1583 void EncoderSession_destroy(EncoderSession *e)
1588 #ifdef FLAC__HAS_OGG
1590 if(0 != e->encoder.ogg) {
1591 OggFLAC__stream_encoder_delete(e->encoder.ogg);
1597 if(0 != e->encoder.flac) {
1598 FLAC__stream_encoder_delete(e->encoder.flac);
1599 e->encoder.flac = 0;
1602 if(0 != e->seek_table_template) {
1603 FLAC__metadata_object_delete(e->seek_table_template);
1604 e->seek_table_template = 0;
1608 int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero)
1610 FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1613 #ifdef FLAC__HAS_OGG
1615 if(e->encoder.ogg) {
1616 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg);
1617 OggFLAC__stream_encoder_finish(e->encoder.ogg);
1622 if(e->encoder.flac) {
1623 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac);
1624 FLAC__stream_encoder_finish(e->encoder.flac);
1627 if(e->total_samples_to_encode > 0) {
1629 flac__utils_printf(stderr, 2, "\n");
1632 if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) {
1633 print_verify_error(e);
1637 if(info_align_carry >= 0) {
1638 flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d samples to be carried over\n", e->inbasefilename, info_align_carry);
1640 if(info_align_zero >= 0) {
1641 flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d zero samples to be appended\n", e->inbasefilename, info_align_zero);
1645 EncoderSession_destroy(e);
1650 int EncoderSession_finish_error(EncoderSession *e)
1652 FLAC__StreamEncoderState fse_state;
1654 #ifdef FLAC__HAS_OGG
1655 FLAC__ASSERT(e->encoder.ogg || e->encoder.flac);
1657 FLAC__ASSERT(e->encoder.flac);
1660 if(e->total_samples_to_encode > 0)
1661 flac__utils_printf(stderr, 2, "\n");
1663 #ifdef FLAC__HAS_OGG
1665 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg);
1670 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac);
1673 if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1674 print_verify_error(e);
1676 /*@@@@@@@@@ BUG: if error was caused because the output file already exists but the file encoder could not write on top of it (i.e. it's not writable), this will delete the pre-existing file, which is not what we want */
1677 unlink(e->outfilename);
1679 EncoderSession_destroy(e);
1684 FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, FLAC__uint32 channel_mask, unsigned channels, unsigned bps, unsigned sample_rate, FLACDecoderData *flac_decoder_data)
1686 unsigned num_metadata, i;
1687 FLAC__StreamMetadata padding, *cuesheet = 0;
1688 FLAC__StreamMetadata *static_metadata[4+64]; /* MAGIC +64 is for pictures metadata in options.pictures */
1689 FLAC__StreamMetadata **metadata = static_metadata;
1690 FLAC__StreamEncoderInitStatus init_status;
1691 const FLAC__bool is_cdda = (channels == 1 || channels == 2) && (bps == 16) && (sample_rate == 44100);
1693 FLAC__ASSERT(sizeof(options.pictures)/sizeof(options.pictures[0]) <= 64);
1695 e->replay_gain = options.replay_gain;
1696 e->channels = channels;
1697 e->bits_per_sample = bps;
1698 e->sample_rate = sample_rate;
1700 if(e->replay_gain) {
1701 if(channels != 1 && channels != 2) {
1702 flac__utils_printf(stderr, 1, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
1705 if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) {
1706 flac__utils_printf(stderr, 1, "%s: ERROR, invalid sample rate (%u) for --replay-gain\n", e->inbasefilename, sample_rate);
1709 if(options.is_first_file) {
1710 if(!grabbag__replaygain_init(sample_rate)) {
1711 flac__utils_printf(stderr, 1, "%s: ERROR initializing ReplayGain stage\n", e->inbasefilename);
1718 options.do_mid_side = options.loose_mid_side = false;
1720 if(!parse_cuesheet(&cuesheet, options.cuesheet_filename, e->inbasefilename, is_cdda, e->total_samples_to_encode))
1723 if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? cuesheet : 0, e)) {
1724 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1726 FLAC__metadata_object_delete(cuesheet);
1730 if(flac_decoder_data) {
1732 * we're encoding from FLAC so we will use the FLAC file's
1733 * metadata as the basic for the encoded file
1737 * first handle padding: if --no-padding was specified,
1738 * then delete all padding; else if -P was specified,
1739 * use that instead of existing padding (if any); else
1740 * if existing file has padding, move all existing
1741 * padding blocks to one padding block at the end; else
1742 * use default padding.
1746 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1747 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_PADDING) {
1750 p += flac_decoder_data->metadata_blocks[i]->length;
1751 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1752 flac_decoder_data->metadata_blocks[i] = 0;
1755 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1757 flac_decoder_data->num_metadata_blocks = j;
1758 if(options.padding > 0)
1759 p = options.padding;
1761 p = e->total_samples_to_encode / e->sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8;
1762 if(options.padding != 0) {
1763 if(p > 0 && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1764 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
1765 if(0 == flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]) {
1766 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PADDING block\n", e->inbasefilename);
1768 FLAC__metadata_object_delete(cuesheet);
1771 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->is_last = false; /* the encoder will set this for us */
1772 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->length = p;
1773 flac_decoder_data->num_metadata_blocks++;
1779 * next handle vorbis comment: if any tags were specified
1780 * or there is no existing vorbis comment, we create a
1781 * new vorbis comment (discarding any existing one); else
1782 * we keep the existing one. also need to make sure to
1783 * propagate any channel mask tag.
1786 FLAC__bool vc_found = false;
1787 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1788 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
1790 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT && options.vorbis_comment->data.vorbis_comment.num_comments > 0) {
1791 (void) flac__utils_get_channel_mask_tag(flac_decoder_data->metadata_blocks[i], &channel_mask);
1792 flac__utils_printf(stderr, 1, "%s: WARNING, replacing tags from input FLAC file with those given on the command-line\n", e->inbasefilename);
1793 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1794 flac_decoder_data->metadata_blocks[i] = 0;
1797 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1799 flac_decoder_data->num_metadata_blocks = j;
1800 if((!vc_found || options.vorbis_comment->data.vorbis_comment.num_comments > 0) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1802 FLAC__StreamMetadata *vc = FLAC__metadata_object_clone(options.vorbis_comment);
1803 if(0 == vc || (channel_mask && !flac__utils_set_channel_mask_tag(vc, channel_mask))) {
1804 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for VORBIS_COMMENT block\n", e->inbasefilename);
1806 FLAC__metadata_object_delete(cuesheet);
1809 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1810 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1811 flac_decoder_data->metadata_blocks[1] = vc;
1812 flac_decoder_data->num_metadata_blocks++;
1817 * next handle cuesheet: if --cuesheet was specified, use
1818 * it; else if file has existing CUESHEET and cuesheet's
1819 * lead-out offset is correct, keep it; else no CUESHEET
1822 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1823 FLAC__bool existing_cuesheet_is_bad = false;
1824 /* check if existing cuesheet matches the input audio */
1825 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && 0 == cuesheet) {
1826 const FLAC__StreamMetadata_CueSheet *cs = &flac_decoder_data->metadata_blocks[i]->data.cue_sheet;
1827 if(e->total_samples_to_encode == 0) {
1828 flac__utils_printf(stderr, 1, "%s: WARNING, cuesheet in input FLAC file cannot be kept if input size is not known, dropping it...\n", e->inbasefilename);
1829 existing_cuesheet_is_bad = true;
1831 else if(e->total_samples_to_encode != cs->tracks[cs->num_tracks-1].offset) {
1832 flac__utils_printf(stderr, 1, "%s: WARNING, lead-out offset of cuesheet in input FLAC file does not match input length, dropping existing cuesheet...\n", e->inbasefilename);
1833 existing_cuesheet_is_bad = true;
1836 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && (existing_cuesheet_is_bad || 0 != cuesheet)) {
1838 flac__utils_printf(stderr, 1, "%s: WARNING, replacing cuesheet in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1839 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1840 flac_decoder_data->metadata_blocks[i] = 0;
1843 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1845 flac_decoder_data->num_metadata_blocks = j;
1846 if(0 != cuesheet && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1848 FLAC__StreamMetadata *cs = FLAC__metadata_object_clone(cuesheet);
1850 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for CUESHEET block\n", e->inbasefilename);
1852 FLAC__metadata_object_delete(cuesheet);
1855 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1856 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1857 flac_decoder_data->metadata_blocks[1] = cs;
1858 flac_decoder_data->num_metadata_blocks++;
1863 * finally handle seektable: if -S- was specified, no
1864 * SEEKTABLE; else if -S was specified, use it/them;
1865 * else if file has existing SEEKTABLE and input size is
1866 * preserved (no --skip/--until/etc specified), keep it;
1867 * else use default seektable options
1869 * note: meanings of num_requested_seek_points:
1870 * -1 : no -S option given, default to some value
1871 * 0 : -S- given (no seektable)
1872 * >0 : one or more -S options given
1875 FLAC__bool existing_seektable = false;
1876 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1877 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE)
1878 existing_seektable = true;
1879 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE && (e->total_samples_to_encode != flac_decoder_data->metadata_blocks[0]->data.stream_info.total_samples || options.num_requested_seek_points >= 0)) {
1880 if(options.num_requested_seek_points > 0)
1881 flac__utils_printf(stderr, 1, "%s: WARNING, replacing seektable in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1882 else if(options.num_requested_seek_points == 0)
1883 ; /* no warning, silently delete existing SEEKTABLE since user specified --no-seektable (-S-) */
1885 flac__utils_printf(stderr, 1, "%s: WARNING, can't use existing seektable in input FLAC since the input size is changing or unknown, dropping existing SEEKTABLE block...\n", e->inbasefilename);
1886 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1887 flac_decoder_data->metadata_blocks[i] = 0;
1888 existing_seektable = false;
1891 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1893 flac_decoder_data->num_metadata_blocks = j;
1894 if((options.num_requested_seek_points > 0 || (options.num_requested_seek_points < 0 && !existing_seektable)) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1896 FLAC__StreamMetadata *st = FLAC__metadata_object_clone(e->seek_table_template);
1898 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for SEEKTABLE block\n", e->inbasefilename);
1900 FLAC__metadata_object_delete(cuesheet);
1903 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1904 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1905 flac_decoder_data->metadata_blocks[1] = st;
1906 flac_decoder_data->num_metadata_blocks++;
1909 metadata = &flac_decoder_data->metadata_blocks[1]; /* don't include STREAMINFO */
1910 num_metadata = flac_decoder_data->num_metadata_blocks - 1;
1914 * we're not encoding from FLAC so we will build the metadata
1918 if(e->seek_table_template->data.seek_table.num_points > 0) {
1919 e->seek_table_template->is_last = false; /* the encoder will set this for us */
1920 metadata[num_metadata++] = e->seek_table_template;
1923 metadata[num_metadata++] = cuesheet;
1925 if(!flac__utils_set_channel_mask_tag(options.vorbis_comment, channel_mask)) {
1926 flac__utils_printf(stderr, 1, "%s: ERROR adding channel mask tag\n", e->inbasefilename);
1928 FLAC__metadata_object_delete(cuesheet);
1932 metadata[num_metadata++] = options.vorbis_comment;
1933 for(i = 0; i < options.num_pictures; i++)
1934 metadata[num_metadata++] = options.pictures[i];
1935 if(options.padding != 0) {
1936 padding.is_last = false; /* the encoder will set this for us */
1937 padding.type = FLAC__METADATA_TYPE_PADDING;
1938 padding.length = (unsigned)(options.padding>0? options.padding : (e->total_samples_to_encode / e->sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8));
1939 metadata[num_metadata++] = &padding;
1943 /* check for a few things that have not already been checked. the
1944 * FLAC__stream_encoder_init*() will check it but only return
1945 * FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA so we check some
1946 * up front to give a better error message.
1948 if(!verify_metadata(e, metadata, num_metadata)) {
1950 FLAC__metadata_object_delete(cuesheet);
1954 e->blocksize = options.blocksize;
1955 e->stats_mask = (options.do_exhaustive_model_search || options.do_qlp_coeff_prec_search)? 0x0f : 0x3f;
1957 #ifdef FLAC__HAS_OGG
1959 OggFLAC__stream_encoder_set_serial_number(e->encoder.ogg, options.serial_number);
1960 OggFLAC__stream_encoder_set_verify(e->encoder.ogg, options.verify);
1961 OggFLAC__stream_encoder_set_streamable_subset(e->encoder.ogg, !options.lax);
1962 OggFLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.ogg, options.do_mid_side);
1963 OggFLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.ogg, options.loose_mid_side);
1964 OggFLAC__stream_encoder_set_channels(e->encoder.ogg, channels);
1965 OggFLAC__stream_encoder_set_bits_per_sample(e->encoder.ogg, bps);
1966 OggFLAC__stream_encoder_set_sample_rate(e->encoder.ogg, sample_rate);
1967 OggFLAC__stream_encoder_set_blocksize(e->encoder.ogg, options.blocksize);
1968 OggFLAC__stream_encoder_set_apodization(e->encoder.ogg, options.apodizations);
1969 OggFLAC__stream_encoder_set_max_lpc_order(e->encoder.ogg, options.max_lpc_order);
1970 OggFLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.ogg, options.qlp_coeff_precision);
1971 OggFLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg, options.do_qlp_coeff_prec_search);
1972 OggFLAC__stream_encoder_set_do_escape_coding(e->encoder.ogg, options.do_escape_coding);
1973 OggFLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.ogg, options.do_exhaustive_model_search);
1974 OggFLAC__stream_encoder_set_min_residual_partition_order(e->encoder.ogg, options.min_residual_partition_order);
1975 OggFLAC__stream_encoder_set_max_residual_partition_order(e->encoder.ogg, options.max_residual_partition_order);
1976 OggFLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.ogg, options.rice_parameter_search_dist);
1977 OggFLAC__stream_encoder_set_total_samples_estimate(e->encoder.ogg, e->total_samples_to_encode);
1978 OggFLAC__stream_encoder_set_metadata(e->encoder.ogg, (num_metadata > 0)? metadata : 0, num_metadata);
1980 OggFLAC__stream_encoder_disable_constant_subframes(e->encoder.ogg, options.debug.disable_constant_subframes);
1981 OggFLAC__stream_encoder_disable_fixed_subframes(e->encoder.ogg, options.debug.disable_fixed_subframes);
1982 OggFLAC__stream_encoder_disable_verbatim_subframes(e->encoder.ogg, options.debug.disable_verbatim_subframes);
1984 init_status = OggFLAC__stream_encoder_init_file(e->encoder.ogg, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
1985 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1986 print_error_with_init_status(e, "ERROR initializing encoder", init_status);
1988 FLAC__metadata_object_delete(cuesheet);
1995 FLAC__stream_encoder_set_verify(e->encoder.flac, options.verify);
1996 FLAC__stream_encoder_set_streamable_subset(e->encoder.flac, !options.lax);
1997 FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.flac, options.do_mid_side);
1998 FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.flac, options.loose_mid_side);
1999 FLAC__stream_encoder_set_channels(e->encoder.flac, channels);
2000 FLAC__stream_encoder_set_bits_per_sample(e->encoder.flac, bps);
2001 FLAC__stream_encoder_set_sample_rate(e->encoder.flac, sample_rate);
2002 FLAC__stream_encoder_set_blocksize(e->encoder.flac, options.blocksize);
2003 FLAC__stream_encoder_set_apodization(e->encoder.flac, options.apodizations);
2004 FLAC__stream_encoder_set_max_lpc_order(e->encoder.flac, options.max_lpc_order);
2005 FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.flac, options.qlp_coeff_precision);
2006 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac, options.do_qlp_coeff_prec_search);
2007 FLAC__stream_encoder_set_do_escape_coding(e->encoder.flac, options.do_escape_coding);
2008 FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.flac, options.do_exhaustive_model_search);
2009 FLAC__stream_encoder_set_min_residual_partition_order(e->encoder.flac, options.min_residual_partition_order);
2010 FLAC__stream_encoder_set_max_residual_partition_order(e->encoder.flac, options.max_residual_partition_order);
2011 FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.flac, options.rice_parameter_search_dist);
2012 FLAC__stream_encoder_set_total_samples_estimate(e->encoder.flac, e->total_samples_to_encode);
2013 FLAC__stream_encoder_set_metadata(e->encoder.flac, (num_metadata > 0)? metadata : 0, num_metadata);
2015 FLAC__stream_encoder_disable_constant_subframes(e->encoder.flac, options.debug.disable_constant_subframes);
2016 FLAC__stream_encoder_disable_fixed_subframes(e->encoder.flac, options.debug.disable_fixed_subframes);
2017 FLAC__stream_encoder_disable_verbatim_subframes(e->encoder.flac, options.debug.disable_verbatim_subframes);
2019 init_status = FLAC__stream_encoder_init_file(e->encoder.flac, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
2020 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
2021 print_error_with_init_status(e, "ERROR initializing encoder", init_status);
2023 FLAC__metadata_object_delete(cuesheet);
2029 FLAC__metadata_object_delete(cuesheet);
2034 FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples)
2036 if(e->replay_gain) {
2037 if(!grabbag__replaygain_analyze(buffer, e->channels==2, e->bits_per_sample, samples)) {
2038 flac__utils_printf(stderr, 1, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename);
2042 #ifdef FLAC__HAS_OGG
2044 return OggFLAC__stream_encoder_process(e->encoder.ogg, buffer, samples);
2047 return FLAC__stream_encoder_process(e->encoder.flac, buffer, samples);
2050 FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e)
2052 const FLAC__bool only_placeholders = e->is_stdout;
2053 FLAC__bool has_real_points;
2055 if(num_requested_seek_points == 0 && 0 == cuesheet)
2058 if(num_requested_seek_points < 0) {
2059 requested_seek_points = "10s;";
2060 num_requested_seek_points = 1;
2063 if(num_requested_seek_points > 0) {
2064 if(!grabbag__seektable_convert_specification_to_template(requested_seek_points, only_placeholders, e->total_samples_to_encode, e->sample_rate, e->seek_table_template, &has_real_points))
2070 const FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet;
2071 for(i = 0; i < cs->num_tracks; i++) {
2072 const FLAC__StreamMetadata_CueSheet_Track *tr = cs->tracks+i;
2073 for(j = 0; j < tr->num_indices; j++) {
2074 if(!FLAC__metadata_object_seektable_template_append_point(e->seek_table_template, tr->offset + tr->indices[j].offset))
2076 has_real_points = true;
2080 if(!FLAC__metadata_object_seektable_template_sort(e->seek_table_template, /*compact=*/true))
2084 if(has_real_points) {
2086 flac__utils_printf(stderr, 1, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename);
2093 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
2095 /* convert from mm:ss.sss to sample number if necessary */
2096 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
2098 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
2099 if(spec->is_relative && spec->value.samples == 0) {
2100 spec->is_relative = false;
2104 /* in any other case the total samples in the input must be known */
2105 if(total_samples_in_input == 0) {
2106 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when input length is unknown\n", inbasefilename);
2110 FLAC__ASSERT(spec->value_is_samples);
2112 /* convert relative specifications to absolute */
2113 if(spec->is_relative) {
2114 if(spec->value.samples <= 0)
2115 spec->value.samples += (FLAC__int64)total_samples_in_input;
2117 spec->value.samples += skip;
2118 spec->is_relative = false;
2122 if(spec->value.samples < 0) {
2123 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
2126 if((FLAC__uint64)spec->value.samples <= skip) {
2127 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
2130 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
2131 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
2138 FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata)
2140 FLAC__bool metadata_picture_has_type1 = false;
2141 FLAC__bool metadata_picture_has_type2 = false;
2144 FLAC__ASSERT(0 != metadata);
2145 for(i = 0; i < num_metadata; i++) {
2146 const FLAC__StreamMetadata *m = metadata[i];
2147 if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
2148 if(!FLAC__format_seektable_is_legal(&m->data.seek_table)) {
2149 flac__utils_printf(stderr, 1, "%s: ERROR: SEEKTABLE metadata block is invalid\n", e->inbasefilename);
2153 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
2154 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0)) {
2155 flac__utils_printf(stderr, 1, "%s: ERROR: CUESHEET metadata block is invalid\n", e->inbasefilename);
2159 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
2160 const char *error = 0;
2161 if(!FLAC__format_picture_is_legal(&m->data.picture, &error)) {
2162 flac__utils_printf(stderr, 1, "%s: ERROR: PICTURE metadata block is invalid: %s\n", e->inbasefilename, error);
2165 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
2166 if(metadata_picture_has_type1) {
2167 flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 1 (32x32 icon) in the file\n", e->inbasefilename);
2170 metadata_picture_has_type1 = true;
2172 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
2173 if(metadata_picture_has_type2) {
2174 flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 2 (icon) in the file\n", e->inbasefilename);
2177 metadata_picture_has_type2 = true;
2185 FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift, size_t *channel_map)
2187 unsigned wide_sample, sample, channel, byte;
2188 FLAC__int32 *out[FLAC__MAX_CHANNELS];
2190 if(0 == channel_map) {
2191 for(channel = 0; channel < channels; channel++)
2192 out[channel] = dest[channel];
2195 for(channel = 0; channel < channels; channel++)
2196 out[channel] = dest[channel_map[channel]];
2200 if(is_unsigned_samples) {
2201 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2202 for(channel = 0; channel < channels; channel++, sample++)
2203 out[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
2206 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2207 for(channel = 0; channel < channels; channel++, sample++)
2208 out[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
2211 else if(bps == 16) {
2212 if(is_big_endian != is_big_endian_host_) {
2214 const unsigned bytes = wide_samples * channels * (bps >> 3);
2215 for(byte = 0; byte < bytes; byte += 2) {
2216 tmp = ucbuffer_[byte];
2217 ucbuffer_[byte] = ucbuffer_[byte+1];
2218 ucbuffer_[byte+1] = tmp;
2221 if(is_unsigned_samples) {
2222 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2223 for(channel = 0; channel < channels; channel++, sample++)
2224 out[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
2227 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2228 for(channel = 0; channel < channels; channel++, sample++)
2229 out[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
2232 else if(bps == 24) {
2233 if(!is_big_endian) {
2235 const unsigned bytes = wide_samples * channels * (bps >> 3);
2236 for(byte = 0; byte < bytes; byte += 3) {
2237 tmp = ucbuffer_[byte];
2238 ucbuffer_[byte] = ucbuffer_[byte+2];
2239 ucbuffer_[byte+2] = tmp;
2242 if(is_unsigned_samples) {
2243 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2244 for(channel = 0; channel < channels; channel++, sample++) {
2245 out[channel][wide_sample] = ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
2246 out[channel][wide_sample] |= ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
2247 out[channel][wide_sample] |= ucbuffer_[byte++];
2248 out[channel][wide_sample] -= 0x800000;
2252 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2253 for(channel = 0; channel < channels; channel++, sample++) {
2254 out[channel][wide_sample] = scbuffer_[byte++]; out[channel][wide_sample] <<= 8;
2255 out[channel][wide_sample] |= ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
2256 out[channel][wide_sample] |= ucbuffer_[byte++];
2264 FLAC__int32 mask = (1<<shift)-1;
2265 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2266 for(channel = 0; channel < channels; channel++) {
2267 if(out[channel][wide_sample] & mask) {
2268 flac__utils_printf(stderr, 1, "ERROR during read, sample data (channel#%u sample#%u = %d) has non-zero least-significant bits\n WAVE/AIFF header said the last %u bits are not significant and should be zero.\n", channel, wide_sample, out[channel][wide_sample], shift);
2271 out[channel][wide_sample] >>= shift;
2277 void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
2279 EncoderSession *encoder_session = (EncoderSession*)client_data;
2281 (void)encoder, (void)total_frames_estimate;
2283 encoder_session->bytes_written = bytes_written;
2284 encoder_session->samples_written = samples_written;
2286 if(encoder_session->total_samples_to_encode > 0 && !((frames_written-1) & encoder_session->stats_mask))
2287 print_stats(encoder_session);
2290 FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
2293 FLACDecoderData *data = (FLACDecoderData*)client_data;
2296 if (data->fatal_error)
2297 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2299 /* use up lookahead first */
2300 if (data->lookahead_length) {
2301 n = min(data->lookahead_length, *bytes);
2302 memcpy(buffer, data->lookahead, n);
2304 data->lookahead += n;
2305 data->lookahead_length -= n;
2308 /* get the rest from file */
2310 *bytes = n + fread(buffer, 1, *bytes-n, data->encoder_session->fin);
2311 return ferror(data->encoder_session->fin)? FLAC__STREAM_DECODER_READ_STATUS_ABORT : FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2314 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2317 FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2319 FLACDecoderData *data = (FLACDecoderData*)client_data;
2322 if(fseeko(data->encoder_session->fin, (off_t)absolute_byte_offset, SEEK_SET) < 0)
2323 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
2325 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2328 FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2330 FLACDecoderData *data = (FLACDecoderData*)client_data;
2334 if((pos = ftello(data->encoder_session->fin)) < 0)
2335 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
2337 *absolute_byte_offset = (FLAC__uint64)pos;
2338 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2342 FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2344 FLACDecoderData *data = (FLACDecoderData*)client_data;
2347 if(0 == data->filesize)
2348 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
2350 *stream_length = (FLAC__uint64)data->filesize;
2351 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2355 FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data)
2357 FLACDecoderData *data = (FLACDecoderData*)client_data;
2360 return feof(data->encoder_session->fin)? true : false;
2363 FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
2365 FLACDecoderData *data = (FLACDecoderData*)client_data;
2366 FLAC__uint64 n = min(data->samples_left_to_process, frame->header.blocksize);
2369 if(!EncoderSession_process(data->encoder_session, buffer, (unsigned)n)) {
2370 print_error_with_state(data->encoder_session, "ERROR during encoding");
2371 data->fatal_error = true;
2372 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2375 data->samples_left_to_process -= n;
2376 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2379 void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
2381 FLACDecoderData *data = (FLACDecoderData*)client_data;
2384 if (data->fatal_error)
2388 data->num_metadata_blocks == sizeof(data->metadata_blocks)/sizeof(data->metadata_blocks[0]) ||
2389 0 == (data->metadata_blocks[data->num_metadata_blocks] = FLAC__metadata_object_clone(metadata))
2391 data->fatal_error = true;
2393 data->num_metadata_blocks++;
2396 void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
2398 FLACDecoderData *data = (FLACDecoderData*)client_data;
2401 flac__utils_printf(stderr, 1, "%s: ERROR got %s while decoding FLAC input\n", data->encoder_session->inbasefilename, FLAC__StreamDecoderErrorStatusString[status]);
2402 data->fatal_error = true;
2405 FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset)
2408 unsigned last_line_read;
2409 const char *error_message;
2411 if(0 == cuesheet_filename)
2414 if(lead_out_offset == 0) {
2415 flac__utils_printf(stderr, 1, "%s: ERROR cannot import cuesheet when the number of input samples to encode is unknown\n", inbasefilename);
2419 if(0 == (f = fopen(cuesheet_filename, "r"))) {
2420 flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading: %s\n", inbasefilename, cuesheet_filename, strerror(errno));
2424 *cuesheet = grabbag__cuesheet_parse(f, &error_message, &last_line_read, is_cdda, lead_out_offset);
2428 if(0 == *cuesheet) {
2429 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\" on line %u: %s\n", inbasefilename, cuesheet_filename, last_line_read, error_message);
2433 if(!FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/false, &error_message)) {
2434 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\": %s\n", inbasefilename, cuesheet_filename, error_message);
2438 /* if we're expecting CDDA, warn about non-compliance */
2439 if(is_cdda && !FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/true, &error_message)) {
2440 flac__utils_printf(stderr, 1, "%s: WARNING cuesheet \"%s\" is not audio CD compliant: %s\n", inbasefilename, cuesheet_filename, error_message);
2441 (*cuesheet)->data.cue_sheet.is_cd = false;
2447 void print_stats(const EncoderSession *encoder_session)
2449 const FLAC__uint64 samples_written = min(encoder_session->total_samples_to_encode, encoder_session->samples_written);
2450 #if defined _MSC_VER || defined __MINGW32__
2451 /* with MSVC you have to spoon feed it the casting */
2452 const double progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)encoder_session->total_samples_to_encode;
2453 const double ratio = (double)(FLAC__int64)encoder_session->bytes_written / ((double)(FLAC__int64)encoder_session->unencoded_size * min(1.0, progress));
2455 const double progress = (double)samples_written / (double)encoder_session->total_samples_to_encode;
2456 const double ratio = (double)encoder_session->bytes_written / ((double)encoder_session->unencoded_size * min(1.0, progress));
2460 if(samples_written == encoder_session->total_samples_to_encode) {
2461 flac__utils_printf(stderr, 2, "\r%s:%s wrote %u bytes, ratio=%0.3f",
2462 encoder_session->inbasefilename,
2463 encoder_session->verify? " Verify OK," : "",
2464 (unsigned)encoder_session->bytes_written,
2469 flac__utils_printf(stderr, 2, "\r%s: %u%% complete, ratio=%0.3f", encoder_session->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
2473 void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status)
2475 const int ilen = strlen(e->inbasefilename) + 1;
2476 const char *state_string = "";
2478 flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2480 flac__utils_printf(stderr, 1, "%*s init_status = %s\n", ilen, "", FLAC__StreamEncoderInitStatusString[init_status]);
2482 if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR) {
2483 #ifdef FLAC__HAS_OGG
2485 state_string = OggFLAC__stream_encoder_get_resolved_state_string(e->encoder.ogg);
2488 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder.flac);
2490 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2492 /* print out some more info for some errors: */
2494 0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])
2495 #ifdef FLAC__HAS_OGG
2496 || 0 == strcmp(state_string, OggFLAC__StreamEncoderStateString[OggFLAC__STREAM_ENCODER_CLIENT_ERROR])
2499 flac__utils_printf(stderr, 1,
2501 "An error occurred while writing; the most common cause is that the disk is full.\n"
2505 0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_IO_ERROR])
2506 #ifdef FLAC__HAS_OGG
2507 || 0 == strcmp(state_string, OggFLAC__StreamEncoderStateString[OggFLAC__STREAM_ENCODER_IO_ERROR])
2510 flac__utils_printf(stderr, 1,
2512 "An error occurred opening the output file; it is likely that the output\n"
2513 "directory does not exist or is not writable, the output file already exists and\n"
2514 "is not writable, or the disk is full.\n"
2518 else if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE) {
2519 flac__utils_printf(stderr, 1,
2521 "The encoding parameters specified do not conform to the FLAC Subset and may not\n"
2522 "be streamable or playable in hardware devices. If you really understand the\n"
2523 "consequences, you can add --lax to the command-line options to encode with\n"
2524 "these parameters anyway. See http://flac.sourceforge.net/format.html#subset\n"
2529 void print_error_with_state(const EncoderSession *e, const char *message)
2531 const int ilen = strlen(e->inbasefilename) + 1;
2532 const char *state_string;
2534 flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2536 #ifdef FLAC__HAS_OGG
2538 state_string = OggFLAC__stream_encoder_get_resolved_state_string(e->encoder.ogg);
2541 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder.flac);
2543 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2545 /* print out some more info for some errors: */
2547 0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])
2548 #ifdef FLAC__HAS_OGG
2549 || 0 == strcmp(state_string, OggFLAC__StreamEncoderStateString[OggFLAC__STREAM_ENCODER_CLIENT_ERROR])
2552 flac__utils_printf(stderr, 1,
2554 "An error occurred while writing; the most common cause is that the disk is full.\n"
2559 void print_verify_error(EncoderSession *e)
2561 FLAC__uint64 absolute_sample;
2562 unsigned frame_number;
2565 FLAC__int32 expected;
2568 #ifdef FLAC__HAS_OGG
2570 OggFLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.ogg, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2573 FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.flac, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2575 flac__utils_printf(stderr, 1, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
2576 flac__utils_printf(stderr, 1, " Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)absolute_sample, frame_number, channel, sample, expected, got);
2577 flac__utils_printf(stderr, 1, " In all known cases, verify errors are caused by hardware problems,\n");
2578 flac__utils_printf(stderr, 1, " usually overclocking or bad RAM. Delete %s\n", e->outfilename);
2579 flac__utils_printf(stderr, 1, " and repeat the flac command exactly as before. If it does not give a\n");
2580 flac__utils_printf(stderr, 1, " verify error in the exact same place each time you try it, then there is\n");
2581 flac__utils_printf(stderr, 1, " a problem with your hardware; please see the FAQ:\n");
2582 flac__utils_printf(stderr, 1, " http://flac.sourceforge.net/faq.html#tools__hardware_prob\n");
2583 flac__utils_printf(stderr, 1, " If it does fail in the exact same place every time, keep\n");
2584 flac__utils_printf(stderr, 1, " %s and submit a bug report to:\n", e->outfilename);
2585 flac__utils_printf(stderr, 1, " https://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
2586 flac__utils_printf(stderr, 1, " Make sure to upload the FLAC file and use the \"Monitor\" feature to\n");
2587 flac__utils_printf(stderr, 1, " monitor the bug status.\n");
2588 flac__utils_printf(stderr, 1, "Verify FAILED! Do not trust %s\n", e->outfilename);
2591 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
2593 size_t bytes_read = fread(val, 1, 2, f);
2595 if(bytes_read == 0) {
2597 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2603 else if(bytes_read < 2) {
2604 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2608 if(is_big_endian_host_) {
2609 FLAC__byte tmp, *b = (FLAC__byte*)val;
2610 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
2616 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2618 size_t bytes_read = fread(val, 1, 4, f);
2620 if(bytes_read == 0) {
2622 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2628 else if(bytes_read < 4) {
2629 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2633 if(is_big_endian_host_) {
2634 FLAC__byte tmp, *b = (FLAC__byte*)val;
2635 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
2636 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
2642 FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
2644 unsigned char buf[4];
2645 size_t bytes_read= fread(buf, 1, 2, f);
2647 if(bytes_read==0U && eof_ok)
2649 else if(bytes_read<2U) {
2650 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2654 /* this is independent of host endianness */
2655 *val= (FLAC__uint16)(buf[0])<<8 | buf[1];
2660 FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2662 unsigned char buf[4];
2663 size_t bytes_read= fread(buf, 1, 4, f);
2665 if(bytes_read==0U && eof_ok)
2667 else if(bytes_read<4U) {
2668 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2672 /* this is independent of host endianness */
2673 *val= (FLAC__uint32)(buf[0])<<24 | (FLAC__uint32)(buf[1])<<16 |
2674 (FLAC__uint32)(buf[2])<<8 | buf[3];
2679 FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2680 /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
2681 * convert it into an integral value and store in 'val'. Return false if only
2682 * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f' and 'eof_ok' is
2683 * false, or if the value is negative, between zero and one, or too large to be
2684 * represented by 'val'; return true otherwise.
2688 unsigned char buf[10];
2689 size_t bytes_read= fread(buf, 1U, 10U, f);
2690 FLAC__int16 e= ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
2691 FLAC__int16 shift= 63-e;
2694 if(bytes_read==0U && eof_ok)
2696 else if(bytes_read<10U) {
2697 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2700 else if((buf[0]>>7)==1U || e<0 || e>63) {
2701 flac__utils_printf(stderr, 1, "%s: ERROR: invalid floating-point value\n", fn);
2705 for(i= 0U; i<8U; ++i)
2706 p|= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
2707 *val= (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1));
2712 FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset)
2714 static unsigned char dump[8192];
2717 long need = (long)min(offset, LONG_MAX);
2718 if(fseeko(f, need, SEEK_CUR) < 0) {
2719 need = (long)min(offset, sizeof(dump));
2720 if((long)fread(dump, 1, need, f) < need)
2725 #if 0 /* pure non-fseek() version */
2727 const long need = (long)min(offset, sizeof(dump));
2728 if(fread(dump, 1, need, f) < need)
2736 unsigned count_channel_mask_bits(FLAC__uint32 mask)
2747 FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels)
2749 FLAC__uint32 x = 0x80000000;
2750 unsigned count = count_channel_mask_bits(mask);
2751 while(x && count > channels) {
2758 FLAC__ASSERT(count_channel_mask_bits(mask) == channels);