1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009 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 <= 1600 /* @@@ [2G limit] */
41 #include <limits.h> /* for LONG_MAX */
42 #include <math.h> /* for floor() */
43 #include <stdio.h> /* for FILE etc. */
44 #include <stdlib.h> /* for malloc */
45 #include <string.h> /* for strcmp(), strerror() */
47 #include "share/alloc.h"
48 #include "share/grabbag.h"
54 #define min(x,y) ((x)<(y)?(x):(y))
58 #define max(x,y) ((x)>(y)?(x):(y))
60 /* this MUST be >= 588 so that sector aligning can take place with one read */
61 /* this MUST be < 2^sizeof(size_t) / ( FLAC__MAX_CHANNELS * (FLAC__MAX_BITS_PER_SAMPLE/8) ) */
62 #define CHUNK_OF_SAMPLES 2048
67 unsigned bits_per_sample; /* width of sample point, including 'shift' bits, valid bps is bits_per_sample-shift */
68 unsigned shift; /* # of LSBs samples have been shifted left by */
69 unsigned bytes_per_wide_sample; /* for convenience, always == channels*((bps+7)/8), or 0 if N/A to input format (like FLAC) */
70 FLAC__bool is_unsigned_samples;
71 FLAC__bool is_big_endian;
72 FLAC__uint32 channel_mask;
75 /* this is the client_data attached to the FLAC decoder when encoding from a FLAC file */
78 const FLAC__byte *lookahead;
79 unsigned lookahead_length;
80 size_t num_metadata_blocks;
81 FLAC__StreamMetadata *metadata_blocks[1024]; /*@@@ BAD MAGIC number */
82 FLAC__uint64 samples_left_to_process;
83 FLAC__bool fatal_error;
92 FLAC__bool outputfile_opened; /* true if we successfully opened the output file and we want it to be deleted if there is an error */
93 const char *inbasefilename;
94 const char *infilename;
95 const char *outfilename;
97 FLAC__bool treat_warnings_as_errors;
98 FLAC__bool continue_through_decode_errors;
99 FLAC__bool replay_gain;
100 FLAC__uint64 total_samples_to_encode; /* (i.e. "wide samples" aka "sample frames") WATCHOUT: may be 0 to mean 'unknown' */
101 FLAC__uint64 unencoded_size; /* an estimate of the input size, only used in the progress indicator */
102 FLAC__uint64 bytes_written;
103 FLAC__uint64 samples_written;
111 FLAC__uint64 data_bytes;
114 FLAC__StreamDecoder *decoder;
115 FLACDecoderData client_data;
119 FLAC__StreamEncoder *encoder;
122 FLAC__StreamMetadata *seek_table_template;
125 const int FLAC_ENCODE__DEFAULT_PADDING = 8192;
127 static FLAC__bool is_big_endian_host_;
129 static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
130 static signed char *scbuffer_ = (signed char *)ucbuffer_;
131 static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_;
132 static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_;
134 static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
135 static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
139 * unpublished debug routines from the FLAC libs
141 extern FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
142 extern FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
143 extern FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
144 extern FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value);
149 static FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length);
150 static void EncoderSession_destroy(EncoderSession *e);
151 static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero, foreign_metadata_t *foreign_metadata);
152 static int EncoderSession_finish_error(EncoderSession *e);
153 static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options);
154 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
155 static FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e);
156 static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
157 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
158 static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata);
159 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);
160 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);
161 static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
162 static FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
163 static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
164 static FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
165 static FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data);
166 static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
167 static void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
168 static void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
169 static FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, unsigned sample_rate, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors);
170 static void print_stats(const EncoderSession *encoder_session);
171 static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
172 static void print_error_with_state(const EncoderSession *e, const char *message);
173 static void print_verify_error(EncoderSession *e);
174 static FLAC__bool read_bytes(FILE *f, FLAC__byte *buf, size_t n, FLAC__bool eof_ok, const char *fn);
175 static FLAC__bool read_uint16(FILE *f, FLAC__bool big_endian, FLAC__uint16 *val, const char *fn);
176 static FLAC__bool read_uint32(FILE *f, FLAC__bool big_endian, FLAC__uint32 *val, const char *fn);
177 static FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn);
178 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn);
179 static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
180 static unsigned count_channel_mask_bits(FLAC__uint32 mask);
182 static FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels);
185 static FLAC__bool get_sample_info_raw(EncoderSession *e, encode_options_t options)
187 e->info.sample_rate = options.format_options.raw.sample_rate;
188 e->info.channels = options.format_options.raw.channels;
189 e->info.bits_per_sample = options.format_options.raw.bps;
191 e->info.bytes_per_wide_sample = options.format_options.raw.channels * ((options.format_options.raw.bps+7)/8);
192 e->info.is_unsigned_samples = options.format_options.raw.is_unsigned_samples;
193 e->info.is_big_endian = options.format_options.raw.is_big_endian;
194 e->info.channel_mask = 0;
199 static FLAC__bool get_sample_info_wave(EncoderSession *e, encode_options_t options)
201 FLAC__bool got_fmt_chunk = false, got_data_chunk = false, got_ds64_chunk = false;
202 unsigned sample_rate = 0, channels = 0, bps = 0, shift = 0;
203 FLAC__uint32 channel_mask = 0;
204 FLAC__uint64 ds64_data_size = 0;
206 e->info.is_unsigned_samples = false;
207 e->info.is_big_endian = false;
209 if(e->format == FORMAT_WAVE64) {
211 * lookahead[] already has "riff\x2E\x91\xCF\x11\xD6\xA5\x28\xDB", skip over remaining header
213 if(!fskip_ahead(e->fin, 16+8+16-12)) { /* riff GUID + riff size + WAVE GUID - lookahead */
214 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over remaining \"riff\" header\n", e->inbasefilename);
218 /* else lookahead[] already has "RIFFxxxxWAVE" or "RF64xxxxWAVE" */
220 while(!feof(e->fin) && !got_data_chunk) {
221 /* chunk IDs are 4 bytes for WAVE/RF64, 16 for Wave64 */
222 /* for WAVE/RF64 we want the 5th char zeroed so we can treat it like a C string */
223 char chunk_id[16] = { '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' };
225 if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, e->format==FORMAT_WAVE64?16:4, /*eof_ok=*/true, e->inbasefilename)) {
226 flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename);
232 if(e->format == FORMAT_RF64 && !memcmp(chunk_id, "ds64", 4)) { /* RF64 64-bit sizes chunk */
233 FLAC__uint32 xx, data_bytes;
236 flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'ds64' chunks\n", e->inbasefilename);
239 if(got_fmt_chunk || got_data_chunk) {
240 flac__utils_printf(stderr, 1, "%s: ERROR: 'ds64' chunk appears after 'fmt ' or 'data' chunk\n", e->inbasefilename);
244 /* ds64 chunk size */
245 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
248 if(data_bytes < 28) {
249 flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'ds64' chunk has length = %u\n", e->inbasefilename, (unsigned)data_bytes);
252 if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */
255 /* RIFF 64-bit size, lo/hi */
256 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
258 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
261 /* 'data' 64-bit size */
262 if(!read_uint64(e->fin, /*big_endian=*/false, &ds64_data_size, e->inbasefilename))
267 /* skip any extra data in the ds64 chunk */
268 if(!fskip_ahead(e->fin, data_bytes)) {
269 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'ds64' data\n", e->inbasefilename);
273 got_ds64_chunk = true;
276 !memcmp(chunk_id, "fmt ", 4) &&
277 (e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "fmt \xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 16))
278 ) { /* format chunk */
280 FLAC__uint32 xx, data_bytes;
281 FLAC__uint16 wFormatTag; /* wFormatTag word from the 'fmt ' chunk */
284 flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'fmt ' chunks\n", e->inbasefilename);
289 * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
290 * http://windowssdk.msdn.microsoft.com/en-us/library/ms713497.aspx
291 * 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
295 * 2 byte: format type: 1 for WAVE_FORMAT_PCM, 65534 for WAVE_FORMAT_EXTENSIBLE
297 * 4 byte: sample rate (Hz)
298 * 4 byte: avg bytes per sec
299 * 2 byte: block align
300 * 2 byte: bits per sample (not necessarily all significant)
302 * 2 byte: extension size in bytes (usually 0 for WAVEFORMATEX and 22 for WAVEFORMATEXTENSIBLE with PCM)
303 * WAVEFORMATEXTENSIBLE adds
304 * 2 byte: valid bits per sample
305 * 4 byte: channel mask
306 * 16 byte: subformat GUID, first 2 bytes have format type, 1 being PCM
308 * Current spec says WAVEFORMATEX with PCM must have bps == 8 or 16, or any multiple of 8 for WAVEFORMATEXTENSIBLE.
309 * 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.
311 * Block align for WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE is also supposed to be channels*bps/8
313 * If the channel mask has more set bits than # of channels, the extra MSBs are ignored.
314 * If the channel mask has less set bits than # of channels, the extra channels are unassigned to any speaker.
316 * Data is supposed to be unsigned for bps <= 8 else signed.
320 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
323 if(e->format == FORMAT_WAVE64) {
324 /* other half of the size field should be 0 */
325 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
328 flac__utils_printf(stderr, 1, "%s: ERROR: freakishly large Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (unsigned)xx, (unsigned)data_bytes);
331 /* subtract size of header */
332 if (data_bytes < 16+8) {
333 flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'fmt ' chunk has length = 0x%08X%08X\n", e->inbasefilename, (unsigned)xx, (unsigned)data_bytes);
336 data_bytes -= (16+8);
338 if(data_bytes < 16) {
339 flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'fmt ' chunk has length = %u\n", e->inbasefilename, (unsigned)data_bytes);
342 if(e->format != FORMAT_WAVE64) {
343 if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */
347 data_bytes = (data_bytes+7) & (~7u); /* should never happen, but enforce Wave64 alignment rules */
351 if(!read_uint16(e->fin, /*big_endian=*/false, &wFormatTag, e->inbasefilename))
353 if(wFormatTag != 1 /*WAVE_FORMAT_PCM*/ && wFormatTag != 65534 /*WAVE_FORMAT_EXTENSIBLE*/) {
354 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", e->inbasefilename, (unsigned)wFormatTag);
358 /* number of channels */
359 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
361 channels = (unsigned)x;
364 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
368 /* avg bytes per second (ignored) */
369 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
372 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
375 /* bits per sample */
376 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
380 e->info.is_unsigned_samples = (bps <= 8);
382 if(wFormatTag == 1) {
383 if(bps != 8 && bps != 16) {
384 if(bps == 24 || bps == 32) {
385 /* let these slide with a warning since they're unambiguous */
386 flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (unsigned)wFormatTag, bps);
387 if(e->treat_warnings_as_errors)
391 /* @@@ we could add an option to specify left- or right-justified blocks so we knew how to set 'shift' */
392 flac__utils_printf(stderr, 1, "%s: ERROR: legacy WAVE file has format type %u but bits-per-sample=%u\n", e->inbasefilename, (unsigned)wFormatTag, bps);
396 #if 0 /* @@@ reinstate once we can get an answer about whether the samples are left- or right-justified */
397 if((bps+7)/8 * channels == block_align) {
399 /* assume legacy file is byte aligned with some LSBs zero; this is double-checked in format_input() */
400 flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", e->inbasefilename, (unsigned)wFormatTag, block_align, bps, channels);
401 if(e->treat_warnings_as_errors)
403 shift = 8 - (bps % 8);
410 flac__utils_printf(stderr, 1, "%s: ERROR: illegal WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", e->inbasefilename, (unsigned)wFormatTag, block_align, bps, channels);
416 if(channels > 2 && !options.channel_map_none) {
417 flac__utils_printf(stderr, 1, "%s: ERROR: WAVE has >2 channels but is not WAVE_FORMAT_EXTENSIBLE; cannot assign channels\n", e->inbasefilename);
420 FLAC__ASSERT(data_bytes >= 16);
424 if(data_bytes < 40) {
425 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with size %u\n", e->inbasefilename, (unsigned)data_bytes);
429 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
432 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with cbSize %u\n", e->inbasefilename, (unsigned)x);
436 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
438 if((unsigned)x > bps) {
439 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", e->inbasefilename, (unsigned)x, bps);
442 shift = bps - (unsigned)x;
444 if(!read_uint32(e->fin, /*big_endian=*/false, &channel_mask, e->inbasefilename))
446 /* for mono/stereo and unassigned channels, we fake the mask */
447 if(channel_mask == 0) {
449 channel_mask = 0x0001;
450 else if(channels == 2)
451 channel_mask = 0x0003;
453 /* set channel mapping */
454 /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
455 /* front left, front right, center, LFE, back left, back right, surround left, surround right */
456 /* the default mapping is sufficient for 1-6 channels and 7-8 are currently unspecified anyway */
458 /* @@@ example for dolby/vorbis order, for reference later in case it becomes important */
460 options.channel_map_none ||
461 channel_mask == 0x0001 || /* 1 channel: (mono) */
462 channel_mask == 0x0003 || /* 2 channels: front left, front right */
463 channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
464 channel_mask == 0x0603 /* 4 channels: front left, front right, side left, side right */
466 /* keep default channel order */
469 channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
470 channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
471 channel_mask == 0x0607 /* 5 channels: front left, front right, front center, side left, side right */
473 /* to dolby order: front left, center, front right [, surround left, surround right ] */
478 channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
479 channel_mask == 0x060f /* 6 channels: front left, front right, front center, LFE, side left, side right */
481 /* to dolby order: front left, center, front right, surround left, surround right, LFE */
490 options.channel_map_none ||
491 channel_mask == 0x0001 || /* 1 channel: (mono) */
492 channel_mask == 0x0003 || /* 2 channels: front left, front right */
493 channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
494 channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
495 channel_mask == 0x0603 || /* 4 channels: front left, front right, side left, side right */
496 channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
497 channel_mask == 0x0607 || /* 5 channels: front left, front right, front center, side left, side right */
498 channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
499 channel_mask == 0x060f /* 6 channels: front left, front right, front center, LFE, side left, side right */
501 /* keep default channel order */
505 flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk with unsupported channel mask=0x%04X\n\nUse --channel-map=none option to store channels in current order; FLAC files\nmust also be decoded with --channel-map=none to restore correct order.\n", e->inbasefilename, (unsigned)channel_mask);
508 if(!options.channel_map_none) {
509 if(count_channel_mask_bits(channel_mask) < channels) {
510 flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has unassigned channels (#channels=%u)\n", e->inbasefilename, (unsigned)channel_mask, channels);
514 /* supporting this is too difficult with channel mapping; e.g. what if mask is 0x003f but #channels=4?
515 * there would be holes in the order that would have to be filled in, or the mask would have to be
516 * limited and the logic above rerun to see if it still fits into the FLAC mapping.
518 else if(count_channel_mask_bits(channel_mask) > channels)
519 channel_mask = limit_channel_mask(channel_mask, channels);
521 else if(count_channel_mask_bits(channel_mask) > channels) {
522 flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has extra bits for non-existant channels (#channels=%u)\n", e->inbasefilename, (unsigned)channel_mask, channels);
527 /* first part of GUID */
528 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
531 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE chunk with non-PCM format %u\n", e->inbasefilename, (unsigned)x);
537 e->info.bytes_per_wide_sample = channels * (bps / 8);
539 /* skip any extra data in the fmt chunk */
540 if(!fskip_ahead(e->fin, data_bytes)) {
541 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'fmt' data\n", e->inbasefilename);
545 got_fmt_chunk = true;
548 !memcmp(chunk_id, "data", 4) &&
549 (e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "data\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 16))
552 FLAC__uint64 data_bytes;
555 flac__utils_printf(stderr, 1, "%s: ERROR: got 'data' chunk before 'fmt' chunk\n", e->inbasefilename);
560 if(e->format != FORMAT_WAVE64) {
561 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
566 if(!read_uint64(e->fin, /*big_endian=*/false, &data_bytes, e->inbasefilename))
568 /* subtract size of header */
569 if (data_bytes < 16+8) {
570 flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'data' chunk has length = 0x00000000%08X\n", e->inbasefilename, (unsigned)data_bytes);
573 data_bytes -= (16+8);
575 if(e->format == FORMAT_RF64) {
576 if(!got_ds64_chunk) {
577 flac__utils_printf(stderr, 1, "%s: ERROR: RF64 file has no 'ds64' chunk before 'data' chunk\n", e->inbasefilename);
580 if(data_bytes == 0xffffffff)
581 data_bytes = ds64_data_size;
583 if(options.ignore_chunk_sizes) {
584 FLAC__ASSERT(!options.sector_align);
586 flac__utils_printf(stderr, 1, "%s: WARNING: 'data' chunk has non-zero size, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id);
587 if(e->treat_warnings_as_errors)
590 data_bytes = (FLAC__uint64)0 - (FLAC__uint64)e->info.bytes_per_wide_sample; /* max out data_bytes; we'll use EOF as signal to stop reading */
592 else if(0 == data_bytes) {
593 flac__utils_printf(stderr, 1, "%s: ERROR: 'data' chunk has size of 0\n", e->inbasefilename);
597 e->fmt.iff.data_bytes = data_bytes;
599 got_data_chunk = true;
605 if(!options.format_options.iff.foreign_metadata) {
606 if(e->format != FORMAT_WAVE64)
607 flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id);
609 flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk %02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X (use --keep-foreign-metadata to keep)\n",
611 (unsigned)((const unsigned char *)chunk_id)[3],
612 (unsigned)((const unsigned char *)chunk_id)[2],
613 (unsigned)((const unsigned char *)chunk_id)[1],
614 (unsigned)((const unsigned char *)chunk_id)[0],
615 (unsigned)((const unsigned char *)chunk_id)[5],
616 (unsigned)((const unsigned char *)chunk_id)[4],
617 (unsigned)((const unsigned char *)chunk_id)[7],
618 (unsigned)((const unsigned char *)chunk_id)[6],
619 (unsigned)((const unsigned char *)chunk_id)[9],
620 (unsigned)((const unsigned char *)chunk_id)[8],
621 (unsigned)((const unsigned char *)chunk_id)[10],
622 (unsigned)((const unsigned char *)chunk_id)[11],
623 (unsigned)((const unsigned char *)chunk_id)[12],
624 (unsigned)((const unsigned char *)chunk_id)[13],
625 (unsigned)((const unsigned char *)chunk_id)[14],
626 (unsigned)((const unsigned char *)chunk_id)[15]
628 if(e->treat_warnings_as_errors)
633 if(e->format != FORMAT_WAVE64) {
634 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
640 if(!read_uint64(e->fin, /*big_endian=*/false, &skip, e->inbasefilename))
642 skip = (skip+7) & (~(FLAC__uint64)7);
643 /* subtract size of header */
645 flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 chunk has length = 0x00000000%08X\n", e->inbasefilename, (unsigned)skip);
651 if(!fskip_ahead(e->fin, skip)) {
652 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename);
660 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find fmt chunk\n", e->inbasefilename);
663 if(!got_data_chunk) {
664 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find data chunk\n", e->inbasefilename);
668 e->info.sample_rate = sample_rate;
669 e->info.channels = channels;
670 e->info.bits_per_sample = bps;
671 e->info.shift = shift;
672 e->info.channel_mask = channel_mask;
677 static FLAC__bool get_sample_info_aiff(EncoderSession *e, encode_options_t options)
679 FLAC__bool got_comm_chunk = false, got_ssnd_chunk = false;
680 unsigned sample_rate = 0, channels = 0, bps = 0, shift = 0;
681 FLAC__uint64 sample_frames = 0;
682 FLAC__uint32 channel_mask = 0;
684 e->info.is_unsigned_samples = false;
685 e->info.is_big_endian = true;
688 * lookahead[] already has "FORMxxxxAIFF", do chunks
690 while(!feof(e->fin) && !got_ssnd_chunk) {
691 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 */
692 if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, 4, /*eof_ok=*/true, e->inbasefilename)) {
693 flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename);
699 if(!memcmp(chunk_id, "COMM", 4)) { /* common chunk */
703 const FLAC__bool is_aifc = e->format == FORMAT_AIFF_C;
704 const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18);
707 flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'COMM' chunks\n", e->inbasefilename);
711 /* COMM chunk size */
712 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
714 else if(xx < minimum_comm_size) {
715 flac__utils_printf(stderr, 1, "%s: ERROR: non-standard %s 'COMM' chunk has length = %u\n", e->inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx);
718 else if(!is_aifc && xx != minimum_comm_size) {
719 flac__utils_printf(stderr, 1, "%s: WARNING: non-standard %s 'COMM' chunk has length = %u, expected %u\n", e->inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx, minimum_comm_size);
720 if(e->treat_warnings_as_errors)
723 skip = (xx-minimum_comm_size)+(xx & 1);
725 /* number of channels */
726 if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
728 channels = (unsigned)x;
729 if(channels > 2 && !options.channel_map_none) {
730 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
734 /* number of sample frames */
735 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
739 /* bits per sample */
740 if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
743 shift = (bps%8)? 8-(bps%8) : 0; /* SSND data is always byte-aligned, left-justified but format_input() will double-check */
747 if(!read_sane_extended(e->fin, &xx, e->inbasefilename))
751 /* check compression type for AIFF-C */
753 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
755 if(xx == 0x736F7774) /* "sowt" */
756 e->info.is_big_endian = false;
757 else if(xx == 0x4E4F4E45) /* "NONE" */
758 ; /* nothing to do, we already default to big-endian */
760 flac__utils_printf(stderr, 1, "%s: ERROR: can't handle AIFF-C compression type \"%c%c%c%c\"\n", e->inbasefilename, (char)(xx>>24), (char)((xx>>16)&8), (char)((xx>>8)&8), (char)(xx&8));
765 /* set channel mapping */
766 /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
767 /* front left, front right, center, LFE, back left, back right, surround left, surround right */
768 /* specs say the channel ordering is:
770 * ___________________________________________________
774 * quad (ambiguous with 4ch) Fl Fr Bl Br
777 * 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
778 * so we only have unambiguous mappings for 2, 3, and 5 channels
781 options.channel_map_none ||
782 channels == 1 || /* 1 channel: (mono) */
783 channels == 2 || /* 2 channels: left, right */
784 channels == 3 || /* 3 channels: left, right, center */
785 channels == 5 /* 5 channels: front left, front right, center, surround left, surround right */
787 /* keep default channel order */
790 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
794 e->info.bytes_per_wide_sample = channels * (bps / 8);
796 /* skip any extra data in the COMM chunk */
797 if(!fskip_ahead(e->fin, skip)) {
798 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra COMM data\n", e->inbasefilename);
802 got_comm_chunk = true;
804 else if(!memcmp(chunk_id, "SSND", 4) && !got_ssnd_chunk) { /* sound data chunk */
806 FLAC__uint64 data_bytes;
809 if(!got_comm_chunk) {
810 flac__utils_printf(stderr, 1, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", e->inbasefilename);
814 /* SSND chunk size */
815 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
818 if(options.ignore_chunk_sizes) {
819 FLAC__ASSERT(!options.sector_align);
821 flac__utils_printf(stderr, 1, "%s: WARNING: 'SSND' chunk has non-zero size, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id);
822 if(e->treat_warnings_as_errors)
825 data_bytes = (FLAC__uint64)0 - (FLAC__uint64)e->info.bytes_per_wide_sample; /* max out data_bytes; we'll use EOF as signal to stop reading */
827 else if(data_bytes <= 8) {
828 flac__utils_printf(stderr, 1, "%s: ERROR: 'SSND' chunk has size <= 8\n", e->inbasefilename);
832 data_bytes -= 8; /* discount the offset and block size fields */
836 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
839 data_bytes -= offset;
842 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
844 if(xx && !options.ignore_chunk_sizes)
845 data_bytes -= (xx - (data_bytes % xx));
846 if(options.ignore_chunk_sizes) {
848 flac__utils_printf(stderr, 1, "%s: WARNING: 'SSND' chunk has non-zero blocksize, using --ignore-chunk-sizes is probably a bad idea\n", e->inbasefilename, chunk_id);
849 if(e->treat_warnings_as_errors)
854 /* skip any SSND offset bytes */
855 if(!fskip_ahead(e->fin, offset)) {
856 flac__utils_printf(stderr, 1, "%s: ERROR: skipping offset in SSND chunk\n", e->inbasefilename);
860 e->fmt.iff.data_bytes = data_bytes;
862 got_ssnd_chunk = true;
866 if(!options.format_options.iff.foreign_metadata) {
867 flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id);
868 if(e->treat_warnings_as_errors)
873 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
876 unsigned long skip = xx + (xx & 1);
878 FLAC__ASSERT(skip <= LONG_MAX);
879 if(!fskip_ahead(e->fin, skip)) {
880 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename);
887 if(!got_comm_chunk) {
888 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find COMM chunk\n", e->inbasefilename);
891 if(!got_ssnd_chunk && sample_frames) {
892 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find SSND chunk\n", e->inbasefilename);
896 e->info.sample_rate = sample_rate;
897 e->info.channels = channels;
898 e->info.bits_per_sample = bps;
899 e->info.shift = shift;
900 e->info.channel_mask = channel_mask;
905 static FLAC__bool get_sample_info_flac(EncoderSession *e)
908 FLAC__stream_decoder_set_md5_checking(e->fmt.flac.decoder, false) &&
909 FLAC__stream_decoder_set_metadata_respond_all(e->fmt.flac.decoder)
911 flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", e->inbasefilename);
915 if (e->format == FORMAT_OGGFLAC) {
916 if (FLAC__stream_decoder_init_ogg_stream(e->fmt.flac.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=*/e) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
917 flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for Ogg FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder));
921 else if (FLAC__stream_decoder_init_stream(e->fmt.flac.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=*/e) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
922 flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder));
926 if (!FLAC__stream_decoder_process_until_end_of_metadata(e->fmt.flac.decoder) || e->fmt.flac.client_data.fatal_error) {
927 if (e->fmt.flac.client_data.fatal_error)
928 flac__utils_printf(stderr, 1, "%s: ERROR: out of memory or too many metadata blocks while reading metadata in FLAC input\n", e->inbasefilename);
930 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, state = %s\n", e->inbasefilename, FLAC__stream_decoder_get_resolved_state_string(e->fmt.flac.decoder));
934 if (e->fmt.flac.client_data.num_metadata_blocks == 0) {
935 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, got no metadata blocks\n", e->inbasefilename);
938 else if (e->fmt.flac.client_data.metadata_blocks[0]->type != FLAC__METADATA_TYPE_STREAMINFO) {
939 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, first metadata block is not STREAMINFO\n", e->inbasefilename);
942 else if (e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples == 0) {
943 flac__utils_printf(stderr, 1, "%s: ERROR: FLAC input has STREAMINFO with unknown total samples which is not supported\n", e->inbasefilename);
947 e->info.sample_rate = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.sample_rate;
948 e->info.channels = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.channels;
949 e->info.bits_per_sample = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.bits_per_sample;
951 e->info.bytes_per_wide_sample = 0;
952 e->info.is_unsigned_samples = false; /* not applicable for FLAC input */
953 e->info.is_big_endian = false; /* not applicable for FLAC input */
954 e->info.channel_mask = 0;
962 int flac__encode_file(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, encode_options_t options)
964 EncoderSession encoder_session;
965 size_t channel_map[FLAC__MAX_CHANNELS];
966 int info_align_carry = -1, info_align_zero = -1;
968 if(!EncoderSession_construct(&encoder_session, options, infilesize, infile, infilename, outfilename, lookahead, lookahead_length))
971 /* initialize default channel map that preserves channel order */
974 for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++)
978 /* read foreign metadata if requested */
979 if(EncoderSession_format_is_iff(&encoder_session) && options.format_options.iff.foreign_metadata) {
982 options.format == FORMAT_WAVE || options.format == FORMAT_RF64?
983 flac__foreign_metadata_read_from_wave(options.format_options.iff.foreign_metadata, infilename, &error) :
984 options.format == FORMAT_WAVE64?
985 flac__foreign_metadata_read_from_wave64(options.format_options.iff.foreign_metadata, infilename, &error) :
986 flac__foreign_metadata_read_from_aiff(options.format_options.iff.foreign_metadata, infilename, &error)
988 flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", encoder_session.inbasefilename, error);
989 return EncoderSession_finish_error(&encoder_session);
993 /* initialize encoder session with info about the audio (channels/bps/resolution/endianness/etc) */
994 switch(options.format) {
996 if(!get_sample_info_raw(&encoder_session, options))
997 return EncoderSession_finish_error(&encoder_session);
1002 if(!get_sample_info_wave(&encoder_session, options))
1003 return EncoderSession_finish_error(&encoder_session);
1007 if(!get_sample_info_aiff(&encoder_session, options))
1008 return EncoderSession_finish_error(&encoder_session);
1011 case FORMAT_OGGFLAC:
1013 * set up FLAC decoder for the input
1015 if (0 == (encoder_session.fmt.flac.decoder = FLAC__stream_decoder_new())) {
1016 flac__utils_printf(stderr, 1, "%s: ERROR: creating decoder for FLAC input\n", encoder_session.inbasefilename);
1017 return EncoderSession_finish_error(&encoder_session);
1019 if(!get_sample_info_flac(&encoder_session))
1020 return EncoderSession_finish_error(&encoder_session);
1024 /* double protection */
1025 return EncoderSession_finish_error(&encoder_session);
1028 /* some more checks */
1029 if(encoder_session.info.channels == 0 || encoder_session.info.channels > FLAC__MAX_CHANNELS) {
1030 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u\n", encoder_session.inbasefilename, encoder_session.info.channels);
1031 return EncoderSession_finish_error(&encoder_session);
1033 if(!FLAC__format_sample_rate_is_valid(encoder_session.info.sample_rate)) {
1034 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, encoder_session.info.sample_rate);
1035 return EncoderSession_finish_error(&encoder_session);
1037 if(encoder_session.info.bits_per_sample-encoder_session.info.shift < 4 || encoder_session.info.bits_per_sample-encoder_session.info.shift > 24) {
1038 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, encoder_session.info.bits_per_sample-encoder_session.info.shift);
1039 return EncoderSession_finish_error(&encoder_session);
1041 if(options.sector_align) {
1042 if(encoder_session.info.channels != 2) {
1043 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.channels);
1044 return EncoderSession_finish_error(&encoder_session);
1046 if(encoder_session.info.sample_rate != 44100) {
1047 flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.sample_rate);
1048 return EncoderSession_finish_error(&encoder_session);
1050 if(encoder_session.info.bits_per_sample-encoder_session.info.shift != 16) {
1051 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits-per-sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, encoder_session.info.bits_per_sample-encoder_session.info.shift);
1052 return EncoderSession_finish_error(&encoder_session);
1057 FLAC__uint64 total_samples_in_input; /* WATCHOUT: may be 0 to mean "unknown" */
1059 FLAC__uint64 until; /* a value of 0 mean end-of-stream (i.e. --until=-0) */
1060 unsigned align_remainder = 0;
1062 switch(options.format) {
1065 total_samples_in_input = 0;
1067 total_samples_in_input = (FLAC__uint64)infilesize / encoder_session.info.bytes_per_wide_sample + *options.align_reservoir_samples;
1074 /* truncation in the division removes any padding byte that was counted in encoder_session.fmt.iff.data_bytes */
1075 total_samples_in_input = encoder_session.fmt.iff.data_bytes / encoder_session.info.bytes_per_wide_sample + *options.align_reservoir_samples;
1078 case FORMAT_OGGFLAC:
1079 total_samples_in_input = encoder_session.fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples + *options.align_reservoir_samples;
1083 /* double protection */
1084 return EncoderSession_finish_error(&encoder_session);
1088 * now that we know the sample rate, canonicalize the
1089 * --skip string to an absolute sample number:
1091 flac__utils_canonicalize_skip_until_specification(&options.skip_specification, encoder_session.info.sample_rate);
1092 FLAC__ASSERT(options.skip_specification.value.samples >= 0);
1093 skip = (FLAC__uint64)options.skip_specification.value.samples;
1094 FLAC__ASSERT(!options.sector_align || (options.format != FORMAT_FLAC && options.format != FORMAT_OGGFLAC && skip == 0));
1095 /* *options.align_reservoir_samples will be 0 unless --sector-align is used */
1096 FLAC__ASSERT(options.sector_align || *options.align_reservoir_samples == 0);
1099 * now that we possibly know the input size, canonicalize the
1100 * --until string to an absolute sample number:
1102 if(!canonicalize_until_specification(&options.until_specification, encoder_session.inbasefilename, encoder_session.info.sample_rate, skip, total_samples_in_input))
1103 return EncoderSession_finish_error(&encoder_session);
1104 until = (FLAC__uint64)options.until_specification.value.samples;
1105 FLAC__ASSERT(!options.sector_align || until == 0);
1107 /* adjust encoding parameters based on skip and until values */
1108 switch(options.format) {
1110 infilesize -= (off_t)skip * encoder_session.info.bytes_per_wide_sample;
1111 encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1118 encoder_session.fmt.iff.data_bytes -= skip * encoder_session.info.bytes_per_wide_sample;
1119 if(options.ignore_chunk_sizes) {
1120 encoder_session.total_samples_to_encode = 0;
1121 flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n");
1122 FLAC__ASSERT(0 == until);
1125 encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1129 case FORMAT_OGGFLAC:
1130 encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1134 /* double protection */
1135 return EncoderSession_finish_error(&encoder_session);
1138 const FLAC__uint64 trim = total_samples_in_input - until;
1139 FLAC__ASSERT(total_samples_in_input > 0);
1140 FLAC__ASSERT(!options.sector_align);
1141 if(options.format == FORMAT_RAW)
1142 infilesize -= (off_t)trim * encoder_session.info.bytes_per_wide_sample;
1143 else if(EncoderSession_format_is_iff(&encoder_session))
1144 encoder_session.fmt.iff.data_bytes -= trim * encoder_session.info.bytes_per_wide_sample;
1145 encoder_session.total_samples_to_encode -= trim;
1147 if(options.sector_align && (options.format != FORMAT_RAW || infilesize >=0)) { /* for RAW, need to know the filesize */
1148 FLAC__ASSERT(skip == 0); /* asserted above too, but lest we forget */
1149 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
1150 if(options.is_last_file)
1151 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
1153 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
1155 switch(options.format) {
1157 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample;
1160 /* +44 for the size of the WAVE headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1161 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 44;
1164 /* +44 for the size of the WAVE headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1165 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 104;
1168 /* +72 for the size of the RF64 headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1169 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 80;
1173 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1174 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 54;
1177 case FORMAT_OGGFLAC:
1179 /* if we don't know, use 0 as hint to progress indicator (which is the only place this is used): */
1180 encoder_session.unencoded_size = 0;
1181 else if(skip == 0 && until == 0)
1182 encoder_session.unencoded_size = (FLAC__uint64)infilesize;
1183 else if(total_samples_in_input)
1184 encoder_session.unencoded_size = (FLAC__uint64)infilesize * encoder_session.total_samples_to_encode / total_samples_in_input;
1186 encoder_session.unencoded_size = (FLAC__uint64)infilesize;
1190 /* double protection */
1191 return EncoderSession_finish_error(&encoder_session);
1194 if(encoder_session.total_samples_to_encode == 0)
1195 flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n");
1197 if(options.format == FORMAT_FLAC || options.format == FORMAT_OGGFLAC)
1198 encoder_session.fmt.flac.client_data.samples_left_to_process = encoder_session.total_samples_to_encode;
1200 /* init the encoder */
1201 if(!EncoderSession_init_encoder(&encoder_session, options))
1202 return EncoderSession_finish_error(&encoder_session);
1204 /* skip over any samples as requested */
1206 switch(options.format) {
1209 unsigned skip_bytes = encoder_session.info.bytes_per_wide_sample * (unsigned)skip;
1210 if(skip_bytes > lookahead_length) {
1211 skip_bytes -= lookahead_length;
1212 lookahead_length = 0;
1213 if(!fskip_ahead(encoder_session.fin, skip_bytes)) {
1214 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1215 return EncoderSession_finish_error(&encoder_session);
1219 lookahead += skip_bytes;
1220 lookahead_length -= skip_bytes;
1229 if(!fskip_ahead(encoder_session.fin, skip * encoder_session.info.bytes_per_wide_sample)) {
1230 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1231 return EncoderSession_finish_error(&encoder_session);
1235 case FORMAT_OGGFLAC:
1237 * have to wait until the FLAC encoder is set up for writing
1238 * before any seeking in the input FLAC file, because the seek
1239 * itself will usually call the decoder's write callback, and
1240 * our decoder's write callback passes samples to our FLAC
1243 if(!FLAC__stream_decoder_seek_absolute(encoder_session.fmt.flac.decoder, skip)) {
1244 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(encoder_session.fmt.flac.decoder));
1245 return EncoderSession_finish_error(&encoder_session);
1250 /* double protection */
1251 return EncoderSession_finish_error(&encoder_session);
1256 * first do any samples in the reservoir
1258 if(options.sector_align && *options.align_reservoir_samples > 0) {
1259 FLAC__ASSERT(options.format != FORMAT_FLAC && options.format != FORMAT_OGGFLAC); /* check again */
1260 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.align_reservoir, *options.align_reservoir_samples)) {
1261 print_error_with_state(&encoder_session, "ERROR during encoding");
1262 return EncoderSession_finish_error(&encoder_session);
1267 * decrement infilesize or the data_bytes counter if we need to align the file
1269 if(options.sector_align) {
1270 if(options.is_last_file) {
1271 *options.align_reservoir_samples = 0;
1274 *options.align_reservoir_samples = align_remainder;
1275 if(options.format == FORMAT_RAW) {
1276 FLAC__ASSERT(infilesize >= 0);
1277 infilesize -= (off_t)((*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample);
1278 FLAC__ASSERT(infilesize >= 0);
1280 else if(EncoderSession_format_is_iff(&encoder_session))
1281 encoder_session.fmt.iff.data_bytes -= (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample;
1286 * now do samples from the file
1288 switch(options.format) {
1290 if(infilesize < 0) {
1292 while(!feof(infile)) {
1293 if(lookahead_length > 0) {
1294 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample);
1295 memcpy(ucbuffer_, lookahead, lookahead_length);
1296 bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
1297 if(ferror(infile)) {
1298 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1299 return EncoderSession_finish_error(&encoder_session);
1301 lookahead_length = 0;
1304 bytes_read = fread(ucbuffer_, sizeof(unsigned char), CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample, infile);
1306 if(bytes_read == 0) {
1307 if(ferror(infile)) {
1308 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1309 return EncoderSession_finish_error(&encoder_session);
1312 else if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1313 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1314 return EncoderSession_finish_error(&encoder_session);
1317 unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1318 if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map))
1319 return EncoderSession_finish_error(&encoder_session);
1321 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1322 print_error_with_state(&encoder_session, "ERROR during encoding");
1323 return EncoderSession_finish_error(&encoder_session);
1330 const FLAC__uint64 max_input_bytes = infilesize;
1331 FLAC__uint64 total_input_bytes_read = 0;
1332 while(total_input_bytes_read < max_input_bytes) {
1334 size_t wanted = (CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample);
1335 wanted = (size_t) min((FLAC__uint64)wanted, max_input_bytes - total_input_bytes_read);
1337 if(lookahead_length > 0) {
1338 FLAC__ASSERT(lookahead_length <= wanted);
1339 memcpy(ucbuffer_, lookahead, lookahead_length);
1340 wanted -= lookahead_length;
1341 bytes_read = lookahead_length;
1343 bytes_read += fread(ucbuffer_+lookahead_length, sizeof(unsigned char), wanted, infile);
1344 if(ferror(infile)) {
1345 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1346 return EncoderSession_finish_error(&encoder_session);
1349 lookahead_length = 0;
1352 bytes_read = fread(ucbuffer_, sizeof(unsigned char), wanted, infile);
1355 if(bytes_read == 0) {
1356 if(ferror(infile)) {
1357 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1358 return EncoderSession_finish_error(&encoder_session);
1360 else if(feof(infile)) {
1361 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);
1362 if(encoder_session.treat_warnings_as_errors)
1363 return EncoderSession_finish_error(&encoder_session);
1364 total_input_bytes_read = max_input_bytes;
1368 if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1369 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1370 return EncoderSession_finish_error(&encoder_session);
1373 unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1374 if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map))
1375 return EncoderSession_finish_error(&encoder_session);
1377 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1378 print_error_with_state(&encoder_session, "ERROR during encoding");
1379 return EncoderSession_finish_error(&encoder_session);
1381 total_input_bytes_read += bytes_read;
1392 while(encoder_session.fmt.iff.data_bytes > 0) {
1393 const size_t bytes_to_read = (size_t)min(
1394 encoder_session.fmt.iff.data_bytes,
1395 (FLAC__uint64)CHUNK_OF_SAMPLES * (FLAC__uint64)encoder_session.info.bytes_per_wide_sample
1397 size_t bytes_read = fread(ucbuffer_, sizeof(unsigned char), bytes_to_read, infile);
1398 if(bytes_read == 0) {
1399 if(ferror(infile)) {
1400 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1401 return EncoderSession_finish_error(&encoder_session);
1403 else if(feof(infile)) {
1404 if(options.ignore_chunk_sizes) {
1405 flac__utils_printf(stderr, 1, "%s: INFO: hit EOF with --ignore-chunk-sizes, got %u samples\n", encoder_session.inbasefilename, (unsigned)encoder_session.samples_written);
1408 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);
1409 if(encoder_session.treat_warnings_as_errors)
1410 return EncoderSession_finish_error(&encoder_session);
1412 encoder_session.fmt.iff.data_bytes = 0;
1416 if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1417 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1418 return EncoderSession_finish_error(&encoder_session);
1421 unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1422 if(!format_input(input_, wide_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map))
1423 return EncoderSession_finish_error(&encoder_session);
1425 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1426 print_error_with_state(&encoder_session, "ERROR during encoding");
1427 return EncoderSession_finish_error(&encoder_session);
1429 encoder_session.fmt.iff.data_bytes -= bytes_read;
1435 case FORMAT_OGGFLAC:
1436 while(!encoder_session.fmt.flac.client_data.fatal_error && encoder_session.fmt.flac.client_data.samples_left_to_process > 0) {
1437 /* We can also hit the end of stream without samples_left_to_process
1438 * going to 0 if there are errors and continue_through_decode_errors
1439 * is on, so we want to break in that case too:
1441 if(encoder_session.continue_through_decode_errors && FLAC__stream_decoder_get_state(encoder_session.fmt.flac.decoder) == FLAC__STREAM_DECODER_END_OF_STREAM)
1443 if(!FLAC__stream_decoder_process_single(encoder_session.fmt.flac.decoder)) {
1444 flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(encoder_session.fmt.flac.decoder));
1445 return EncoderSession_finish_error(&encoder_session);
1448 if(encoder_session.fmt.flac.client_data.fatal_error) {
1449 flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(encoder_session.fmt.flac.decoder));
1450 return EncoderSession_finish_error(&encoder_session);
1455 /* double protection */
1456 return EncoderSession_finish_error(&encoder_session);
1460 * now read unaligned samples into reservoir or pad with zeroes if necessary
1462 if(options.sector_align) {
1463 if(options.is_last_file) {
1464 unsigned wide_samples = 588 - align_remainder;
1465 if(wide_samples < 588) {
1468 info_align_zero = wide_samples;
1469 for(channel = 0; channel < encoder_session.info.channels; channel++)
1470 memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
1472 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1473 print_error_with_state(&encoder_session, "ERROR during encoding");
1474 return EncoderSession_finish_error(&encoder_session);
1479 if(*options.align_reservoir_samples > 0) {
1481 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1482 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample, infile);
1483 if(bytes_read == 0 && ferror(infile)) {
1484 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1485 return EncoderSession_finish_error(&encoder_session);
1487 else if(bytes_read != (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample) {
1488 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);
1489 if(encoder_session.treat_warnings_as_errors)
1490 return EncoderSession_finish_error(&encoder_session);
1493 info_align_carry = *options.align_reservoir_samples;
1494 if(!format_input(options.align_reservoir, *options.align_reservoir_samples, encoder_session.info.is_big_endian, encoder_session.info.is_unsigned_samples, encoder_session.info.channels, encoder_session.info.bits_per_sample, encoder_session.info.shift, channel_map))
1495 return EncoderSession_finish_error(&encoder_session);
1502 return EncoderSession_finish_ok(
1506 EncoderSession_format_is_iff(&encoder_session)? options.format_options.iff.foreign_metadata : 0
1510 FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length)
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
1530 e->use_ogg = options.use_ogg;
1532 e->verify = options.verify;
1533 e->treat_warnings_as_errors = options.treat_warnings_as_errors;
1534 e->continue_through_decode_errors = options.continue_through_decode_errors;
1536 e->is_stdout = (0 == strcmp(outfilename, "-"));
1537 e->outputfile_opened = false;
1539 e->inbasefilename = grabbag__file_get_basename(infilename);
1540 e->infilename = infilename;
1541 e->outfilename = outfilename;
1543 e->total_samples_to_encode = 0;
1544 e->unencoded_size = 0;
1545 e->bytes_written = 0;
1546 e->samples_written = 0;
1549 memset(&e->info, 0, sizeof(e->info));
1551 e->format = options.format;
1553 switch(options.format) {
1561 e->fmt.iff.data_bytes = 0;
1564 case FORMAT_OGGFLAC:
1565 e->fmt.flac.decoder = 0;
1566 e->fmt.flac.client_data.filesize = infilesize;
1567 e->fmt.flac.client_data.lookahead = lookahead;
1568 e->fmt.flac.client_data.lookahead_length = lookahead_length;
1569 e->fmt.flac.client_data.num_metadata_blocks = 0;
1570 e->fmt.flac.client_data.samples_left_to_process = 0;
1571 e->fmt.flac.client_data.fatal_error = false;
1575 /* double protection */
1582 e->seek_table_template = 0;
1584 if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1585 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1589 e->encoder = FLAC__stream_encoder_new();
1590 if(0 == e->encoder) {
1591 flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1592 EncoderSession_destroy(e);
1599 void EncoderSession_destroy(EncoderSession *e)
1601 if(e->format == FORMAT_FLAC || e->format == FORMAT_OGGFLAC) {
1603 if(e->fmt.flac.decoder)
1604 FLAC__stream_decoder_delete(e->fmt.flac.decoder);
1605 e->fmt.flac.decoder = 0;
1606 for(i = 0; i < e->fmt.flac.client_data.num_metadata_blocks; i++)
1607 FLAC__metadata_object_delete(e->fmt.flac.client_data.metadata_blocks[i]);
1608 e->fmt.flac.client_data.num_metadata_blocks = 0;
1614 if(0 != e->encoder) {
1615 FLAC__stream_encoder_delete(e->encoder);
1619 if(0 != e->seek_table_template) {
1620 FLAC__metadata_object_delete(e->seek_table_template);
1621 e->seek_table_template = 0;
1625 int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero, foreign_metadata_t *foreign_metadata)
1627 FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1629 FLAC__bool verify_error = false;
1632 fse_state = FLAC__stream_encoder_get_state(e->encoder);
1633 ret = FLAC__stream_encoder_finish(e->encoder)? 0 : 1;
1635 fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA ||
1636 FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA
1639 /* all errors except verify errors should interrupt the stats */
1640 if(ret && !verify_error)
1641 print_error_with_state(e, "ERROR during encoding");
1642 else if(e->total_samples_to_encode > 0) {
1644 flac__utils_printf(stderr, 2, "\n");
1648 print_verify_error(e);
1652 if(info_align_carry >= 0) {
1653 flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d samples to be carried over\n", e->inbasefilename, info_align_carry);
1655 if(info_align_zero >= 0) {
1656 flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d zero samples to be appended\n", e->inbasefilename, info_align_zero);
1660 /*@@@@@@ should this go here or somewhere else? */
1661 if(ret == 0 && foreign_metadata) {
1663 if(!flac__foreign_metadata_write_to_flac(foreign_metadata, e->infilename, e->outfilename, &error)) {
1664 flac__utils_printf(stderr, 1, "%s: ERROR: updating foreign metadata in FLAC file: %s\n", e->inbasefilename, error);
1669 EncoderSession_destroy(e);
1674 int EncoderSession_finish_error(EncoderSession *e)
1676 FLAC__ASSERT(e->encoder);
1678 if(e->total_samples_to_encode > 0)
1679 flac__utils_printf(stderr, 2, "\n");
1681 if(FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1682 print_verify_error(e);
1683 else if(e->outputfile_opened)
1684 /* only want to delete the file if we opened it; otherwise it could be an existing file and our overwrite failed */
1685 unlink(e->outfilename);
1687 EncoderSession_destroy(e);
1693 unsigned num_metadata;
1694 FLAC__bool *needs_delete;
1695 FLAC__StreamMetadata **metadata;
1696 FLAC__StreamMetadata *cuesheet; /* always needs to be deleted */
1697 } static_metadata_t;
1699 static void static_metadata_init(static_metadata_t *m)
1701 m->num_metadata = 0;
1702 m->needs_delete = 0;
1707 static void static_metadata_clear(static_metadata_t *m)
1710 for(i = 0; i < m->num_metadata; i++)
1711 if(m->needs_delete[i])
1712 FLAC__metadata_object_delete(m->metadata[i]);
1716 free(m->needs_delete);
1718 FLAC__metadata_object_delete(m->cuesheet);
1719 static_metadata_init(m);
1722 static FLAC__bool static_metadata_append(static_metadata_t *m, FLAC__StreamMetadata *d, FLAC__bool needs_delete)
1725 if(0 == (x = safe_realloc_muladd2_(m->metadata, sizeof(*m->metadata), /*times (*/m->num_metadata, /*+*/1/*)*/)))
1727 m->metadata = (FLAC__StreamMetadata**)x;
1728 if(0 == (x = safe_realloc_muladd2_(m->needs_delete, sizeof(*m->needs_delete), /*times (*/m->num_metadata, /*+*/1/*)*/)))
1730 m->needs_delete = (FLAC__bool*)x;
1731 m->metadata[m->num_metadata] = d;
1732 m->needs_delete[m->num_metadata] = needs_delete;
1737 FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options)
1739 const unsigned channels = e->info.channels;
1740 const unsigned bps = e->info.bits_per_sample - e->info.shift;
1741 const unsigned sample_rate = e->info.sample_rate;
1742 FLACDecoderData *flac_decoder_data = (e->format == FORMAT_FLAC || e->format == FORMAT_OGGFLAC)? &e->fmt.flac.client_data : 0;
1743 FLAC__StreamMetadata padding;
1744 FLAC__StreamMetadata **metadata = 0;
1745 static_metadata_t static_metadata;
1746 unsigned num_metadata = 0, i;
1747 FLAC__StreamEncoderInitStatus init_status;
1748 const FLAC__bool is_cdda = (channels == 1 || channels == 2) && (bps == 16) && (sample_rate == 44100);
1749 char apodizations[2000];
1751 FLAC__ASSERT(sizeof(options.pictures)/sizeof(options.pictures[0]) <= 64);
1753 static_metadata_init(&static_metadata);
1755 e->replay_gain = options.replay_gain;
1757 apodizations[0] = '\0';
1759 if(e->replay_gain) {
1760 if(channels != 1 && channels != 2) {
1761 flac__utils_printf(stderr, 1, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
1764 if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) {
1765 flac__utils_printf(stderr, 1, "%s: ERROR, invalid sample rate (%u) for --replay-gain\n", e->inbasefilename, sample_rate);
1768 if(options.is_first_file) {
1769 if(!grabbag__replaygain_init(sample_rate)) {
1770 flac__utils_printf(stderr, 1, "%s: ERROR initializing ReplayGain stage\n", e->inbasefilename);
1776 if(!parse_cuesheet(&static_metadata.cuesheet, options.cuesheet_filename, e->inbasefilename, sample_rate, is_cdda, e->total_samples_to_encode, e->treat_warnings_as_errors))
1779 if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? static_metadata.cuesheet : 0, e)) {
1780 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1781 static_metadata_clear(&static_metadata);
1785 /* build metadata */
1786 if(flac_decoder_data) {
1788 * we're encoding from FLAC so we will use the FLAC file's
1789 * metadata as the basis for the encoded file
1793 * first handle pictures: simple append any --pictures
1796 for(i = 0; i < options.num_pictures; i++) {
1797 FLAC__StreamMetadata *pic = FLAC__metadata_object_clone(options.pictures[i]);
1799 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PICTURE block\n", e->inbasefilename);
1800 static_metadata_clear(&static_metadata);
1803 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks++] = pic;
1808 * next handle vorbis comment: if any tags were specified
1809 * or there is no existing vorbis comment, we create a
1810 * new vorbis comment (discarding any existing one); else
1811 * we keep the existing one. also need to make sure to
1812 * propagate any channel mask tag.
1814 /* @@@ change to append -T values from options.vorbis_comment if input has VC already? */
1816 FLAC__bool vc_found = false;
1817 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1818 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
1820 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT && options.vorbis_comment->data.vorbis_comment.num_comments > 0) {
1821 (void) flac__utils_get_channel_mask_tag(flac_decoder_data->metadata_blocks[i], &e->info.channel_mask);
1822 flac__utils_printf(stderr, 1, "%s: WARNING, replacing tags from input FLAC file with those given on the command-line\n", e->inbasefilename);
1823 if(e->treat_warnings_as_errors) {
1824 static_metadata_clear(&static_metadata);
1827 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1828 flac_decoder_data->metadata_blocks[i] = 0;
1831 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1833 flac_decoder_data->num_metadata_blocks = j;
1834 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])) {
1836 FLAC__StreamMetadata *vc = FLAC__metadata_object_clone(options.vorbis_comment);
1837 if(0 == vc || (e->info.channel_mask && !flac__utils_set_channel_mask_tag(vc, e->info.channel_mask))) {
1838 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for VORBIS_COMMENT block\n", e->inbasefilename);
1839 static_metadata_clear(&static_metadata);
1842 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1843 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1844 flac_decoder_data->metadata_blocks[1] = vc;
1845 flac_decoder_data->num_metadata_blocks++;
1850 * next handle cuesheet: if --cuesheet was specified, use
1851 * it; else if file has existing CUESHEET and cuesheet's
1852 * lead-out offset is correct, keep it; else no CUESHEET
1855 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1856 FLAC__bool existing_cuesheet_is_bad = false;
1857 /* check if existing cuesheet matches the input audio */
1858 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && 0 == static_metadata.cuesheet) {
1859 const FLAC__StreamMetadata_CueSheet *cs = &flac_decoder_data->metadata_blocks[i]->data.cue_sheet;
1860 if(e->total_samples_to_encode == 0) {
1861 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);
1862 if(e->treat_warnings_as_errors) {
1863 static_metadata_clear(&static_metadata);
1866 existing_cuesheet_is_bad = true;
1868 else if(e->total_samples_to_encode != cs->tracks[cs->num_tracks-1].offset) {
1869 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);
1870 if(e->treat_warnings_as_errors) {
1871 static_metadata_clear(&static_metadata);
1874 existing_cuesheet_is_bad = true;
1877 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && (existing_cuesheet_is_bad || 0 != static_metadata.cuesheet)) {
1878 if(0 != static_metadata.cuesheet) {
1879 flac__utils_printf(stderr, 1, "%s: WARNING, replacing cuesheet in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1880 if(e->treat_warnings_as_errors) {
1881 static_metadata_clear(&static_metadata);
1885 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1886 flac_decoder_data->metadata_blocks[i] = 0;
1889 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1891 flac_decoder_data->num_metadata_blocks = j;
1892 if(0 != static_metadata.cuesheet && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1894 FLAC__StreamMetadata *cs = FLAC__metadata_object_clone(static_metadata.cuesheet);
1896 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for CUESHEET block\n", e->inbasefilename);
1897 static_metadata_clear(&static_metadata);
1900 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1901 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1902 flac_decoder_data->metadata_blocks[1] = cs;
1903 flac_decoder_data->num_metadata_blocks++;
1908 * next handle seektable: if -S- was specified, no
1909 * SEEKTABLE; else if -S was specified, use it/them;
1910 * else if file has existing SEEKTABLE and input size is
1911 * preserved (no --skip/--until/etc specified), keep it;
1912 * else use default seektable options
1914 * note: meanings of num_requested_seek_points:
1915 * -1 : no -S option given, default to some value
1916 * 0 : -S- given (no seektable)
1917 * >0 : one or more -S options given
1920 FLAC__bool existing_seektable = false;
1921 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1922 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE)
1923 existing_seektable = true;
1924 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)) {
1925 if(options.num_requested_seek_points > 0) {
1926 flac__utils_printf(stderr, 1, "%s: WARNING, replacing seektable in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1927 if(e->treat_warnings_as_errors) {
1928 static_metadata_clear(&static_metadata);
1932 else if(options.num_requested_seek_points == 0)
1933 ; /* no warning, silently delete existing SEEKTABLE since user specified --no-seektable (-S-) */
1935 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);
1936 if(e->treat_warnings_as_errors) {
1937 static_metadata_clear(&static_metadata);
1941 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1942 flac_decoder_data->metadata_blocks[i] = 0;
1943 existing_seektable = false;
1946 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1948 flac_decoder_data->num_metadata_blocks = j;
1949 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])) {
1951 FLAC__StreamMetadata *st = FLAC__metadata_object_clone(e->seek_table_template);
1953 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for SEEKTABLE block\n", e->inbasefilename);
1954 static_metadata_clear(&static_metadata);
1957 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1958 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1959 flac_decoder_data->metadata_blocks[1] = st;
1960 flac_decoder_data->num_metadata_blocks++;
1965 * finally handle padding: if --no-padding was specified,
1966 * then delete all padding; else if -P was specified,
1967 * use that instead of existing padding (if any); else
1968 * if existing file has padding, move all existing
1969 * padding blocks to one padding block at the end; else
1970 * use default padding.
1974 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1975 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_PADDING) {
1978 p += flac_decoder_data->metadata_blocks[i]->length;
1979 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1980 flac_decoder_data->metadata_blocks[i] = 0;
1983 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1985 flac_decoder_data->num_metadata_blocks = j;
1986 if(options.padding > 0)
1987 p = options.padding;
1989 p = e->total_samples_to_encode / sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8;
1990 if(options.padding != 0) {
1991 if(p > 0 && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1992 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
1993 if(0 == flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]) {
1994 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PADDING block\n", e->inbasefilename);
1995 static_metadata_clear(&static_metadata);
1998 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->is_last = false; /* the encoder will set this for us */
1999 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->length = p;
2000 flac_decoder_data->num_metadata_blocks++;
2004 metadata = &flac_decoder_data->metadata_blocks[1]; /* don't include STREAMINFO */
2005 num_metadata = flac_decoder_data->num_metadata_blocks - 1;
2009 * we're not encoding from FLAC so we will build the metadata
2012 const foreign_metadata_t *foreign_metadata = EncoderSession_format_is_iff(e)? options.format_options.iff.foreign_metadata : 0;
2014 if(e->seek_table_template->data.seek_table.num_points > 0) {
2015 e->seek_table_template->is_last = false; /* the encoder will set this for us */
2016 static_metadata_append(&static_metadata, e->seek_table_template, /*needs_delete=*/false);
2018 if(0 != static_metadata.cuesheet)
2019 static_metadata_append(&static_metadata, static_metadata.cuesheet, /*needs_delete=*/false);
2020 if(e->info.channel_mask) {
2021 if(!flac__utils_set_channel_mask_tag(options.vorbis_comment, e->info.channel_mask)) {
2022 flac__utils_printf(stderr, 1, "%s: ERROR adding channel mask tag\n", e->inbasefilename);
2023 static_metadata_clear(&static_metadata);
2027 static_metadata_append(&static_metadata, options.vorbis_comment, /*needs_delete=*/false);
2028 for(i = 0; i < options.num_pictures; i++)
2029 static_metadata_append(&static_metadata, options.pictures[i], /*needs_delete=*/false);
2030 if(foreign_metadata) {
2031 for(i = 0; i < foreign_metadata->num_blocks; i++) {
2032 FLAC__StreamMetadata *p = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
2034 flac__utils_printf(stderr, 1, "%s: ERROR: out of memory\n", e->inbasefilename);
2035 static_metadata_clear(&static_metadata);
2038 static_metadata_append(&static_metadata, p, /*needs_delete=*/true);
2039 static_metadata.metadata[static_metadata.num_metadata-1]->length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8 + foreign_metadata->blocks[i].size;
2042 if(options.padding != 0) {
2043 padding.is_last = false; /* the encoder will set this for us */
2044 padding.type = FLAC__METADATA_TYPE_PADDING;
2045 padding.length = (unsigned)(options.padding>0? options.padding : (e->total_samples_to_encode / sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8));
2046 static_metadata_append(&static_metadata, &padding, /*needs_delete=*/false);
2048 metadata = static_metadata.metadata;
2049 num_metadata = static_metadata.num_metadata;
2052 /* check for a few things that have not already been checked. the
2053 * FLAC__stream_encoder_init*() will check it but only return
2054 * FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA so we check some
2055 * up front to give a better error message.
2057 if(!verify_metadata(e, metadata, num_metadata)) {
2058 static_metadata_clear(&static_metadata);
2062 FLAC__stream_encoder_set_verify(e->encoder, options.verify);
2063 FLAC__stream_encoder_set_streamable_subset(e->encoder, !options.lax);
2064 FLAC__stream_encoder_set_channels(e->encoder, channels);
2065 FLAC__stream_encoder_set_bits_per_sample(e->encoder, bps);
2066 FLAC__stream_encoder_set_sample_rate(e->encoder, sample_rate);
2067 for(i = 0; i < options.num_compression_settings; i++) {
2068 switch(options.compression_settings[i].type) {
2070 FLAC__stream_encoder_set_blocksize(e->encoder, options.compression_settings[i].value.t_unsigned);
2072 case CST_COMPRESSION_LEVEL:
2073 FLAC__stream_encoder_set_compression_level(e->encoder, options.compression_settings[i].value.t_unsigned);
2074 apodizations[0] = '\0';
2076 case CST_DO_MID_SIDE:
2077 FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder, options.compression_settings[i].value.t_bool);
2079 case CST_LOOSE_MID_SIDE:
2080 FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder, options.compression_settings[i].value.t_bool);
2082 case CST_APODIZATION:
2083 if(strlen(apodizations)+strlen(options.compression_settings[i].value.t_string)+2 >= sizeof(apodizations)) {
2084 flac__utils_printf(stderr, 1, "%s: ERROR: too many apodization functions requested\n", e->inbasefilename);
2085 static_metadata_clear(&static_metadata);
2089 strcat(apodizations, options.compression_settings[i].value.t_string);
2090 strcat(apodizations, ";");
2093 case CST_MAX_LPC_ORDER:
2094 FLAC__stream_encoder_set_max_lpc_order(e->encoder, options.compression_settings[i].value.t_unsigned);
2096 case CST_QLP_COEFF_PRECISION:
2097 FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder, options.compression_settings[i].value.t_unsigned);
2099 case CST_DO_QLP_COEFF_PREC_SEARCH:
2100 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder, options.compression_settings[i].value.t_bool);
2102 case CST_DO_ESCAPE_CODING:
2103 FLAC__stream_encoder_set_do_escape_coding(e->encoder, options.compression_settings[i].value.t_bool);
2105 case CST_DO_EXHAUSTIVE_MODEL_SEARCH:
2106 FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder, options.compression_settings[i].value.t_bool);
2108 case CST_MIN_RESIDUAL_PARTITION_ORDER:
2109 FLAC__stream_encoder_set_min_residual_partition_order(e->encoder, options.compression_settings[i].value.t_unsigned);
2111 case CST_MAX_RESIDUAL_PARTITION_ORDER:
2112 FLAC__stream_encoder_set_max_residual_partition_order(e->encoder, options.compression_settings[i].value.t_unsigned);
2114 case CST_RICE_PARAMETER_SEARCH_DIST:
2115 FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder, options.compression_settings[i].value.t_unsigned);
2120 FLAC__stream_encoder_set_apodization(e->encoder, apodizations);
2121 FLAC__stream_encoder_set_total_samples_estimate(e->encoder, e->total_samples_to_encode);
2122 FLAC__stream_encoder_set_metadata(e->encoder, (num_metadata > 0)? metadata : 0, num_metadata);
2124 FLAC__stream_encoder_disable_constant_subframes(e->encoder, options.debug.disable_constant_subframes);
2125 FLAC__stream_encoder_disable_fixed_subframes(e->encoder, options.debug.disable_fixed_subframes);
2126 FLAC__stream_encoder_disable_verbatim_subframes(e->encoder, options.debug.disable_verbatim_subframes);
2127 if(!options.debug.do_md5) {
2128 flac__utils_printf(stderr, 1, "%s: WARNING, MD5 computation disabled, resulting file will not have MD5 sum\n", e->inbasefilename);
2129 if(e->treat_warnings_as_errors) {
2130 static_metadata_clear(&static_metadata);
2133 FLAC__stream_encoder_set_do_md5(e->encoder, false);
2138 FLAC__stream_encoder_set_ogg_serial_number(e->encoder, options.serial_number);
2140 init_status = FLAC__stream_encoder_init_ogg_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
2145 init_status = FLAC__stream_encoder_init_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
2148 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
2149 print_error_with_init_status(e, "ERROR initializing encoder", init_status);
2150 if(FLAC__stream_encoder_get_state(e->encoder) != FLAC__STREAM_ENCODER_IO_ERROR)
2151 e->outputfile_opened = true;
2152 static_metadata_clear(&static_metadata);
2156 e->outputfile_opened = true;
2159 (FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) && FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x07 :
2160 (FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x0f :
2163 static_metadata_clear(&static_metadata);
2168 FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples)
2170 if(e->replay_gain) {
2171 if(!grabbag__replaygain_analyze(buffer, e->info.channels==2, e->info.bits_per_sample, samples)) {
2172 flac__utils_printf(stderr, 1, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename);
2173 if(e->treat_warnings_as_errors)
2178 return FLAC__stream_encoder_process(e->encoder, buffer, samples);
2181 FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e)
2184 e->format == FORMAT_WAVE ||
2185 e->format == FORMAT_WAVE64 ||
2186 e->format == FORMAT_RF64 ||
2187 e->format == FORMAT_AIFF ||
2188 e->format == FORMAT_AIFF_C;
2191 FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e)
2193 const FLAC__bool only_placeholders = e->is_stdout;
2194 FLAC__bool has_real_points;
2196 if(num_requested_seek_points == 0 && 0 == cuesheet)
2199 if(num_requested_seek_points < 0) {
2201 /*@@@@@@ workaround ogg bug: too many seekpoints makes table not fit in one page */
2202 if(e->use_ogg && e->total_samples_to_encode > 0 && e->total_samples_to_encode / e->info.sample_rate / 10 > 230)
2203 requested_seek_points = "230x;";
2206 requested_seek_points = "10s;";
2207 num_requested_seek_points = 1;
2210 if(num_requested_seek_points > 0) {
2211 if(!grabbag__seektable_convert_specification_to_template(requested_seek_points, only_placeholders, e->total_samples_to_encode, e->info.sample_rate, e->seek_table_template, &has_real_points))
2217 const FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet;
2218 for(i = 0; i < cs->num_tracks; i++) {
2219 const FLAC__StreamMetadata_CueSheet_Track *tr = cs->tracks+i;
2220 for(j = 0; j < tr->num_indices; j++) {
2221 if(!FLAC__metadata_object_seektable_template_append_point(e->seek_table_template, tr->offset + tr->indices[j].offset))
2223 has_real_points = true;
2227 if(!FLAC__metadata_object_seektable_template_sort(e->seek_table_template, /*compact=*/true))
2231 if(has_real_points) {
2233 flac__utils_printf(stderr, 1, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename);
2234 if(e->treat_warnings_as_errors)
2242 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
2244 /* convert from mm:ss.sss to sample number if necessary */
2245 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
2247 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
2248 if(spec->is_relative && spec->value.samples == 0) {
2249 spec->is_relative = false;
2253 /* in any other case the total samples in the input must be known */
2254 if(total_samples_in_input == 0) {
2255 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when input length is unknown\n", inbasefilename);
2259 FLAC__ASSERT(spec->value_is_samples);
2261 /* convert relative specifications to absolute */
2262 if(spec->is_relative) {
2263 if(spec->value.samples <= 0)
2264 spec->value.samples += (FLAC__int64)total_samples_in_input;
2266 spec->value.samples += skip;
2267 spec->is_relative = false;
2271 if(spec->value.samples < 0) {
2272 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
2275 if((FLAC__uint64)spec->value.samples <= skip) {
2276 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
2279 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
2280 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
2287 FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata)
2289 FLAC__bool metadata_picture_has_type1 = false;
2290 FLAC__bool metadata_picture_has_type2 = false;
2293 FLAC__ASSERT(0 != metadata);
2294 for(i = 0; i < num_metadata; i++) {
2295 const FLAC__StreamMetadata *m = metadata[i];
2296 if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
2297 if(!FLAC__format_seektable_is_legal(&m->data.seek_table)) {
2298 flac__utils_printf(stderr, 1, "%s: ERROR: SEEKTABLE metadata block is invalid\n", e->inbasefilename);
2302 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
2303 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0)) {
2304 flac__utils_printf(stderr, 1, "%s: ERROR: CUESHEET metadata block is invalid\n", e->inbasefilename);
2308 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
2309 const char *error = 0;
2310 if(!FLAC__format_picture_is_legal(&m->data.picture, &error)) {
2311 flac__utils_printf(stderr, 1, "%s: ERROR: PICTURE metadata block is invalid: %s\n", e->inbasefilename, error);
2314 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
2315 if(metadata_picture_has_type1) {
2316 flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 1 (32x32 icon) in the file\n", e->inbasefilename);
2319 metadata_picture_has_type1 = true;
2321 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
2322 if(metadata_picture_has_type2) {
2323 flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 2 (icon) in the file\n", e->inbasefilename);
2326 metadata_picture_has_type2 = true;
2334 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)
2336 unsigned wide_sample, sample, channel, byte;
2337 FLAC__int32 *out[FLAC__MAX_CHANNELS];
2339 if(0 == channel_map) {
2340 for(channel = 0; channel < channels; channel++)
2341 out[channel] = dest[channel];
2344 for(channel = 0; channel < channels; channel++)
2345 out[channel] = dest[channel_map[channel]];
2349 if(is_unsigned_samples) {
2350 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2351 for(channel = 0; channel < channels; channel++, sample++)
2352 out[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
2355 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2356 for(channel = 0; channel < channels; channel++, sample++)
2357 out[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
2360 else if(bps == 16) {
2361 if(is_big_endian != is_big_endian_host_) {
2363 const unsigned bytes = wide_samples * channels * (bps >> 3);
2364 for(byte = 0; byte < bytes; byte += 2) {
2365 tmp = ucbuffer_[byte];
2366 ucbuffer_[byte] = ucbuffer_[byte+1];
2367 ucbuffer_[byte+1] = tmp;
2370 if(is_unsigned_samples) {
2371 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2372 for(channel = 0; channel < channels; channel++, sample++)
2373 out[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
2376 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2377 for(channel = 0; channel < channels; channel++, sample++)
2378 out[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
2381 else if(bps == 24) {
2382 if(!is_big_endian) {
2384 const unsigned bytes = wide_samples * channels * (bps >> 3);
2385 for(byte = 0; byte < bytes; byte += 3) {
2386 tmp = ucbuffer_[byte];
2387 ucbuffer_[byte] = ucbuffer_[byte+2];
2388 ucbuffer_[byte+2] = tmp;
2391 if(is_unsigned_samples) {
2392 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2393 for(channel = 0; channel < channels; channel++, sample++) {
2394 out[channel][wide_sample] = ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
2395 out[channel][wide_sample] |= ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
2396 out[channel][wide_sample] |= ucbuffer_[byte++];
2397 out[channel][wide_sample] -= 0x800000;
2401 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2402 for(channel = 0; channel < channels; channel++, sample++) {
2403 out[channel][wide_sample] = scbuffer_[byte++]; out[channel][wide_sample] <<= 8;
2404 out[channel][wide_sample] |= ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
2405 out[channel][wide_sample] |= ucbuffer_[byte++];
2413 FLAC__int32 mask = (1<<shift)-1;
2414 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2415 for(channel = 0; channel < channels; channel++) {
2416 if(out[channel][wide_sample] & mask) {
2417 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);
2420 out[channel][wide_sample] >>= shift;
2426 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)
2428 EncoderSession *e = (EncoderSession*)client_data;
2430 (void)encoder, (void)total_frames_estimate;
2432 e->bytes_written = bytes_written;
2433 e->samples_written = samples_written;
2435 if(e->total_samples_to_encode > 0 && !((frames_written-1) & e->stats_mask))
2439 FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
2442 EncoderSession *e = (EncoderSession*)client_data;
2443 FLACDecoderData *data = &e->fmt.flac.client_data;
2447 if (data->fatal_error)
2448 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2450 /* use up lookahead first */
2451 if (data->lookahead_length) {
2452 n = min(data->lookahead_length, *bytes);
2453 memcpy(buffer, data->lookahead, n);
2455 data->lookahead += n;
2456 data->lookahead_length -= n;
2459 /* get the rest from file */
2461 *bytes = n + fread(buffer, 1, *bytes-n, e->fin);
2463 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2464 else if(0 == *bytes)
2465 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2467 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2470 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2473 FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2475 EncoderSession *e = (EncoderSession*)client_data;
2478 if(fseeko(e->fin, (off_t)absolute_byte_offset, SEEK_SET) < 0)
2479 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
2481 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2484 FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2486 EncoderSession *e = (EncoderSession*)client_data;
2490 if((pos = ftello(e->fin)) < 0)
2491 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
2493 *absolute_byte_offset = (FLAC__uint64)pos;
2494 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2498 FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2500 const EncoderSession *e = (EncoderSession*)client_data;
2501 const FLACDecoderData *data = &e->fmt.flac.client_data;
2504 if(data->filesize < 0)
2505 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
2507 *stream_length = (FLAC__uint64)data->filesize;
2508 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2512 FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data)
2514 EncoderSession *e = (EncoderSession*)client_data;
2517 return feof(e->fin)? true : false;
2520 FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
2522 EncoderSession *e = (EncoderSession*)client_data;
2523 FLACDecoderData *data = &e->fmt.flac.client_data;
2524 FLAC__uint64 n = min(data->samples_left_to_process, frame->header.blocksize);
2527 if(!EncoderSession_process(e, buffer, (unsigned)n)) {
2528 print_error_with_state(e, "ERROR during encoding");
2529 data->fatal_error = true;
2530 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2533 data->samples_left_to_process -= n;
2534 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2537 void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
2539 EncoderSession *e = (EncoderSession*)client_data;
2540 FLACDecoderData *data = &e->fmt.flac.client_data;
2543 if (data->fatal_error)
2547 data->num_metadata_blocks == sizeof(data->metadata_blocks)/sizeof(data->metadata_blocks[0]) ||
2548 0 == (data->metadata_blocks[data->num_metadata_blocks] = FLAC__metadata_object_clone(metadata))
2550 data->fatal_error = true;
2552 data->num_metadata_blocks++;
2555 void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
2557 EncoderSession *e = (EncoderSession*)client_data;
2558 FLACDecoderData *data = &e->fmt.flac.client_data;
2561 flac__utils_printf(stderr, 1, "%s: ERROR got %s while decoding FLAC input\n", e->inbasefilename, FLAC__StreamDecoderErrorStatusString[status]);
2562 if(!e->continue_through_decode_errors)
2563 data->fatal_error = true;
2566 FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, unsigned sample_rate, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors)
2569 unsigned last_line_read;
2570 const char *error_message;
2572 if(0 == cuesheet_filename)
2575 if(lead_out_offset == 0) {
2576 flac__utils_printf(stderr, 1, "%s: ERROR cannot import cuesheet when the number of input samples to encode is unknown\n", inbasefilename);
2580 if(0 == (f = fopen(cuesheet_filename, "r"))) {
2581 flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading: %s\n", inbasefilename, cuesheet_filename, strerror(errno));
2585 *cuesheet = grabbag__cuesheet_parse(f, &error_message, &last_line_read, sample_rate, is_cdda, lead_out_offset);
2589 if(0 == *cuesheet) {
2590 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\" on line %u: %s\n", inbasefilename, cuesheet_filename, last_line_read, error_message);
2594 if(!FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/false, &error_message)) {
2595 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\": %s\n", inbasefilename, cuesheet_filename, error_message);
2599 /* if we're expecting CDDA, warn about non-compliance */
2600 if(is_cdda && !FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/true, &error_message)) {
2601 flac__utils_printf(stderr, 1, "%s: WARNING cuesheet \"%s\" is not audio CD compliant: %s\n", inbasefilename, cuesheet_filename, error_message);
2602 if(treat_warnings_as_errors)
2604 (*cuesheet)->data.cue_sheet.is_cd = false;
2610 void print_stats(const EncoderSession *encoder_session)
2612 const FLAC__uint64 samples_written = min(encoder_session->total_samples_to_encode, encoder_session->samples_written);
2613 const FLAC__uint64 uesize = encoder_session->unencoded_size;
2614 #if defined _MSC_VER || defined __MINGW32__
2615 /* with MSVC you have to spoon feed it the casting */
2616 const double progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)encoder_session->total_samples_to_encode;
2617 const double ratio = (double)(FLAC__int64)encoder_session->bytes_written / ((double)(FLAC__int64)(uesize? uesize:1) * min(1.0, progress));
2619 const double progress = (double)samples_written / (double)encoder_session->total_samples_to_encode;
2620 const double ratio = (double)encoder_session->bytes_written / ((double)(uesize? uesize:1) * min(1.0, progress));
2623 FLAC__ASSERT(encoder_session->total_samples_to_encode > 0);
2625 if(samples_written == encoder_session->total_samples_to_encode) {
2626 flac__utils_printf(stderr, 2, "\r%s:%s wrote %u bytes, ratio=",
2627 encoder_session->inbasefilename,
2628 encoder_session->verify? " Verify OK," : "",
2629 (unsigned)encoder_session->bytes_written
2633 flac__utils_printf(stderr, 2, "\r%s: %u%% complete, ratio=", encoder_session->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5));
2636 flac__utils_printf(stderr, 2, "%0.3f", ratio);
2638 flac__utils_printf(stderr, 2, "N/A");
2641 void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status)
2643 const int ilen = strlen(e->inbasefilename) + 1;
2644 const char *state_string = "";
2646 flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2648 flac__utils_printf(stderr, 1, "%*s init_status = %s\n", ilen, "", FLAC__StreamEncoderInitStatusString[init_status]);
2650 if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR) {
2651 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
2653 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2655 /* print out some more info for some errors: */
2656 if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
2657 flac__utils_printf(stderr, 1,
2659 "An error occurred while writing; the most common cause is that the disk is full.\n"
2662 else if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_IO_ERROR])) {
2663 flac__utils_printf(stderr, 1,
2665 "An error occurred opening the output file; it is likely that the output\n"
2666 "directory does not exist or is not writable, the output file already exists and\n"
2667 "is not writable, or the disk is full.\n"
2671 else if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE) {
2672 flac__utils_printf(stderr, 1,
2674 "The encoding parameters specified do not conform to the FLAC Subset and may not\n"
2675 "be streamable or playable in hardware devices. If you really understand the\n"
2676 "consequences, you can add --lax to the command-line options to encode with\n"
2677 "these parameters anyway. See http://flac.sourceforge.net/format.html#subset\n"
2682 void print_error_with_state(const EncoderSession *e, const char *message)
2684 const int ilen = strlen(e->inbasefilename) + 1;
2685 const char *state_string;
2687 flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2689 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
2691 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2693 /* print out some more info for some errors: */
2694 if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
2695 flac__utils_printf(stderr, 1,
2697 "An error occurred while writing; the most common cause is that the disk is full.\n"
2702 void print_verify_error(EncoderSession *e)
2704 FLAC__uint64 absolute_sample;
2705 unsigned frame_number;
2708 FLAC__int32 expected;
2711 FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2713 flac__utils_printf(stderr, 1, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
2714 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);
2715 flac__utils_printf(stderr, 1, " In all known cases, verify errors are caused by hardware problems,\n");
2716 flac__utils_printf(stderr, 1, " usually overclocking or bad RAM. Delete %s\n", e->outfilename);
2717 flac__utils_printf(stderr, 1, " and repeat the flac command exactly as before. If it does not give a\n");
2718 flac__utils_printf(stderr, 1, " verify error in the exact same place each time you try it, then there is\n");
2719 flac__utils_printf(stderr, 1, " a problem with your hardware; please see the FAQ:\n");
2720 flac__utils_printf(stderr, 1, " http://flac.sourceforge.net/faq.html#tools__hardware_prob\n");
2721 flac__utils_printf(stderr, 1, " If it does fail in the exact same place every time, keep\n");
2722 flac__utils_printf(stderr, 1, " %s and submit a bug report to:\n", e->outfilename);
2723 flac__utils_printf(stderr, 1, " https://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
2724 flac__utils_printf(stderr, 1, " Make sure to upload the FLAC file and use the \"Monitor\" feature to\n");
2725 flac__utils_printf(stderr, 1, " monitor the bug status.\n");
2726 flac__utils_printf(stderr, 1, "Verify FAILED! Do not trust %s\n", e->outfilename);
2729 FLAC__bool read_bytes(FILE *f, FLAC__byte *buf, size_t n, FLAC__bool eof_ok, const char *fn)
2731 size_t bytes_read = fread(buf, 1, n, f);
2733 if(bytes_read == 0) {
2735 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2741 if(bytes_read < n) {
2742 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2748 FLAC__bool read_uint16(FILE *f, FLAC__bool big_endian, FLAC__uint16 *val, const char *fn)
2750 if(!read_bytes(f, (FLAC__byte*)val, 2, /*eof_ok=*/false, fn))
2752 if(is_big_endian_host_ != big_endian) {
2753 FLAC__byte tmp, *b = (FLAC__byte*)val;
2754 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
2759 FLAC__bool read_uint32(FILE *f, FLAC__bool big_endian, FLAC__uint32 *val, const char *fn)
2761 if(!read_bytes(f, (FLAC__byte*)val, 4, /*eof_ok=*/false, fn))
2763 if(is_big_endian_host_ != big_endian) {
2764 FLAC__byte tmp, *b = (FLAC__byte*)val;
2765 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
2766 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
2771 FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn)
2773 if(!read_bytes(f, (FLAC__byte*)val, 8, /*eof_ok=*/false, fn))
2775 if(is_big_endian_host_ != big_endian) {
2776 FLAC__byte tmp, *b = (FLAC__byte*)val;
2777 tmp = b[7]; b[7] = b[0]; b[0] = tmp;
2778 tmp = b[6]; b[6] = b[1]; b[1] = tmp;
2779 tmp = b[5]; b[5] = b[2]; b[2] = tmp;
2780 tmp = b[4]; b[4] = b[3]; b[3] = tmp;
2785 FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn)
2786 /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
2787 * convert it into an integral value and store in 'val'. Return false if only
2788 * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f', or if the
2789 * value is negative, between zero and one, or too large to be represented by
2790 * 'val'; return true otherwise.
2799 if(!read_bytes(f, buf, sizeof(buf), /*eof_ok=*/false, fn))
2801 e = ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
2803 if((buf[0]>>7)==1U || e<0 || e>63) {
2804 flac__utils_printf(stderr, 1, "%s: ERROR: invalid floating-point value\n", fn);
2808 for(i = 0; i < 8; ++i)
2809 p |= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
2810 *val = (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1));
2815 FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset)
2817 static unsigned char dump[8192];
2821 /* MS' stdio impl can't even seek forward on stdin, have to use pure non-fseek() version: */
2823 const long need = (long)min(offset, sizeof(dump));
2824 if((long)fread(dump, 1, need, f) < need)
2833 long need = (long)min(offset, LONG_MAX);
2834 if(fseeko(f, need, SEEK_CUR) < 0) {
2835 need = (long)min(offset, sizeof(dump));
2836 if((long)fread(dump, 1, need, f) < need)
2845 unsigned count_channel_mask_bits(FLAC__uint32 mask)
2857 FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels)
2859 FLAC__uint32 x = 0x80000000;
2860 unsigned count = count_channel_mask_bits(mask);
2861 while(x && count > channels) {
2868 FLAC__ASSERT(count_channel_mask_bits(mask) == channels);