1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000-2009 Josh Coalson
3 * Copyright (C) 2011-2013 Xiph.Org Foundation
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <limits.h> /* for LONG_MAX */
26 #include <math.h> /* for floor() */
27 #include <stdio.h> /* for FILE etc. */
28 #include <stdlib.h> /* for malloc */
29 #include <string.h> /* for strcmp(), strerror() */
32 #include "share/alloc.h"
33 #include "share/grabbag.h"
34 #include "share/compat.h"
35 #include "share/private.h"
36 #include "share/safe_str.h"
42 #define min(x,y) ((x)<(y)?(x):(y))
46 #define max(x,y) ((x)>(y)?(x):(y))
48 /* this MUST be >= 588 so that sector aligning can take place with one read */
49 /* this MUST be < 2^sizeof(size_t) / ( FLAC__MAX_CHANNELS * (FLAC__MAX_BITS_PER_SAMPLE/8) ) */
50 #define CHUNK_OF_SAMPLES 2048
55 unsigned bits_per_sample; /* width of sample point, including 'shift' bits, valid bps is bits_per_sample-shift */
56 unsigned shift; /* # of LSBs samples have been shifted left by */
57 unsigned bytes_per_wide_sample; /* for convenience, always == channels*((bps+7)/8), or 0 if N/A to input format (like FLAC) */
58 FLAC__bool is_unsigned_samples;
59 FLAC__bool is_big_endian;
60 FLAC__uint32 channel_mask;
63 /* this is the client_data attached to the FLAC decoder when encoding from a FLAC file */
66 const FLAC__byte *lookahead;
67 unsigned lookahead_length;
68 size_t num_metadata_blocks;
69 FLAC__StreamMetadata *metadata_blocks[1024]; /*@@@ BAD MAGIC number */
70 FLAC__uint64 samples_left_to_process;
71 FLAC__bool fatal_error;
80 FLAC__bool outputfile_opened; /* true if we successfully opened the output file and we want it to be deleted if there is an error */
81 const char *inbasefilename;
82 const char *infilename;
83 const char *outfilename;
85 FLAC__bool treat_warnings_as_errors;
86 FLAC__bool continue_through_decode_errors;
87 FLAC__bool replay_gain;
88 FLAC__uint64 total_samples_to_encode; /* (i.e. "wide samples" aka "sample frames") WATCHOUT: may be 0 to mean 'unknown' */
89 FLAC__uint64 unencoded_size; /* an estimate of the input size, only used in the progress indicator */
90 FLAC__uint64 bytes_written;
91 FLAC__uint64 samples_written;
99 FLAC__uint64 data_bytes;
102 FLAC__StreamDecoder *decoder;
103 FLACDecoderData client_data;
107 FLAC__StreamEncoder *encoder;
110 FLAC__StreamMetadata *seek_table_template;
113 const int FLAC_ENCODE__DEFAULT_PADDING = 8192;
115 static FLAC__bool is_big_endian_host_;
117 static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
118 static signed char *scbuffer_ = (signed char *)ucbuffer_;
119 static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_;
120 static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_;
122 static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
123 static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
129 static FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, FLAC__off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length);
130 static void EncoderSession_destroy(EncoderSession *e);
131 static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero, foreign_metadata_t *foreign_metadata);
132 static int EncoderSession_finish_error(EncoderSession *e);
133 static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options);
134 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
135 static FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e);
136 static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
137 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
138 static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata);
139 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);
140 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);
141 static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
142 static FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
143 static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
144 static FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
145 static FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data);
146 static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
147 static void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
148 static void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
149 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);
150 static void print_stats(const EncoderSession *encoder_session);
151 static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
152 static void print_error_with_state(const EncoderSession *e, const char *message);
153 static void print_verify_error(EncoderSession *e);
154 static FLAC__bool read_bytes(FILE *f, FLAC__byte *buf, size_t n, FLAC__bool eof_ok, const char *fn);
155 static FLAC__bool read_uint16(FILE *f, FLAC__bool big_endian, FLAC__uint16 *val, const char *fn);
156 static FLAC__bool read_uint32(FILE *f, FLAC__bool big_endian, FLAC__uint32 *val, const char *fn);
157 static FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn);
158 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn);
159 static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
160 static unsigned count_channel_mask_bits(FLAC__uint32 mask);
162 static FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels);
165 static FLAC__bool get_sample_info_raw(EncoderSession *e, encode_options_t options)
167 e->info.sample_rate = options.format_options.raw.sample_rate;
168 e->info.channels = options.format_options.raw.channels;
169 e->info.bits_per_sample = options.format_options.raw.bps;
171 e->info.bytes_per_wide_sample = options.format_options.raw.channels * ((options.format_options.raw.bps+7)/8);
172 e->info.is_unsigned_samples = options.format_options.raw.is_unsigned_samples;
173 e->info.is_big_endian = options.format_options.raw.is_big_endian;
174 e->info.channel_mask = 0;
179 static FLAC__bool get_sample_info_wave(EncoderSession *e, encode_options_t options)
181 FLAC__bool got_fmt_chunk = false, got_data_chunk = false, got_ds64_chunk = false;
182 unsigned sample_rate = 0, channels = 0, bps = 0, shift = 0;
183 FLAC__uint32 channel_mask = 0;
184 FLAC__uint64 ds64_data_size = 0;
186 e->info.is_unsigned_samples = false;
187 e->info.is_big_endian = false;
189 if(e->format == FORMAT_WAVE64) {
191 * lookahead[] already has "riff\x2E\x91\xCF\x11\xA5\xD6\x28\xDB", skip over remaining header
193 if(!fskip_ahead(e->fin, 16+8+16-12)) { /* riff GUID + riff size + WAVE GUID - lookahead */
194 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over remaining \"riff\" header\n", e->inbasefilename);
198 /* else lookahead[] already has "RIFFxxxxWAVE" or "RF64xxxxWAVE" */
200 while(!feof(e->fin) && !got_data_chunk) {
201 /* chunk IDs are 4 bytes for WAVE/RF64, 16 for Wave64 */
202 /* for WAVE/RF64 we want the 5th char zeroed so we can treat it like a C string */
203 char chunk_id[16] = { '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' };
205 if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, e->format==FORMAT_WAVE64?16:4, /*eof_ok=*/true, e->inbasefilename)) {
206 flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename);
212 if(e->format == FORMAT_RF64 && !memcmp(chunk_id, "ds64", 4)) { /* RF64 64-bit sizes chunk */
213 FLAC__uint32 xx, data_bytes;
216 flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'ds64' chunks\n", e->inbasefilename);
219 if(got_fmt_chunk || got_data_chunk) {
220 flac__utils_printf(stderr, 1, "%s: ERROR: 'ds64' chunk appears after 'fmt ' or 'data' chunk\n", e->inbasefilename);
224 /* ds64 chunk size */
225 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
228 if(data_bytes < 28) {
229 flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'ds64' chunk has length = %u\n", e->inbasefilename, (unsigned)data_bytes);
232 if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */
235 /* RIFF 64-bit size, lo/hi */
236 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
238 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
241 /* 'data' 64-bit size */
242 if(!read_uint64(e->fin, /*big_endian=*/false, &ds64_data_size, e->inbasefilename))
247 /* skip any extra data in the ds64 chunk */
248 if(!fskip_ahead(e->fin, data_bytes)) {
249 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'ds64' data\n", e->inbasefilename);
253 got_ds64_chunk = true;
256 !memcmp(chunk_id, "fmt ", 4) &&
257 (e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "fmt \xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 16))
258 ) { /* format chunk */
260 FLAC__uint32 xx, data_bytes;
261 FLAC__uint16 wFormatTag; /* wFormatTag word from the 'fmt ' chunk */
264 flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'fmt ' chunks\n", e->inbasefilename);
269 * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
270 * http://windowssdk.msdn.microsoft.com/en-us/library/ms713497.aspx
271 * 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
275 * 2 byte: format type: 1 for WAVE_FORMAT_PCM, 65534 for WAVE_FORMAT_EXTENSIBLE
277 * 4 byte: sample rate (Hz)
278 * 4 byte: avg bytes per sec
279 * 2 byte: block align
280 * 2 byte: bits per sample (not necessarily all significant)
282 * 2 byte: extension size in bytes (usually 0 for WAVEFORMATEX and 22 for WAVEFORMATEXTENSIBLE with PCM)
283 * WAVEFORMATEXTENSIBLE adds
284 * 2 byte: valid bits per sample
285 * 4 byte: channel mask
286 * 16 byte: subformat GUID, first 2 bytes have format type, 1 being PCM
288 * Current spec says WAVEFORMATEX with PCM must have bps == 8 or 16, or any multiple of 8 for WAVEFORMATEXTENSIBLE.
289 * 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.
291 * Block align for WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE is also supposed to be channels*bps/8
293 * If the channel mask has more set bits than # of channels, the extra MSBs are ignored.
294 * If the channel mask has less set bits than # of channels, the extra channels are unassigned to any speaker.
296 * Data is supposed to be unsigned for bps <= 8 else signed.
300 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
303 if(e->format == FORMAT_WAVE64) {
304 /* other half of the size field should be 0 */
305 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
308 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);
311 /* subtract size of header */
312 if (data_bytes < 16+8) {
313 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);
316 data_bytes -= (16+8);
318 if(data_bytes < 16) {
319 flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'fmt ' chunk has length = %u\n", e->inbasefilename, (unsigned)data_bytes);
322 if(e->format != FORMAT_WAVE64) {
323 if(data_bytes & 1) /* should never happen, but enforce WAVE alignment rules */
327 data_bytes = (data_bytes+7) & (~7u); /* should never happen, but enforce Wave64 alignment rules */
331 if(!read_uint16(e->fin, /*big_endian=*/false, &wFormatTag, e->inbasefilename))
333 if(wFormatTag != 1 /*WAVE_FORMAT_PCM*/ && wFormatTag != 65534 /*WAVE_FORMAT_EXTENSIBLE*/) {
334 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", e->inbasefilename, (unsigned)wFormatTag);
338 /* number of channels */
339 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
341 channels = (unsigned)x;
344 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
348 /* avg bytes per second (ignored) */
349 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
352 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
355 /* bits per sample */
356 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
360 e->info.is_unsigned_samples = (bps <= 8);
362 if(wFormatTag == 1) {
363 if(bps != 8 && bps != 16) {
364 if(bps == 24 || bps == 32) {
365 /* let these slide with a warning since they're unambiguous */
366 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);
367 if(e->treat_warnings_as_errors)
371 /* @@@ we could add an option to specify left- or right-justified blocks so we knew how to set 'shift' */
372 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);
376 #if 0 /* @@@ reinstate once we can get an answer about whether the samples are left- or right-justified */
377 if((bps+7)/8 * channels == block_align) {
379 /* assume legacy file is byte aligned with some LSBs zero; this is double-checked in format_input() */
380 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);
381 if(e->treat_warnings_as_errors)
383 shift = 8 - (bps % 8);
390 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);
396 if(channels > 2 && !options.channel_map_none) {
397 flac__utils_printf(stderr, 1, "%s: ERROR: WAVE has >2 channels but is not WAVE_FORMAT_EXTENSIBLE; cannot assign channels\n", e->inbasefilename);
400 FLAC__ASSERT(data_bytes >= 16);
404 if(data_bytes < 40) {
405 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with size %u\n", e->inbasefilename, (unsigned)data_bytes);
409 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
412 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with cbSize %u\n", e->inbasefilename, (unsigned)x);
416 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
418 if((unsigned)x > bps) {
419 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", e->inbasefilename, (unsigned)x, bps);
422 shift = bps - (unsigned)x;
424 if(!read_uint32(e->fin, /*big_endian=*/false, &channel_mask, e->inbasefilename))
426 /* for mono/stereo and unassigned channels, we fake the mask */
427 if(channel_mask == 0) {
429 channel_mask = 0x0001;
430 else if(channels == 2)
431 channel_mask = 0x0003;
433 /* set channel mapping */
434 /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
435 /* front left, front right, center, LFE, back left, back right, surround left, surround right */
436 /* the default mapping is sufficient for 1-6 channels and 7-8 are currently unspecified anyway */
438 /* @@@ example for dolby/vorbis order, for reference later in case it becomes important */
440 options.channel_map_none ||
441 channel_mask == 0x0001 || /* 1 channel: (mono) */
442 channel_mask == 0x0003 || /* 2 channels: front left, front right */
443 channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
444 channel_mask == 0x0603 /* 4 channels: front left, front right, side left, side right */
446 /* keep default channel order */
449 channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
450 channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
451 channel_mask == 0x0607 /* 5 channels: front left, front right, front center, side left, side right */
453 /* to dolby order: front left, center, front right [, surround left, surround right ] */
458 channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
459 channel_mask == 0x060f || /* 6 channels: front left, front right, front center, LFE, side left, side right */
460 channel_mask == 0x070f || /* 7 channels: front left, front right, front center, LFE, back center, side left, side right */
461 channel_mask == 0x063f /* 8 channels: front left, front right, front center, LFE, back left, back right, side left, side right */
463 /* to dolby order: front left, center, front right, surround left, surround right, LFE */
472 options.channel_map_none ||
473 channel_mask == 0x0001 || /* 1 channel: (mono) */
474 channel_mask == 0x0003 || /* 2 channels: front left, front right */
475 channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
476 channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
477 channel_mask == 0x0603 || /* 4 channels: front left, front right, side left, side right */
478 channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
479 channel_mask == 0x0607 || /* 5 channels: front left, front right, front center, side left, side right */
480 channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
481 channel_mask == 0x060f || /* 6 channels: front left, front right, front center, LFE, side left, side right */
482 channel_mask == 0x070f || /* 7 channels: front left, front right, front center, LFE, back center, side left, side right */
483 channel_mask == 0x063f /* 8 channels: front left, front right, front center, LFE, back left, back right, side left, side right */
485 /* keep default channel order */
489 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);
492 if(!options.channel_map_none) {
493 if(count_channel_mask_bits(channel_mask) < channels) {
494 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);
498 /* supporting this is too difficult with channel mapping; e.g. what if mask is 0x003f but #channels=4?
499 * there would be holes in the order that would have to be filled in, or the mask would have to be
500 * limited and the logic above rerun to see if it still fits into the FLAC mapping.
502 else if(count_channel_mask_bits(channel_mask) > channels)
503 channel_mask = limit_channel_mask(channel_mask, channels);
505 else if(count_channel_mask_bits(channel_mask) > channels) {
506 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);
511 /* first part of GUID */
512 if(!read_uint16(e->fin, /*big_endian=*/false, &x, e->inbasefilename))
515 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE chunk with non-PCM format %u\n", e->inbasefilename, (unsigned)x);
521 e->info.bytes_per_wide_sample = channels * (bps / 8);
523 /* skip any extra data in the fmt chunk */
524 if(!fskip_ahead(e->fin, data_bytes)) {
525 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra 'fmt' data\n", e->inbasefilename);
529 got_fmt_chunk = true;
532 !memcmp(chunk_id, "data", 4) &&
533 (e->format!=FORMAT_WAVE64 || !memcmp(chunk_id, "data\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 16))
536 FLAC__uint64 data_bytes;
539 flac__utils_printf(stderr, 1, "%s: ERROR: got 'data' chunk before 'fmt' chunk\n", e->inbasefilename);
544 if(e->format != FORMAT_WAVE64) {
545 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
550 if(!read_uint64(e->fin, /*big_endian=*/false, &data_bytes, e->inbasefilename))
552 /* subtract size of header */
553 if (data_bytes < 16+8) {
554 flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 'data' chunk has length = 0x00000000%08X\n", e->inbasefilename, (unsigned)data_bytes);
557 data_bytes -= (16+8);
559 if(e->format == FORMAT_RF64) {
560 if(!got_ds64_chunk) {
561 flac__utils_printf(stderr, 1, "%s: ERROR: RF64 file has no 'ds64' chunk before 'data' chunk\n", e->inbasefilename);
564 if(data_bytes == 0xffffffff)
565 data_bytes = ds64_data_size;
567 if(options.ignore_chunk_sizes) {
568 FLAC__ASSERT(!options.sector_align);
570 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);
571 if(e->treat_warnings_as_errors)
574 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 */
576 else if(0 == data_bytes) {
577 flac__utils_printf(stderr, 1, "%s: ERROR: 'data' chunk has size of 0\n", e->inbasefilename);
581 e->fmt.iff.data_bytes = data_bytes;
583 got_data_chunk = true;
589 if(!options.format_options.iff.foreign_metadata) {
590 if(e->format != FORMAT_WAVE64)
591 flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id);
593 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",
595 (unsigned)((const unsigned char *)chunk_id)[3],
596 (unsigned)((const unsigned char *)chunk_id)[2],
597 (unsigned)((const unsigned char *)chunk_id)[1],
598 (unsigned)((const unsigned char *)chunk_id)[0],
599 (unsigned)((const unsigned char *)chunk_id)[5],
600 (unsigned)((const unsigned char *)chunk_id)[4],
601 (unsigned)((const unsigned char *)chunk_id)[7],
602 (unsigned)((const unsigned char *)chunk_id)[6],
603 (unsigned)((const unsigned char *)chunk_id)[9],
604 (unsigned)((const unsigned char *)chunk_id)[8],
605 (unsigned)((const unsigned char *)chunk_id)[10],
606 (unsigned)((const unsigned char *)chunk_id)[11],
607 (unsigned)((const unsigned char *)chunk_id)[12],
608 (unsigned)((const unsigned char *)chunk_id)[13],
609 (unsigned)((const unsigned char *)chunk_id)[14],
610 (unsigned)((const unsigned char *)chunk_id)[15]
612 if(e->treat_warnings_as_errors)
617 if(e->format != FORMAT_WAVE64) {
618 if(!read_uint32(e->fin, /*big_endian=*/false, &xx, e->inbasefilename))
624 if(!read_uint64(e->fin, /*big_endian=*/false, &skip, e->inbasefilename))
626 skip = (skip+7) & (~(FLAC__uint64)7);
627 /* subtract size of header */
629 flac__utils_printf(stderr, 1, "%s: ERROR: freakishly small Wave64 chunk has length = 0x00000000%08X\n", e->inbasefilename, (unsigned)skip);
635 if(!fskip_ahead(e->fin, skip)) {
636 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename);
644 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find fmt chunk\n", e->inbasefilename);
647 if(!got_data_chunk) {
648 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find data chunk\n", e->inbasefilename);
652 e->info.sample_rate = sample_rate;
653 e->info.channels = channels;
654 e->info.bits_per_sample = bps;
655 e->info.shift = shift;
656 e->info.channel_mask = channel_mask;
661 static FLAC__bool get_sample_info_aiff(EncoderSession *e, encode_options_t options)
663 FLAC__bool got_comm_chunk = false, got_ssnd_chunk = false;
664 unsigned sample_rate = 0, channels = 0, bps = 0, shift = 0;
665 FLAC__uint64 sample_frames = 0;
666 FLAC__uint32 channel_mask = 0;
668 e->info.is_unsigned_samples = false;
669 e->info.is_big_endian = true;
672 * lookahead[] already has "FORMxxxxAIFF", do chunks
674 while(!feof(e->fin) && !got_ssnd_chunk) {
675 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 */
676 if(!read_bytes(e->fin, (FLAC__byte*)chunk_id, 4, /*eof_ok=*/true, e->inbasefilename)) {
677 flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", e->inbasefilename);
683 if(!memcmp(chunk_id, "COMM", 4)) { /* common chunk */
687 const FLAC__bool is_aifc = e->format == FORMAT_AIFF_C;
688 const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18);
691 flac__utils_printf(stderr, 1, "%s: ERROR: file has multiple 'COMM' chunks\n", e->inbasefilename);
695 /* COMM chunk size */
696 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
698 else if(xx < minimum_comm_size) {
699 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);
702 else if(!is_aifc && xx != minimum_comm_size) {
703 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);
704 if(e->treat_warnings_as_errors)
707 skip = (xx-minimum_comm_size)+(xx & 1);
709 /* number of channels */
710 if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
712 channels = (unsigned)x;
713 if(channels > 2 && !options.channel_map_none) {
714 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
718 /* number of sample frames */
719 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
723 /* bits per sample */
724 if(!read_uint16(e->fin, /*big_endian=*/true, &x, e->inbasefilename))
727 shift = (bps%8)? 8-(bps%8) : 0; /* SSND data is always byte-aligned, left-justified but format_input() will double-check */
731 if(!read_sane_extended(e->fin, &xx, e->inbasefilename))
735 /* check compression type for AIFF-C */
737 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
739 if(xx == 0x736F7774) /* "sowt" */
740 e->info.is_big_endian = false;
741 else if(xx == 0x4E4F4E45) /* "NONE" */
742 ; /* nothing to do, we already default to big-endian */
744 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));
749 /* set channel mapping */
750 /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
751 /* front left, front right, center, LFE, back left, back right, surround left, surround right */
752 /* specs say the channel ordering is:
754 * ___________________________________________________
758 * quad (ambiguous with 4ch) Fl Fr Bl Br
761 * 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
762 * so we only have unambiguous mappings for 2, 3, and 5 channels
765 options.channel_map_none ||
766 channels == 1 || /* 1 channel: (mono) */
767 channels == 2 || /* 2 channels: left, right */
768 channels == 3 || /* 3 channels: left, right, center */
769 channels == 5 /* 5 channels: front left, front right, center, surround left, surround right */
771 /* keep default channel order */
774 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u for AIFF\n", e->inbasefilename, channels);
778 e->info.bytes_per_wide_sample = channels * (bps / 8);
780 /* skip any extra data in the COMM chunk */
781 if(!fskip_ahead(e->fin, skip)) {
782 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over extra COMM data\n", e->inbasefilename);
786 got_comm_chunk = true;
788 else if(!memcmp(chunk_id, "SSND", 4) && !got_ssnd_chunk) { /* sound data chunk */
790 FLAC__uint64 data_bytes;
793 if(!got_comm_chunk) {
794 flac__utils_printf(stderr, 1, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", e->inbasefilename);
798 /* SSND chunk size */
799 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
802 if(options.ignore_chunk_sizes) {
803 FLAC__ASSERT(!options.sector_align);
805 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);
806 if(e->treat_warnings_as_errors)
809 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 */
811 else if(data_bytes <= 8) {
812 flac__utils_printf(stderr, 1, "%s: ERROR: 'SSND' chunk has size <= 8\n", e->inbasefilename);
816 data_bytes -= 8; /* discount the offset and block size fields */
820 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
823 data_bytes -= offset;
826 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
828 if(xx && !options.ignore_chunk_sizes)
829 data_bytes -= (xx - (data_bytes % xx));
830 if(options.ignore_chunk_sizes) {
832 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);
833 if(e->treat_warnings_as_errors)
838 /* skip any SSND offset bytes */
839 if(!fskip_ahead(e->fin, offset)) {
840 flac__utils_printf(stderr, 1, "%s: ERROR: skipping offset in SSND chunk\n", e->inbasefilename);
844 e->fmt.iff.data_bytes = data_bytes;
846 got_ssnd_chunk = true;
850 if(!options.format_options.iff.foreign_metadata) {
851 flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s' (use --keep-foreign-metadata to keep)\n", e->inbasefilename, chunk_id);
852 if(e->treat_warnings_as_errors)
857 if(!read_uint32(e->fin, /*big_endian=*/true, &xx, e->inbasefilename))
860 unsigned long skip = xx + (xx & 1);
862 FLAC__ASSERT(skip <= LONG_MAX);
863 if(!fskip_ahead(e->fin, skip)) {
864 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping over chunk\n", e->inbasefilename);
871 if(!got_comm_chunk) {
872 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find COMM chunk\n", e->inbasefilename);
875 if(!got_ssnd_chunk && sample_frames) {
876 flac__utils_printf(stderr, 1, "%s: ERROR: didn't find SSND chunk\n", e->inbasefilename);
880 e->info.sample_rate = sample_rate;
881 e->info.channels = channels;
882 e->info.bits_per_sample = bps;
883 e->info.shift = shift;
884 e->info.channel_mask = channel_mask;
889 static FLAC__bool get_sample_info_flac(EncoderSession *e)
892 FLAC__stream_decoder_set_md5_checking(e->fmt.flac.decoder, false) &&
893 FLAC__stream_decoder_set_metadata_respond_all(e->fmt.flac.decoder)
895 flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", e->inbasefilename);
899 if (e->format == FORMAT_OGGFLAC) {
900 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) {
901 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));
905 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) {
906 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));
910 if (!FLAC__stream_decoder_process_until_end_of_metadata(e->fmt.flac.decoder) || e->fmt.flac.client_data.fatal_error) {
911 if (e->fmt.flac.client_data.fatal_error)
912 flac__utils_printf(stderr, 1, "%s: ERROR: out of memory or too many metadata blocks while reading metadata in FLAC input\n", e->inbasefilename);
914 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));
918 if (e->fmt.flac.client_data.num_metadata_blocks == 0) {
919 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, got no metadata blocks\n", e->inbasefilename);
922 else if (e->fmt.flac.client_data.metadata_blocks[0]->type != FLAC__METADATA_TYPE_STREAMINFO) {
923 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, first metadata block is not STREAMINFO\n", e->inbasefilename);
926 else if (e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples == 0) {
927 flac__utils_printf(stderr, 1, "%s: ERROR: FLAC input has STREAMINFO with unknown total samples which is not supported\n", e->inbasefilename);
931 e->info.sample_rate = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.sample_rate;
932 e->info.channels = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.channels;
933 e->info.bits_per_sample = e->fmt.flac.client_data.metadata_blocks[0]->data.stream_info.bits_per_sample;
935 e->info.bytes_per_wide_sample = 0;
936 e->info.is_unsigned_samples = false; /* not applicable for FLAC input */
937 e->info.is_big_endian = false; /* not applicable for FLAC input */
938 e->info.channel_mask = 0;
946 int flac__encode_file(FILE *infile, FLAC__off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, encode_options_t options)
948 EncoderSession encoder_session;
949 size_t channel_map[FLAC__MAX_CHANNELS];
950 int info_align_carry = -1, info_align_zero = -1;
952 if(!EncoderSession_construct(&encoder_session, options, infilesize, infile, infilename, outfilename, lookahead, lookahead_length))
955 /* initialize default channel map that preserves channel order */
958 for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++)
962 /* read foreign metadata if requested */
963 if(EncoderSession_format_is_iff(&encoder_session) && options.format_options.iff.foreign_metadata) {
966 options.format == FORMAT_WAVE || options.format == FORMAT_RF64?
967 flac__foreign_metadata_read_from_wave(options.format_options.iff.foreign_metadata, infilename, &error) :
968 options.format == FORMAT_WAVE64?
969 flac__foreign_metadata_read_from_wave64(options.format_options.iff.foreign_metadata, infilename, &error) :
970 flac__foreign_metadata_read_from_aiff(options.format_options.iff.foreign_metadata, infilename, &error)
972 flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", encoder_session.inbasefilename, error);
973 return EncoderSession_finish_error(&encoder_session);
977 /* initialize encoder session with info about the audio (channels/bps/resolution/endianness/etc) */
978 switch(options.format) {
980 if(!get_sample_info_raw(&encoder_session, options))
981 return EncoderSession_finish_error(&encoder_session);
986 if(!get_sample_info_wave(&encoder_session, options))
987 return EncoderSession_finish_error(&encoder_session);
991 if(!get_sample_info_aiff(&encoder_session, options))
992 return EncoderSession_finish_error(&encoder_session);
997 * set up FLAC decoder for the input
999 if (0 == (encoder_session.fmt.flac.decoder = FLAC__stream_decoder_new())) {
1000 flac__utils_printf(stderr, 1, "%s: ERROR: creating decoder for FLAC input\n", encoder_session.inbasefilename);
1001 return EncoderSession_finish_error(&encoder_session);
1003 if(!get_sample_info_flac(&encoder_session))
1004 return EncoderSession_finish_error(&encoder_session);
1008 /* double protection */
1009 return EncoderSession_finish_error(&encoder_session);
1012 /* some more checks */
1013 if(encoder_session.info.channels == 0 || encoder_session.info.channels > FLAC__MAX_CHANNELS) {
1014 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u\n", encoder_session.inbasefilename, encoder_session.info.channels);
1015 return EncoderSession_finish_error(&encoder_session);
1017 if(!FLAC__format_sample_rate_is_valid(encoder_session.info.sample_rate)) {
1018 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, encoder_session.info.sample_rate);
1019 return EncoderSession_finish_error(&encoder_session);
1021 if(encoder_session.info.bits_per_sample-encoder_session.info.shift < 4 || encoder_session.info.bits_per_sample-encoder_session.info.shift > 24) {
1022 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);
1023 return EncoderSession_finish_error(&encoder_session);
1025 if(options.sector_align) {
1026 if(encoder_session.info.channels != 2) {
1027 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);
1028 return EncoderSession_finish_error(&encoder_session);
1030 if(encoder_session.info.sample_rate != 44100) {
1031 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);
1032 return EncoderSession_finish_error(&encoder_session);
1034 if(encoder_session.info.bits_per_sample-encoder_session.info.shift != 16) {
1035 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);
1036 return EncoderSession_finish_error(&encoder_session);
1041 FLAC__uint64 total_samples_in_input; /* WATCHOUT: may be 0 to mean "unknown" */
1043 FLAC__uint64 until; /* a value of 0 mean end-of-stream (i.e. --until=-0) */
1044 unsigned align_remainder = 0;
1046 switch(options.format) {
1049 total_samples_in_input = 0;
1051 total_samples_in_input = (FLAC__uint64)infilesize / encoder_session.info.bytes_per_wide_sample + *options.align_reservoir_samples;
1058 /* truncation in the division removes any padding byte that was counted in encoder_session.fmt.iff.data_bytes */
1059 total_samples_in_input = encoder_session.fmt.iff.data_bytes / encoder_session.info.bytes_per_wide_sample + *options.align_reservoir_samples;
1062 case FORMAT_OGGFLAC:
1063 total_samples_in_input = encoder_session.fmt.flac.client_data.metadata_blocks[0]->data.stream_info.total_samples + *options.align_reservoir_samples;
1067 /* double protection */
1068 return EncoderSession_finish_error(&encoder_session);
1072 * now that we know the sample rate, canonicalize the
1073 * --skip string to an absolute sample number:
1075 flac__utils_canonicalize_skip_until_specification(&options.skip_specification, encoder_session.info.sample_rate);
1076 FLAC__ASSERT(options.skip_specification.value.samples >= 0);
1077 skip = (FLAC__uint64)options.skip_specification.value.samples;
1078 FLAC__ASSERT(!options.sector_align || (options.format != FORMAT_FLAC && options.format != FORMAT_OGGFLAC && skip == 0));
1079 /* *options.align_reservoir_samples will be 0 unless --sector-align is used */
1080 FLAC__ASSERT(options.sector_align || *options.align_reservoir_samples == 0);
1083 * now that we possibly know the input size, canonicalize the
1084 * --until string to an absolute sample number:
1086 if(!canonicalize_until_specification(&options.until_specification, encoder_session.inbasefilename, encoder_session.info.sample_rate, skip, total_samples_in_input))
1087 return EncoderSession_finish_error(&encoder_session);
1088 until = (FLAC__uint64)options.until_specification.value.samples;
1089 FLAC__ASSERT(!options.sector_align || until == 0);
1091 /* adjust encoding parameters based on skip and until values */
1092 switch(options.format) {
1094 infilesize -= (FLAC__off_t)skip * encoder_session.info.bytes_per_wide_sample;
1095 encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1102 encoder_session.fmt.iff.data_bytes -= skip * encoder_session.info.bytes_per_wide_sample;
1103 if(options.ignore_chunk_sizes) {
1104 encoder_session.total_samples_to_encode = 0;
1105 flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n");
1106 FLAC__ASSERT(0 == until);
1109 encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1113 case FORMAT_OGGFLAC:
1114 encoder_session.total_samples_to_encode = total_samples_in_input - skip;
1118 /* double protection */
1119 return EncoderSession_finish_error(&encoder_session);
1122 const FLAC__uint64 trim = total_samples_in_input - until;
1123 FLAC__ASSERT(total_samples_in_input > 0);
1124 FLAC__ASSERT(!options.sector_align);
1125 if(options.format == FORMAT_RAW)
1126 infilesize -= (FLAC__off_t)trim * encoder_session.info.bytes_per_wide_sample;
1127 else if(EncoderSession_format_is_iff(&encoder_session))
1128 encoder_session.fmt.iff.data_bytes -= trim * encoder_session.info.bytes_per_wide_sample;
1129 encoder_session.total_samples_to_encode -= trim;
1131 if(options.sector_align && (options.format != FORMAT_RAW || infilesize >=0)) { /* for RAW, need to know the filesize */
1132 FLAC__ASSERT(skip == 0); /* asserted above too, but lest we forget */
1133 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
1134 if(options.is_last_file)
1135 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
1137 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
1139 switch(options.format) {
1141 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample;
1144 /* +44 for the size of the WAVE headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1145 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 44;
1148 /* +44 for the size of the WAVE headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1149 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 104;
1152 /* +72 for the size of the RF64 headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1153 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 80;
1157 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
1158 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * encoder_session.info.bytes_per_wide_sample + 54;
1161 case FORMAT_OGGFLAC:
1163 /* if we don't know, use 0 as hint to progress indicator (which is the only place this is used): */
1164 encoder_session.unencoded_size = 0;
1165 else if(skip == 0 && until == 0)
1166 encoder_session.unencoded_size = (FLAC__uint64)infilesize;
1167 else if(total_samples_in_input)
1168 encoder_session.unencoded_size = (FLAC__uint64)infilesize * encoder_session.total_samples_to_encode / total_samples_in_input;
1170 encoder_session.unencoded_size = (FLAC__uint64)infilesize;
1174 /* double protection */
1175 return EncoderSession_finish_error(&encoder_session);
1178 if(encoder_session.total_samples_to_encode == 0)
1179 flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n");
1181 if(options.format == FORMAT_FLAC || options.format == FORMAT_OGGFLAC)
1182 encoder_session.fmt.flac.client_data.samples_left_to_process = encoder_session.total_samples_to_encode;
1185 /* init the encoder */
1186 if(!EncoderSession_init_encoder(&encoder_session, options))
1187 return EncoderSession_finish_error(&encoder_session);
1189 /* skip over any samples as requested */
1191 switch(options.format) {
1194 unsigned skip_bytes = encoder_session.info.bytes_per_wide_sample * (unsigned)skip;
1195 if(skip_bytes > lookahead_length) {
1196 skip_bytes -= lookahead_length;
1197 lookahead_length = 0;
1198 if(!fskip_ahead(encoder_session.fin, skip_bytes)) {
1199 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1200 return EncoderSession_finish_error(&encoder_session);
1204 lookahead += skip_bytes;
1205 lookahead_length -= skip_bytes;
1214 if(!fskip_ahead(encoder_session.fin, skip * encoder_session.info.bytes_per_wide_sample)) {
1215 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1216 return EncoderSession_finish_error(&encoder_session);
1220 case FORMAT_OGGFLAC:
1222 * have to wait until the FLAC encoder is set up for writing
1223 * before any seeking in the input FLAC file, because the seek
1224 * itself will usually call the decoder's write callback, and
1225 * our decoder's write callback passes samples to our FLAC
1228 if(!FLAC__stream_decoder_seek_absolute(encoder_session.fmt.flac.decoder, skip)) {
1229 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));
1230 return EncoderSession_finish_error(&encoder_session);
1235 /* double protection */
1236 return EncoderSession_finish_error(&encoder_session);
1241 * first do any samples in the reservoir
1243 if(options.sector_align && *options.align_reservoir_samples > 0) {
1244 FLAC__ASSERT(options.format != FORMAT_FLAC && options.format != FORMAT_OGGFLAC); /* check again */
1245 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.align_reservoir, *options.align_reservoir_samples)) {
1246 print_error_with_state(&encoder_session, "ERROR during encoding");
1247 return EncoderSession_finish_error(&encoder_session);
1252 * decrement infilesize or the data_bytes counter if we need to align the file
1254 if(options.sector_align) {
1255 if(options.is_last_file) {
1256 *options.align_reservoir_samples = 0;
1259 *options.align_reservoir_samples = align_remainder;
1260 if(options.format == FORMAT_RAW) {
1261 FLAC__ASSERT(infilesize >= 0);
1262 infilesize -= (FLAC__off_t)((*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample);
1263 FLAC__ASSERT(infilesize >= 0);
1265 else if(EncoderSession_format_is_iff(&encoder_session))
1266 encoder_session.fmt.iff.data_bytes -= (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample;
1271 * now do samples from the file
1273 switch(options.format) {
1275 if(infilesize < 0) {
1277 while(!feof(infile)) {
1278 if(lookahead_length > 0) {
1279 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample);
1280 memcpy(ucbuffer_, lookahead, lookahead_length);
1281 bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
1282 if(ferror(infile)) {
1283 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1284 return EncoderSession_finish_error(&encoder_session);
1286 lookahead_length = 0;
1289 bytes_read = fread(ucbuffer_, sizeof(unsigned char), CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample, infile);
1291 if(bytes_read == 0) {
1292 if(ferror(infile)) {
1293 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1294 return EncoderSession_finish_error(&encoder_session);
1297 else if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1298 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1299 return EncoderSession_finish_error(&encoder_session);
1302 unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1303 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))
1304 return EncoderSession_finish_error(&encoder_session);
1306 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1307 print_error_with_state(&encoder_session, "ERROR during encoding");
1308 return EncoderSession_finish_error(&encoder_session);
1315 const FLAC__uint64 max_input_bytes = infilesize;
1316 FLAC__uint64 total_input_bytes_read = 0;
1317 while(total_input_bytes_read < max_input_bytes) {
1319 size_t wanted = (CHUNK_OF_SAMPLES * encoder_session.info.bytes_per_wide_sample);
1320 wanted = (size_t) min((FLAC__uint64)wanted, max_input_bytes - total_input_bytes_read);
1322 if(lookahead_length > 0) {
1323 FLAC__ASSERT(lookahead_length <= wanted);
1324 memcpy(ucbuffer_, lookahead, lookahead_length);
1325 wanted -= lookahead_length;
1326 bytes_read = lookahead_length;
1328 bytes_read += fread(ucbuffer_+lookahead_length, sizeof(unsigned char), wanted, infile);
1329 if(ferror(infile)) {
1330 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1331 return EncoderSession_finish_error(&encoder_session);
1334 lookahead_length = 0;
1337 bytes_read = fread(ucbuffer_, sizeof(unsigned char), wanted, infile);
1340 if(bytes_read == 0) {
1341 if(ferror(infile)) {
1342 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1343 return EncoderSession_finish_error(&encoder_session);
1345 else if(feof(infile)) {
1346 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %" PRIu64 " samples, got %" PRIu64 " samples\n", encoder_session.inbasefilename, encoder_session.total_samples_to_encode, encoder_session.samples_written);
1347 if(encoder_session.treat_warnings_as_errors)
1348 return EncoderSession_finish_error(&encoder_session);
1349 total_input_bytes_read = max_input_bytes;
1353 if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1354 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1355 return EncoderSession_finish_error(&encoder_session);
1358 unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1359 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))
1360 return EncoderSession_finish_error(&encoder_session);
1362 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1363 print_error_with_state(&encoder_session, "ERROR during encoding");
1364 return EncoderSession_finish_error(&encoder_session);
1366 total_input_bytes_read += bytes_read;
1377 while(encoder_session.fmt.iff.data_bytes > 0) {
1378 const size_t bytes_to_read = (size_t)min(
1379 encoder_session.fmt.iff.data_bytes,
1380 (FLAC__uint64)CHUNK_OF_SAMPLES * (FLAC__uint64)encoder_session.info.bytes_per_wide_sample
1382 size_t bytes_read = fread(ucbuffer_, sizeof(unsigned char), bytes_to_read, infile);
1383 if(bytes_read == 0) {
1384 if(ferror(infile)) {
1385 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1386 return EncoderSession_finish_error(&encoder_session);
1388 else if(feof(infile)) {
1389 if(options.ignore_chunk_sizes) {
1390 flac__utils_printf(stderr, 1, "%s: INFO: hit EOF with --ignore-chunk-sizes, got %" PRIu64 " samples\n", encoder_session.inbasefilename, encoder_session.samples_written);
1393 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %" PRIu64 " samples, got %" PRIu64 " samples\n", encoder_session.inbasefilename, encoder_session.total_samples_to_encode, encoder_session.samples_written);
1394 if(encoder_session.treat_warnings_as_errors)
1395 return EncoderSession_finish_error(&encoder_session);
1397 encoder_session.fmt.iff.data_bytes = 0;
1401 if(bytes_read % encoder_session.info.bytes_per_wide_sample != 0) {
1402 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1403 return EncoderSession_finish_error(&encoder_session);
1406 unsigned wide_samples = bytes_read / encoder_session.info.bytes_per_wide_sample;
1407 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))
1408 return EncoderSession_finish_error(&encoder_session);
1410 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1411 print_error_with_state(&encoder_session, "ERROR during encoding");
1412 return EncoderSession_finish_error(&encoder_session);
1414 encoder_session.fmt.iff.data_bytes -= bytes_read;
1420 case FORMAT_OGGFLAC:
1421 while(!encoder_session.fmt.flac.client_data.fatal_error && encoder_session.fmt.flac.client_data.samples_left_to_process > 0) {
1422 /* We can also hit the end of stream without samples_left_to_process
1423 * going to 0 if there are errors and continue_through_decode_errors
1424 * is on, so we want to break in that case too:
1426 if(encoder_session.continue_through_decode_errors && FLAC__stream_decoder_get_state(encoder_session.fmt.flac.decoder) == FLAC__STREAM_DECODER_END_OF_STREAM)
1428 if(!FLAC__stream_decoder_process_single(encoder_session.fmt.flac.decoder)) {
1429 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));
1430 return EncoderSession_finish_error(&encoder_session);
1433 if(encoder_session.fmt.flac.client_data.fatal_error) {
1434 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));
1435 return EncoderSession_finish_error(&encoder_session);
1440 /* double protection */
1441 return EncoderSession_finish_error(&encoder_session);
1445 * now read unaligned samples into reservoir or pad with zeroes if necessary
1447 if(options.sector_align) {
1448 if(options.is_last_file) {
1449 unsigned wide_samples = 588 - align_remainder;
1450 if(wide_samples < 588) {
1453 info_align_zero = wide_samples;
1454 for(channel = 0; channel < encoder_session.info.channels; channel++)
1455 memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
1457 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1458 print_error_with_state(&encoder_session, "ERROR during encoding");
1459 return EncoderSession_finish_error(&encoder_session);
1464 if(*options.align_reservoir_samples > 0) {
1466 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1467 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample, infile);
1468 if(bytes_read == 0 && ferror(infile)) {
1469 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1470 return EncoderSession_finish_error(&encoder_session);
1472 else if(bytes_read != (*options.align_reservoir_samples) * encoder_session.info.bytes_per_wide_sample) {
1473 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %" PRIu64 " bytes; expected %" PRIu64 " samples, got %" PRIu64 " samples\n", encoder_session.inbasefilename, bytes_read, encoder_session.total_samples_to_encode, encoder_session.samples_written);
1474 if(encoder_session.treat_warnings_as_errors)
1475 return EncoderSession_finish_error(&encoder_session);
1478 info_align_carry = *options.align_reservoir_samples;
1479 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))
1480 return EncoderSession_finish_error(&encoder_session);
1487 return EncoderSession_finish_ok(
1491 EncoderSession_format_is_iff(&encoder_session)? options.format_options.iff.foreign_metadata : 0
1495 FLAC__bool EncoderSession_construct(EncoderSession *e, encode_options_t options, FLAC__off_t infilesize, FILE *infile, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length)
1498 FLAC__uint32 test = 1;
1501 * initialize globals
1504 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
1506 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1507 input_[i] = &(in_[i][0]);
1511 * initialize instance
1515 e->use_ogg = options.use_ogg;
1517 e->verify = options.verify;
1518 e->treat_warnings_as_errors = options.treat_warnings_as_errors;
1519 e->continue_through_decode_errors = options.continue_through_decode_errors;
1521 e->is_stdout = (0 == strcmp(outfilename, "-"));
1522 e->outputfile_opened = false;
1524 e->inbasefilename = grabbag__file_get_basename(infilename);
1525 e->infilename = infilename;
1526 e->outfilename = outfilename;
1528 e->total_samples_to_encode = 0;
1529 e->unencoded_size = 0;
1530 e->bytes_written = 0;
1531 e->samples_written = 0;
1534 memset(&e->info, 0, sizeof(e->info));
1536 e->format = options.format;
1538 switch(options.format) {
1546 e->fmt.iff.data_bytes = 0;
1549 case FORMAT_OGGFLAC:
1550 e->fmt.flac.decoder = 0;
1551 e->fmt.flac.client_data.filesize = infilesize;
1552 e->fmt.flac.client_data.lookahead = lookahead;
1553 e->fmt.flac.client_data.lookahead_length = lookahead_length;
1554 e->fmt.flac.client_data.num_metadata_blocks = 0;
1555 e->fmt.flac.client_data.samples_left_to_process = 0;
1556 e->fmt.flac.client_data.fatal_error = false;
1560 /* double protection */
1567 e->seek_table_template = 0;
1569 if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1570 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1574 e->encoder = FLAC__stream_encoder_new();
1575 if(0 == e->encoder) {
1576 flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1577 EncoderSession_destroy(e);
1584 void EncoderSession_destroy(EncoderSession *e)
1586 if(e->format == FORMAT_FLAC || e->format == FORMAT_OGGFLAC) {
1588 if(e->fmt.flac.decoder)
1589 FLAC__stream_decoder_delete(e->fmt.flac.decoder);
1590 e->fmt.flac.decoder = 0;
1591 for(i = 0; i < e->fmt.flac.client_data.num_metadata_blocks; i++)
1592 FLAC__metadata_object_delete(e->fmt.flac.client_data.metadata_blocks[i]);
1593 e->fmt.flac.client_data.num_metadata_blocks = 0;
1599 if(0 != e->encoder) {
1600 FLAC__stream_encoder_delete(e->encoder);
1604 if(0 != e->seek_table_template) {
1605 FLAC__metadata_object_delete(e->seek_table_template);
1606 e->seek_table_template = 0;
1610 int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero, foreign_metadata_t *foreign_metadata)
1612 FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1614 FLAC__bool verify_error = false;
1617 fse_state = FLAC__stream_encoder_get_state(e->encoder);
1618 ret = FLAC__stream_encoder_finish(e->encoder)? 0 : 1;
1620 fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA ||
1621 FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA
1624 /* all errors except verify errors should interrupt the stats */
1625 if(ret && !verify_error)
1626 print_error_with_state(e, "ERROR during encoding");
1627 else if(e->total_samples_to_encode > 0) {
1629 flac__utils_printf(stderr, 2, "\n");
1633 print_verify_error(e);
1637 if(info_align_carry >= 0) {
1638 flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d samples to be carried over\n", e->inbasefilename, info_align_carry);
1640 if(info_align_zero >= 0) {
1641 flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d zero samples to be appended\n", e->inbasefilename, info_align_zero);
1645 /*@@@@@@ should this go here or somewhere else? */
1646 if(ret == 0 && foreign_metadata) {
1648 if(!flac__foreign_metadata_write_to_flac(foreign_metadata, e->infilename, e->outfilename, &error)) {
1649 flac__utils_printf(stderr, 1, "%s: ERROR: updating foreign metadata in FLAC file: %s\n", e->inbasefilename, error);
1654 EncoderSession_destroy(e);
1659 int EncoderSession_finish_error(EncoderSession *e)
1661 FLAC__ASSERT(e->encoder);
1663 if(e->total_samples_to_encode > 0)
1664 flac__utils_printf(stderr, 2, "\n");
1666 if(FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1667 print_verify_error(e);
1668 else if(e->outputfile_opened)
1669 /* only want to delete the file if we opened it; otherwise it could be an existing file and our overwrite failed */
1670 flac_unlink(e->outfilename);
1672 EncoderSession_destroy(e);
1678 unsigned num_metadata;
1679 FLAC__bool *needs_delete;
1680 FLAC__StreamMetadata **metadata;
1681 FLAC__StreamMetadata *cuesheet; /* always needs to be deleted */
1682 } static_metadata_t;
1684 static void static_metadata_init(static_metadata_t *m)
1686 m->num_metadata = 0;
1687 m->needs_delete = 0;
1692 static void static_metadata_clear(static_metadata_t *m)
1695 for(i = 0; i < m->num_metadata; i++)
1696 if(m->needs_delete[i])
1697 FLAC__metadata_object_delete(m->metadata[i]);
1701 free(m->needs_delete);
1703 FLAC__metadata_object_delete(m->cuesheet);
1704 static_metadata_init(m);
1707 static FLAC__bool static_metadata_append(static_metadata_t *m, FLAC__StreamMetadata *d, FLAC__bool needs_delete)
1710 if(0 == (x = safe_realloc_muladd2_(m->metadata, sizeof(*m->metadata), /*times (*/m->num_metadata, /*+*/1/*)*/)))
1712 m->metadata = (FLAC__StreamMetadata**)x;
1713 if(0 == (x = safe_realloc_muladd2_(m->needs_delete, sizeof(*m->needs_delete), /*times (*/m->num_metadata, /*+*/1/*)*/)))
1715 m->needs_delete = (FLAC__bool*)x;
1716 m->metadata[m->num_metadata] = d;
1717 m->needs_delete[m->num_metadata] = needs_delete;
1722 FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options)
1724 const unsigned channels = e->info.channels;
1725 const unsigned bps = e->info.bits_per_sample - e->info.shift;
1726 const unsigned sample_rate = e->info.sample_rate;
1727 FLACDecoderData *flac_decoder_data = (e->format == FORMAT_FLAC || e->format == FORMAT_OGGFLAC)? &e->fmt.flac.client_data : 0;
1728 FLAC__StreamMetadata padding;
1729 FLAC__StreamMetadata **metadata = 0;
1730 static_metadata_t static_metadata;
1731 unsigned num_metadata = 0, ic;
1732 FLAC__StreamEncoderInitStatus init_status;
1733 const FLAC__bool is_cdda = (channels == 1 || channels == 2) && (bps == 16) && (sample_rate == 44100);
1734 char apodizations[2000];
1736 FLAC__ASSERT(sizeof(options.pictures)/sizeof(options.pictures[0]) <= 64);
1738 static_metadata_init(&static_metadata);
1740 e->replay_gain = options.replay_gain;
1742 apodizations[0] = '\0';
1744 if(e->replay_gain) {
1745 if(channels != 1 && channels != 2) {
1746 flac__utils_printf(stderr, 1, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
1749 if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) {
1750 flac__utils_printf(stderr, 1, "%s: ERROR, invalid sample rate (%u) for --replay-gain\n", e->inbasefilename, sample_rate);
1753 if(options.is_first_file) {
1754 if(!grabbag__replaygain_init(sample_rate)) {
1755 flac__utils_printf(stderr, 1, "%s: ERROR initializing ReplayGain stage\n", e->inbasefilename);
1761 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))
1764 if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? static_metadata.cuesheet : 0, e)) {
1765 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1766 static_metadata_clear(&static_metadata);
1770 /* build metadata */
1771 if(flac_decoder_data) {
1773 * we're encoding from FLAC so we will use the FLAC file's
1774 * metadata as the basis for the encoded file
1779 * first handle pictures: simple append any --pictures
1782 for(i = 0; i < options.num_pictures; i++) {
1783 FLAC__StreamMetadata *pic = FLAC__metadata_object_clone(options.pictures[i]);
1785 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PICTURE block\n", e->inbasefilename);
1786 static_metadata_clear(&static_metadata);
1789 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks++] = pic;
1794 * next handle vorbis comment: if any tags were specified
1795 * or there is no existing vorbis comment, we create a
1796 * new vorbis comment (discarding any existing one); else
1797 * we keep the existing one. also need to make sure to
1798 * propagate any channel mask tag.
1800 /* @@@ change to append -T values from options.vorbis_comment if input has VC already? */
1802 FLAC__bool vc_found = false;
1803 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1804 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
1806 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT && options.vorbis_comment->data.vorbis_comment.num_comments > 0) {
1807 (void) flac__utils_get_channel_mask_tag(flac_decoder_data->metadata_blocks[i], &e->info.channel_mask);
1808 flac__utils_printf(stderr, 1, "%s: WARNING, replacing tags from input FLAC file with those given on the command-line\n", e->inbasefilename);
1809 if(e->treat_warnings_as_errors) {
1810 static_metadata_clear(&static_metadata);
1813 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1814 flac_decoder_data->metadata_blocks[i] = 0;
1817 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1819 flac_decoder_data->num_metadata_blocks = j;
1820 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])) {
1822 FLAC__StreamMetadata *vc = FLAC__metadata_object_clone(options.vorbis_comment);
1823 if(0 == vc || (e->info.channel_mask && !flac__utils_set_channel_mask_tag(vc, e->info.channel_mask))) {
1824 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for VORBIS_COMMENT block\n", e->inbasefilename);
1825 static_metadata_clear(&static_metadata);
1828 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1829 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1830 flac_decoder_data->metadata_blocks[1] = vc;
1831 flac_decoder_data->num_metadata_blocks++;
1836 * next handle cuesheet: if --cuesheet was specified, use
1837 * it; else if file has existing CUESHEET and cuesheet's
1838 * lead-out offset is correct, keep it; else no CUESHEET
1841 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1842 FLAC__bool existing_cuesheet_is_bad = false;
1843 /* check if existing cuesheet matches the input audio */
1844 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && 0 == static_metadata.cuesheet) {
1845 const FLAC__StreamMetadata_CueSheet *cs = &flac_decoder_data->metadata_blocks[i]->data.cue_sheet;
1846 if(e->total_samples_to_encode == 0) {
1847 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);
1848 if(e->treat_warnings_as_errors) {
1849 static_metadata_clear(&static_metadata);
1852 existing_cuesheet_is_bad = true;
1854 else if(e->total_samples_to_encode != cs->tracks[cs->num_tracks-1].offset) {
1855 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);
1856 if(e->treat_warnings_as_errors) {
1857 static_metadata_clear(&static_metadata);
1860 existing_cuesheet_is_bad = true;
1863 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && (existing_cuesheet_is_bad || 0 != static_metadata.cuesheet)) {
1864 if(0 != static_metadata.cuesheet) {
1865 flac__utils_printf(stderr, 1, "%s: WARNING, replacing cuesheet in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1866 if(e->treat_warnings_as_errors) {
1867 static_metadata_clear(&static_metadata);
1871 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1872 flac_decoder_data->metadata_blocks[i] = 0;
1875 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1877 flac_decoder_data->num_metadata_blocks = j;
1878 if(0 != static_metadata.cuesheet && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1880 FLAC__StreamMetadata *cs = FLAC__metadata_object_clone(static_metadata.cuesheet);
1882 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for CUESHEET block\n", e->inbasefilename);
1883 static_metadata_clear(&static_metadata);
1886 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1887 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1888 flac_decoder_data->metadata_blocks[1] = cs;
1889 flac_decoder_data->num_metadata_blocks++;
1894 * next handle seektable: if -S- was specified, no
1895 * SEEKTABLE; else if -S was specified, use it/them;
1896 * else if file has existing SEEKTABLE and input size is
1897 * preserved (no --skip/--until/etc specified), keep it;
1898 * else use default seektable options
1900 * note: meanings of num_requested_seek_points:
1901 * -1 : no -S option given, default to some value
1902 * 0 : -S- given (no seektable)
1903 * >0 : one or more -S options given
1906 FLAC__bool existing_seektable = false;
1907 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1908 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE)
1909 existing_seektable = true;
1910 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)) {
1911 if(options.num_requested_seek_points > 0) {
1912 flac__utils_printf(stderr, 1, "%s: WARNING, replacing seektable in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1913 if(e->treat_warnings_as_errors) {
1914 static_metadata_clear(&static_metadata);
1918 else if(options.num_requested_seek_points == 0)
1919 ; /* no warning, silently delete existing SEEKTABLE since user specified --no-seektable (-S-) */
1921 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);
1922 if(e->treat_warnings_as_errors) {
1923 static_metadata_clear(&static_metadata);
1927 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1928 flac_decoder_data->metadata_blocks[i] = 0;
1929 existing_seektable = false;
1932 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1934 flac_decoder_data->num_metadata_blocks = j;
1935 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])) {
1937 FLAC__StreamMetadata *st = FLAC__metadata_object_clone(e->seek_table_template);
1939 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for SEEKTABLE block\n", e->inbasefilename);
1940 static_metadata_clear(&static_metadata);
1943 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1944 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1945 flac_decoder_data->metadata_blocks[1] = st;
1946 flac_decoder_data->num_metadata_blocks++;
1951 * finally handle padding: if --no-padding was specified,
1952 * then delete all padding; else if -P was specified,
1953 * use that instead of existing padding (if any); else
1954 * if existing file has padding, move all existing
1955 * padding blocks to one padding block at the end; else
1956 * use default padding.
1960 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1961 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_PADDING) {
1964 p += flac_decoder_data->metadata_blocks[i]->length;
1965 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1966 flac_decoder_data->metadata_blocks[i] = 0;
1969 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1971 flac_decoder_data->num_metadata_blocks = j;
1972 if(options.padding > 0)
1973 p = options.padding;
1975 p = e->total_samples_to_encode / sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8;
1976 if(options.padding != 0) {
1977 if(p > 0 && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1978 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
1979 if(0 == flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]) {
1980 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PADDING block\n", e->inbasefilename);
1981 static_metadata_clear(&static_metadata);
1984 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->is_last = false; /* the encoder will set this for us */
1985 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->length = p;
1986 flac_decoder_data->num_metadata_blocks++;
1990 metadata = &flac_decoder_data->metadata_blocks[1]; /* don't include STREAMINFO */
1991 num_metadata = flac_decoder_data->num_metadata_blocks - 1;
1995 * we're not encoding from FLAC so we will build the metadata
1998 const foreign_metadata_t *foreign_metadata = EncoderSession_format_is_iff(e)? options.format_options.iff.foreign_metadata : 0;
2001 if(e->seek_table_template->data.seek_table.num_points > 0) {
2002 e->seek_table_template->is_last = false; /* the encoder will set this for us */
2003 static_metadata_append(&static_metadata, e->seek_table_template, /*needs_delete=*/false);
2005 if(0 != static_metadata.cuesheet)
2006 static_metadata_append(&static_metadata, static_metadata.cuesheet, /*needs_delete=*/false);
2007 if(e->info.channel_mask) {
2008 if(!flac__utils_set_channel_mask_tag(options.vorbis_comment, e->info.channel_mask)) {
2009 flac__utils_printf(stderr, 1, "%s: ERROR adding channel mask tag\n", e->inbasefilename);
2010 static_metadata_clear(&static_metadata);
2014 static_metadata_append(&static_metadata, options.vorbis_comment, /*needs_delete=*/false);
2015 for(i = 0; i < options.num_pictures; i++)
2016 static_metadata_append(&static_metadata, options.pictures[i], /*needs_delete=*/false);
2017 if(foreign_metadata) {
2018 for(i = 0; i < foreign_metadata->num_blocks; i++) {
2019 FLAC__StreamMetadata *p = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
2021 flac__utils_printf(stderr, 1, "%s: ERROR: out of memory\n", e->inbasefilename);
2022 static_metadata_clear(&static_metadata);
2025 static_metadata_append(&static_metadata, p, /*needs_delete=*/true);
2026 static_metadata.metadata[static_metadata.num_metadata-1]->length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8 + foreign_metadata->blocks[i].size;
2029 if(options.padding != 0) {
2030 padding.is_last = false; /* the encoder will set this for us */
2031 padding.type = FLAC__METADATA_TYPE_PADDING;
2032 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));
2033 static_metadata_append(&static_metadata, &padding, /*needs_delete=*/false);
2035 metadata = static_metadata.metadata;
2036 num_metadata = static_metadata.num_metadata;
2039 /* check for a few things that have not already been checked. the
2040 * FLAC__stream_encoder_init*() will check it but only return
2041 * FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA so we check some
2042 * up front to give a better error message.
2044 if(!verify_metadata(e, metadata, num_metadata)) {
2045 static_metadata_clear(&static_metadata);
2049 FLAC__stream_encoder_set_verify(e->encoder, options.verify);
2050 FLAC__stream_encoder_set_streamable_subset(e->encoder, !options.lax);
2051 FLAC__stream_encoder_set_channels(e->encoder, channels);
2052 FLAC__stream_encoder_set_bits_per_sample(e->encoder, bps);
2053 FLAC__stream_encoder_set_sample_rate(e->encoder, sample_rate);
2054 for(ic = 0; ic < options.num_compression_settings; ic++) {
2055 switch(options.compression_settings[ic].type) {
2057 FLAC__stream_encoder_set_blocksize(e->encoder, options.compression_settings[ic].value.t_unsigned);
2059 case CST_COMPRESSION_LEVEL:
2060 FLAC__stream_encoder_set_compression_level(e->encoder, options.compression_settings[ic].value.t_unsigned);
2061 apodizations[0] = '\0';
2063 case CST_DO_MID_SIDE:
2064 FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder, options.compression_settings[ic].value.t_bool);
2066 case CST_LOOSE_MID_SIDE:
2067 FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder, options.compression_settings[ic].value.t_bool);
2069 case CST_APODIZATION:
2070 if(strlen(apodizations)+strlen(options.compression_settings[ic].value.t_string)+2 >= sizeof(apodizations)) {
2071 flac__utils_printf(stderr, 1, "%s: ERROR: too many apodization functions requested\n", e->inbasefilename);
2072 static_metadata_clear(&static_metadata);
2076 safe_strncat(apodizations, options.compression_settings[ic].value.t_string, sizeof(apodizations));
2077 safe_strncat(apodizations, ";", sizeof(apodizations));
2080 case CST_MAX_LPC_ORDER:
2081 FLAC__stream_encoder_set_max_lpc_order(e->encoder, options.compression_settings[ic].value.t_unsigned);
2083 case CST_QLP_COEFF_PRECISION:
2084 FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder, options.compression_settings[ic].value.t_unsigned);
2086 case CST_DO_QLP_COEFF_PREC_SEARCH:
2087 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder, options.compression_settings[ic].value.t_bool);
2089 case CST_DO_ESCAPE_CODING:
2090 FLAC__stream_encoder_set_do_escape_coding(e->encoder, options.compression_settings[ic].value.t_bool);
2092 case CST_DO_EXHAUSTIVE_MODEL_SEARCH:
2093 FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder, options.compression_settings[ic].value.t_bool);
2095 case CST_MIN_RESIDUAL_PARTITION_ORDER:
2096 FLAC__stream_encoder_set_min_residual_partition_order(e->encoder, options.compression_settings[ic].value.t_unsigned);
2098 case CST_MAX_RESIDUAL_PARTITION_ORDER:
2099 FLAC__stream_encoder_set_max_residual_partition_order(e->encoder, options.compression_settings[ic].value.t_unsigned);
2101 case CST_RICE_PARAMETER_SEARCH_DIST:
2102 FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder, options.compression_settings[ic].value.t_unsigned);
2107 FLAC__stream_encoder_set_apodization(e->encoder, apodizations);
2108 FLAC__stream_encoder_set_total_samples_estimate(e->encoder, e->total_samples_to_encode);
2109 FLAC__stream_encoder_set_metadata(e->encoder, (num_metadata > 0)? metadata : 0, num_metadata);
2111 FLAC__stream_encoder_disable_constant_subframes(e->encoder, options.debug.disable_constant_subframes);
2112 FLAC__stream_encoder_disable_fixed_subframes(e->encoder, options.debug.disable_fixed_subframes);
2113 FLAC__stream_encoder_disable_verbatim_subframes(e->encoder, options.debug.disable_verbatim_subframes);
2114 if(!options.debug.do_md5) {
2115 flac__utils_printf(stderr, 1, "%s: WARNING, MD5 computation disabled, resulting file will not have MD5 sum\n", e->inbasefilename);
2116 if(e->treat_warnings_as_errors) {
2117 static_metadata_clear(&static_metadata);
2120 FLAC__stream_encoder_set_do_md5(e->encoder, false);
2125 FLAC__stream_encoder_set_ogg_serial_number(e->encoder, options.serial_number);
2127 init_status = FLAC__stream_encoder_init_ogg_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
2132 init_status = FLAC__stream_encoder_init_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
2135 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
2136 print_error_with_init_status(e, "ERROR initializing encoder", init_status);
2137 if(FLAC__stream_encoder_get_state(e->encoder) != FLAC__STREAM_ENCODER_IO_ERROR)
2138 e->outputfile_opened = true;
2139 static_metadata_clear(&static_metadata);
2143 e->outputfile_opened = true;
2146 (FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) && FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x07 :
2147 (FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x0f :
2150 static_metadata_clear(&static_metadata);
2155 FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples)
2157 if(e->replay_gain) {
2158 if(!grabbag__replaygain_analyze(buffer, e->info.channels==2, e->info.bits_per_sample, samples)) {
2159 flac__utils_printf(stderr, 1, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename);
2160 if(e->treat_warnings_as_errors)
2165 return FLAC__stream_encoder_process(e->encoder, buffer, samples);
2168 FLAC__bool EncoderSession_format_is_iff(const EncoderSession *e)
2171 e->format == FORMAT_WAVE ||
2172 e->format == FORMAT_WAVE64 ||
2173 e->format == FORMAT_RF64 ||
2174 e->format == FORMAT_AIFF ||
2175 e->format == FORMAT_AIFF_C;
2178 FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e)
2180 const FLAC__bool only_placeholders = e->is_stdout;
2181 FLAC__bool has_real_points;
2183 if(num_requested_seek_points == 0 && 0 == cuesheet)
2186 if(num_requested_seek_points < 0) {
2188 /*@@@@@@ workaround ogg bug: too many seekpoints makes table not fit in one page */
2189 if(e->use_ogg && e->total_samples_to_encode > 0 && e->total_samples_to_encode / e->info.sample_rate / 10 > 230)
2190 requested_seek_points = "230x;";
2193 requested_seek_points = "10s;";
2194 num_requested_seek_points = 1;
2197 if(num_requested_seek_points > 0) {
2198 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))
2204 const FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet;
2205 for(i = 0; i < cs->num_tracks; i++) {
2206 const FLAC__StreamMetadata_CueSheet_Track *tr = cs->tracks+i;
2207 for(j = 0; j < tr->num_indices; j++) {
2208 if(!FLAC__metadata_object_seektable_template_append_point(e->seek_table_template, tr->offset + tr->indices[j].offset))
2210 has_real_points = true;
2214 if(!FLAC__metadata_object_seektable_template_sort(e->seek_table_template, /*compact=*/true))
2218 if(has_real_points) {
2220 flac__utils_printf(stderr, 1, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename);
2221 if(e->treat_warnings_as_errors)
2229 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
2231 /* convert from mm:ss.sss to sample number if necessary */
2232 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
2234 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
2235 if(spec->is_relative && spec->value.samples == 0) {
2236 spec->is_relative = false;
2240 /* in any other case the total samples in the input must be known */
2241 if(total_samples_in_input == 0) {
2242 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when input length is unknown\n", inbasefilename);
2246 FLAC__ASSERT(spec->value_is_samples);
2248 /* convert relative specifications to absolute */
2249 if(spec->is_relative) {
2250 if(spec->value.samples <= 0)
2251 spec->value.samples += (FLAC__int64)total_samples_in_input;
2253 spec->value.samples += skip;
2254 spec->is_relative = false;
2258 if(spec->value.samples < 0) {
2259 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
2262 if((FLAC__uint64)spec->value.samples <= skip) {
2263 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
2266 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
2267 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
2274 FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata)
2276 FLAC__bool metadata_picture_has_type1 = false;
2277 FLAC__bool metadata_picture_has_type2 = false;
2280 FLAC__ASSERT(0 != metadata);
2281 for(i = 0; i < num_metadata; i++) {
2282 const FLAC__StreamMetadata *m = metadata[i];
2283 if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
2284 if(!FLAC__format_seektable_is_legal(&m->data.seek_table)) {
2285 flac__utils_printf(stderr, 1, "%s: ERROR: SEEKTABLE metadata block is invalid\n", e->inbasefilename);
2289 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
2290 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0)) {
2291 flac__utils_printf(stderr, 1, "%s: ERROR: CUESHEET metadata block is invalid\n", e->inbasefilename);
2295 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
2296 const char *error = 0;
2297 if(!FLAC__format_picture_is_legal(&m->data.picture, &error)) {
2298 flac__utils_printf(stderr, 1, "%s: ERROR: PICTURE metadata block is invalid: %s\n", e->inbasefilename, error);
2301 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
2302 if(metadata_picture_has_type1) {
2303 flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 1 (32x32 icon) in the file\n", e->inbasefilename);
2306 metadata_picture_has_type1 = true;
2308 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
2309 if(metadata_picture_has_type2) {
2310 flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 2 (icon) in the file\n", e->inbasefilename);
2313 metadata_picture_has_type2 = true;
2321 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)
2323 unsigned wide_sample, sample, channel;
2324 FLAC__int32 *out[FLAC__MAX_CHANNELS];
2326 if(0 == channel_map) {
2327 for(channel = 0; channel < channels; channel++)
2328 out[channel] = dest[channel];
2331 for(channel = 0; channel < channels; channel++)
2332 out[channel] = dest[channel_map[channel]];
2336 if(is_unsigned_samples) {
2337 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2338 for(channel = 0; channel < channels; channel++, sample++)
2339 out[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
2342 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2343 for(channel = 0; channel < channels; channel++, sample++)
2344 out[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
2347 else if(bps == 16) {
2348 if(is_big_endian != is_big_endian_host_) {
2350 const unsigned bytes = wide_samples * channels * (bps >> 3);
2352 for(b = 0; b < bytes; b += 2) {
2354 ucbuffer_[b] = ucbuffer_[b+1];
2355 ucbuffer_[b+1] = tmp;
2358 if(is_unsigned_samples) {
2359 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2360 for(channel = 0; channel < channels; channel++, sample++)
2361 out[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
2364 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2365 for(channel = 0; channel < channels; channel++, sample++)
2366 out[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
2369 else if(bps == 24) {
2370 if(!is_big_endian) {
2372 const unsigned bytes = wide_samples * channels * (bps >> 3);
2374 for(b = 0; b < bytes; b += 3) {
2376 ucbuffer_[b] = ucbuffer_[b+2];
2377 ucbuffer_[b+2] = tmp;
2380 if(is_unsigned_samples) {
2382 for(b = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2383 for(channel = 0; channel < channels; channel++, sample++) {
2384 out[channel][wide_sample] = ucbuffer_[b++]; out[channel][wide_sample] <<= 8;
2385 out[channel][wide_sample] |= ucbuffer_[b++]; out[channel][wide_sample] <<= 8;
2386 out[channel][wide_sample] |= ucbuffer_[b++];
2387 out[channel][wide_sample] -= 0x800000;
2392 for(b = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2393 for(channel = 0; channel < channels; channel++, sample++) {
2394 out[channel][wide_sample] = scbuffer_[b++]; out[channel][wide_sample] <<= 8;
2395 out[channel][wide_sample] |= ucbuffer_[b++]; out[channel][wide_sample] <<= 8;
2396 out[channel][wide_sample] |= ucbuffer_[b++];
2404 FLAC__int32 mask = (1<<shift)-1;
2405 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2406 for(channel = 0; channel < channels; channel++) {
2407 if(out[channel][wide_sample] & mask) {
2408 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);
2411 out[channel][wide_sample] >>= shift;
2417 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)
2419 EncoderSession *e = (EncoderSession*)client_data;
2421 (void)encoder, (void)total_frames_estimate;
2423 e->bytes_written = bytes_written;
2424 e->samples_written = samples_written;
2426 if(e->total_samples_to_encode > 0 && !((frames_written-1) & e->stats_mask))
2430 FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
2433 EncoderSession *e = (EncoderSession*)client_data;
2434 FLACDecoderData *data = &e->fmt.flac.client_data;
2438 if (data->fatal_error)
2439 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2441 /* use up lookahead first */
2442 if (data->lookahead_length) {
2443 n = min(data->lookahead_length, *bytes);
2444 memcpy(buffer, data->lookahead, n);
2446 data->lookahead += n;
2447 data->lookahead_length -= n;
2450 /* get the rest from file */
2452 *bytes = n + fread(buffer, 1, *bytes-n, e->fin);
2454 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2455 else if(0 == *bytes)
2456 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2458 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2461 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2464 FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2466 EncoderSession *e = (EncoderSession*)client_data;
2469 if(fseeko(e->fin, (FLAC__off_t)absolute_byte_offset, SEEK_SET) < 0)
2470 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
2472 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2475 FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2477 EncoderSession *e = (EncoderSession*)client_data;
2481 if((pos = ftello(e->fin)) < 0)
2482 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
2484 *absolute_byte_offset = (FLAC__uint64)pos;
2485 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2489 FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2491 const EncoderSession *e = (EncoderSession*)client_data;
2492 const FLACDecoderData *data = &e->fmt.flac.client_data;
2495 if(data->filesize < 0)
2496 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
2498 *stream_length = (FLAC__uint64)data->filesize;
2499 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2503 FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data)
2505 EncoderSession *e = (EncoderSession*)client_data;
2508 return feof(e->fin)? true : false;
2511 FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
2513 EncoderSession *e = (EncoderSession*)client_data;
2514 FLACDecoderData *data = &e->fmt.flac.client_data;
2515 FLAC__uint64 n = min(data->samples_left_to_process, frame->header.blocksize);
2518 if(!EncoderSession_process(e, buffer, (unsigned)n)) {
2519 print_error_with_state(e, "ERROR during encoding");
2520 data->fatal_error = true;
2521 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2524 data->samples_left_to_process -= n;
2525 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2528 void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
2530 EncoderSession *e = (EncoderSession*)client_data;
2531 FLACDecoderData *data = &e->fmt.flac.client_data;
2534 if (data->fatal_error)
2538 data->num_metadata_blocks == sizeof(data->metadata_blocks)/sizeof(data->metadata_blocks[0]) ||
2539 0 == (data->metadata_blocks[data->num_metadata_blocks] = FLAC__metadata_object_clone(metadata))
2541 data->fatal_error = true;
2543 data->num_metadata_blocks++;
2546 void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
2548 EncoderSession *e = (EncoderSession*)client_data;
2549 FLACDecoderData *data = &e->fmt.flac.client_data;
2552 stats_print_name(1, e->inbasefilename);
2553 flac__utils_printf(stderr, 1, "ERROR got %s while decoding FLAC input\n", FLAC__StreamDecoderErrorStatusString[status]);
2554 if(!e->continue_through_decode_errors)
2555 data->fatal_error = true;
2558 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)
2561 unsigned last_line_read;
2562 const char *error_message;
2564 if(0 == cuesheet_filename)
2567 if(lead_out_offset == 0) {
2568 flac__utils_printf(stderr, 1, "%s: ERROR cannot import cuesheet when the number of input samples to encode is unknown\n", inbasefilename);
2572 if(0 == (f = flac_fopen(cuesheet_filename, "r"))) {
2573 flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading: %s\n", inbasefilename, cuesheet_filename, strerror(errno));
2577 *cuesheet = grabbag__cuesheet_parse(f, &error_message, &last_line_read, sample_rate, is_cdda, lead_out_offset);
2581 if(0 == *cuesheet) {
2582 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\" on line %u: %s\n", inbasefilename, cuesheet_filename, last_line_read, error_message);
2586 if(!FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/false, &error_message)) {
2587 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\": %s\n", inbasefilename, cuesheet_filename, error_message);
2591 /* if we're expecting CDDA, warn about non-compliance */
2592 if(is_cdda && !FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/true, &error_message)) {
2593 flac__utils_printf(stderr, 1, "%s: WARNING cuesheet \"%s\" is not audio CD compliant: %s\n", inbasefilename, cuesheet_filename, error_message);
2594 if(treat_warnings_as_errors)
2596 (*cuesheet)->data.cue_sheet.is_cd = false;
2602 void print_stats(const EncoderSession *encoder_session)
2604 if(flac__utils_verbosity_ >= 2) {
2605 const FLAC__uint64 samples_written = min(encoder_session->total_samples_to_encode, encoder_session->samples_written);
2606 const FLAC__uint64 uesize = encoder_session->unencoded_size;
2607 #if defined _MSC_VER || defined __MINGW32__
2608 /* with MSVC you have to spoon feed it the casting */
2609 const double progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)encoder_session->total_samples_to_encode;
2610 const double ratio = (double)(FLAC__int64)encoder_session->bytes_written / ((double)(FLAC__int64)(uesize? uesize:1) * min(1.0, progress));
2612 const double progress = (double)samples_written / (double)encoder_session->total_samples_to_encode;
2613 const double ratio = (double)encoder_session->bytes_written / ((double)(uesize? uesize:1) * min(1.0, progress));
2617 FLAC__ASSERT(encoder_session->total_samples_to_encode > 0);
2619 if (uesize) flac_snprintf(ratiostr, sizeof(ratiostr), "%0.3f", ratio); else flac_snprintf(ratiostr, sizeof(ratiostr), "N/A");
2621 if(samples_written == encoder_session->total_samples_to_encode) {
2622 stats_print_name(2, encoder_session->inbasefilename);
2623 stats_print_info(2, "%swrote %" PRIu64 " bytes, ratio=%s",
2624 encoder_session->verify? "Verify OK, " : "",
2625 encoder_session->bytes_written,
2630 stats_print_name(2, encoder_session->inbasefilename);
2631 stats_print_info(2, "%u%% complete, ratio=%s", (unsigned)floor(progress * 100.0 + 0.5), ratiostr);
2636 void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status)
2638 const int ilen = strlen(e->inbasefilename) + 1;
2639 const char *state_string = "";
2641 flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2643 flac__utils_printf(stderr, 1, "%*s init_status = %s\n", ilen, "", FLAC__StreamEncoderInitStatusString[init_status]);
2645 if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR) {
2646 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
2648 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2650 /* print out some more info for some errors: */
2651 if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
2652 flac__utils_printf(stderr, 1,
2654 "An error occurred while writing; the most common cause is that the disk is full.\n"
2657 else if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_IO_ERROR])) {
2658 flac__utils_printf(stderr, 1,
2660 "An error occurred opening the output file; it is likely that the output\n"
2661 "directory does not exist or is not writable, the output file already exists and\n"
2662 "is not writable, or the disk is full.\n"
2666 else if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE) {
2667 flac__utils_printf(stderr, 1,
2669 "The encoding parameters specified do not conform to the FLAC Subset and may not\n"
2670 "be streamable or playable in hardware devices. If you really understand the\n"
2671 "consequences, you can add --lax to the command-line options to encode with\n"
2672 "these parameters anyway. See http://flac.sourceforge.net/format.html#subset\n"
2677 void print_error_with_state(const EncoderSession *e, const char *message)
2679 const int ilen = strlen(e->inbasefilename) + 1;
2680 const char *state_string;
2682 flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2684 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
2686 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2688 /* print out some more info for some errors: */
2689 if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
2690 flac__utils_printf(stderr, 1,
2692 "An error occurred while writing; the most common cause is that the disk is full.\n"
2697 void print_verify_error(EncoderSession *e)
2699 FLAC__uint64 absolute_sample;
2700 unsigned frame_number;
2703 FLAC__int32 expected;
2706 FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2708 flac__utils_printf(stderr, 1, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
2709 flac__utils_printf(stderr, 1, " Absolute sample=%" PRIu64 ", frame=%u, channel=%u, sample=%u, expected %d, got %d\n", absolute_sample, frame_number, channel, sample, expected, got);
2710 flac__utils_printf(stderr, 1, " In all known cases, verify errors are caused by hardware problems,\n");
2711 flac__utils_printf(stderr, 1, " usually overclocking or bad RAM. Delete %s\n", e->outfilename);
2712 flac__utils_printf(stderr, 1, " and repeat the flac command exactly as before. If it does not give a\n");
2713 flac__utils_printf(stderr, 1, " verify error in the exact same place each time you try it, then there is\n");
2714 flac__utils_printf(stderr, 1, " a problem with your hardware; please see the FAQ:\n");
2715 flac__utils_printf(stderr, 1, " http://flac.sourceforge.net/faq.html#tools__hardware_prob\n");
2716 flac__utils_printf(stderr, 1, " If it does fail in the exact same place every time, keep\n");
2717 flac__utils_printf(stderr, 1, " %s and submit a bug report to:\n", e->outfilename);
2718 flac__utils_printf(stderr, 1, " https://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
2719 flac__utils_printf(stderr, 1, " Make sure to upload the FLAC file and use the \"Monitor\" feature to\n");
2720 flac__utils_printf(stderr, 1, " monitor the bug status.\n");
2721 flac__utils_printf(stderr, 1, "Verify FAILED! Do not trust %s\n", e->outfilename);
2724 FLAC__bool read_bytes(FILE *f, FLAC__byte *buf, size_t n, FLAC__bool eof_ok, const char *fn)
2726 size_t bytes_read = fread(buf, 1, n, f);
2728 if(bytes_read == 0) {
2730 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2736 if(bytes_read < n) {
2737 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2743 FLAC__bool read_uint16(FILE *f, FLAC__bool big_endian, FLAC__uint16 *val, const char *fn)
2745 if(!read_bytes(f, (FLAC__byte*)val, 2, /*eof_ok=*/false, fn))
2747 if(is_big_endian_host_ != big_endian) {
2748 FLAC__byte tmp, *b = (FLAC__byte*)val;
2749 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
2754 FLAC__bool read_uint32(FILE *f, FLAC__bool big_endian, FLAC__uint32 *val, const char *fn)
2756 if(!read_bytes(f, (FLAC__byte*)val, 4, /*eof_ok=*/false, fn))
2758 if(is_big_endian_host_ != big_endian) {
2759 FLAC__byte tmp, *b = (FLAC__byte*)val;
2760 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
2761 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
2766 FLAC__bool read_uint64(FILE *f, FLAC__bool big_endian, FLAC__uint64 *val, const char *fn)
2768 if(!read_bytes(f, (FLAC__byte*)val, 8, /*eof_ok=*/false, fn))
2770 if(is_big_endian_host_ != big_endian) {
2771 FLAC__byte tmp, *b = (FLAC__byte*)val;
2772 tmp = b[7]; b[7] = b[0]; b[0] = tmp;
2773 tmp = b[6]; b[6] = b[1]; b[1] = tmp;
2774 tmp = b[5]; b[5] = b[2]; b[2] = tmp;
2775 tmp = b[4]; b[4] = b[3]; b[3] = tmp;
2780 FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, const char *fn)
2781 /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
2782 * convert it into an integral value and store in 'val'. Return false if only
2783 * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f', or if the
2784 * value is negative, between zero and one, or too large to be represented by
2785 * 'val'; return true otherwise.
2794 if(!read_bytes(f, buf, sizeof(buf), /*eof_ok=*/false, fn))
2796 e = ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
2798 if((buf[0]>>7)==1U || e<0 || e>63) {
2799 flac__utils_printf(stderr, 1, "%s: ERROR: invalid floating-point value\n", fn);
2803 for(i = 0; i < 8; ++i)
2804 p |= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
2805 *val = (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1));
2810 FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset)
2812 static unsigned char dump[8192];
2813 struct flac_stat_s stb;
2815 if(flac_fstat(fileno(f), &stb) == 0 && (stb.st_mode & S_IFMT) == S_IFREG)
2817 if(fseeko(f, offset, SEEK_CUR) == 0)
2821 const long need = (long)min(offset, sizeof(dump));
2822 if((long)fread(dump, 1, need, f) < need)
2829 unsigned count_channel_mask_bits(FLAC__uint32 mask)
2841 FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels)
2843 FLAC__uint32 x = 0x80000000;
2844 unsigned count = count_channel_mask_bits(mask);
2845 while(x && count > channels) {
2852 FLAC__ASSERT(count_channel_mask_bits(mask) == channels);