1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006 Josh Coalson
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 #if defined _WIN32 && !defined __CYGWIN__
24 /* where MSVC puts unlink() */
29 #if defined _MSC_VER || defined __MINGW32__
30 #include <sys/types.h> /* for off_t */
31 //@@@@@@ [2G limit] hacks for MSVC6
36 #include <limits.h> /* for LONG_MAX */
37 #include <math.h> /* for floor() */
38 #include <stdio.h> /* for FILE etc. */
39 #include <stdlib.h> /* for malloc */
40 #include <string.h> /* for strcmp(), strerror( */
42 #include "share/grabbag.h"
46 #include "OggFLAC/stream_encoder.h"
52 #define min(x,y) ((x)<(y)?(x):(y))
56 #define max(x,y) ((x)>(y)?(x):(y))
58 /* this MUST be >= 588 so that sector aligning can take place with one read */
59 #define CHUNK_OF_SAMPLES 2048
67 const char *inbasefilename;
68 const char *outfilename;
71 FLAC__uint64 until; /* a value of 0 mean end-of-stream (i.e. --until=-0) */
72 FLAC__bool replay_gain;
74 unsigned bits_per_sample;
76 FLAC__uint64 unencoded_size;
77 FLAC__uint64 total_samples_to_encode;
78 FLAC__uint64 bytes_written;
79 FLAC__uint64 samples_written;
84 FLAC__StreamEncoder *flac;
86 OggFLAC__StreamEncoder *ogg;
91 FLAC__StreamMetadata *seek_table_template;
94 /* this is data attached to the FLAC decoder when encoding from a FLAC file */
96 EncoderSession *encoder_session;
98 const FLAC__byte *lookahead;
99 unsigned lookahead_length;
100 size_t num_metadata_blocks;
101 FLAC__StreamMetadata *metadata_blocks[1024]; /*@@@ BAD MAGIC number */
102 FLAC__uint64 samples_left_to_process;
103 FLAC__bool fatal_error;
106 const int FLAC_ENCODE__DEFAULT_PADDING = 8192;
108 static FLAC__bool is_big_endian_host_;
110 static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
111 static signed char *scbuffer_ = (signed char *)ucbuffer_;
112 static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_;
113 static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_;
115 static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
116 static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
120 * unpublished debug routines from the FLAC libs
122 extern FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
123 extern FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
124 extern FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
126 extern FLAC__bool OggFLAC__stream_encoder_disable_constant_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
127 extern FLAC__bool OggFLAC__stream_encoder_disable_fixed_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
128 extern FLAC__bool OggFLAC__stream_encoder_disable_verbatim_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
134 static FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FILE *infile, const char *infilename, const char *outfilename);
135 static void EncoderSession_destroy(EncoderSession *e);
136 static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero);
137 static int EncoderSession_finish_error(EncoderSession *e);
138 static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, FLACDecoderData *flac_decoder_data);
139 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
140 static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
141 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
142 static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata);
143 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);
144 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);
145 static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
146 static FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
147 static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
148 static FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
149 static FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data);
150 static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
151 static void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
152 static void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
153 static FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset);
154 static void print_stats(const EncoderSession *encoder_session);
155 static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
156 static void print_error_with_state(const EncoderSession *e, const char *message);
157 static void print_verify_error(EncoderSession *e);
158 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
159 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
160 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
161 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
162 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
163 static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
164 static unsigned count_channel_mask_bits(FLAC__uint32 mask);
165 static unsigned limit_channel_mask(FLAC__uint32 mask, unsigned channels);
170 int flac__encode_aif(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options, FLAC__bool is_aifc)
172 EncoderSession encoder_session;
175 unsigned int channels= 0U, bps= 0U, sample_rate= 0U, sample_frames= 0U;
176 FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
177 int info_align_carry= -1, info_align_zero= -1;
178 FLAC__bool is_big_endian_pcm = true;
180 (void)infilesize; /* silence compiler warning about unused parameter */
181 (void)lookahead; /* silence compiler warning about unused parameter */
182 (void)lookahead_length; /* silence compiler warning about unused parameter */
185 EncoderSession_construct(
188 options.common.use_ogg,
192 options.common.verify,
200 /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
204 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 */
206 /* chunk identifier; really conservative about behavior of fread() and feof() */
207 if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
209 else if(c<4U || feof(infile)) {
210 flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", encoder_session.inbasefilename);
211 return EncoderSession_finish_error(&encoder_session);
214 if(got_comm_chunk==false && !memcmp(chunk_id, "COMM", 4)) { /* common chunk */
216 const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18);
218 /* COMM chunk size */
219 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
220 return EncoderSession_finish_error(&encoder_session);
221 else if(xx<minimum_comm_size) {
222 flac__utils_printf(stderr, 1, "%s: ERROR: non-standard %s 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx);
223 return EncoderSession_finish_error(&encoder_session);
225 else if(!is_aifc && xx!=minimum_comm_size) {
226 flac__utils_printf(stderr, 1, "%s: WARNING: non-standard %s 'COMM' chunk has length = %u, expected %u\n", encoder_session.inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx, minimum_comm_size);
228 skip= (xx-minimum_comm_size)+(xx & 1U);
230 /* number of channels */
231 if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
232 return EncoderSession_finish_error(&encoder_session);
233 else if(x==0U || x>FLAC__MAX_CHANNELS) {
234 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned int)x);
235 return EncoderSession_finish_error(&encoder_session);
237 else if(options.common.sector_align && x!=2U) {
238 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
239 return EncoderSession_finish_error(&encoder_session);
243 /* number of sample frames */
244 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
245 return EncoderSession_finish_error(&encoder_session);
248 /* bits per sample */
249 if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
250 return EncoderSession_finish_error(&encoder_session);
251 else if(x!=8U && x!=16U && x!=24U) {
252 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits per sample %u\n", encoder_session.inbasefilename, (unsigned int)x);
253 return EncoderSession_finish_error(&encoder_session);
255 else if(options.common.sector_align && x!=16U) {
256 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
257 return EncoderSession_finish_error(&encoder_session);
262 if(!read_sane_extended(infile, &xx, false, encoder_session.inbasefilename))
263 return EncoderSession_finish_error(&encoder_session);
264 else if(!FLAC__format_sample_rate_is_valid(xx)) {
265 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned int)xx);
266 return EncoderSession_finish_error(&encoder_session);
268 else if(options.common.sector_align && xx!=44100U) {
269 flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)xx);
270 return EncoderSession_finish_error(&encoder_session);
274 /* check compression type for AIFF-C */
276 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
277 return EncoderSession_finish_error(&encoder_session);
278 if(xx == 0x736F7774) /* "sowt" */
279 is_big_endian_pcm = false;
280 else if(xx == 0x4E4F4E45) /* "NONE" */
281 ; /* nothing to do, we already default to big-endian */
283 flac__utils_printf(stderr, 1, "%s: ERROR: can't handle AIFF-C compression type \"%c%c%c%c\"\n", encoder_session.inbasefilename, (char)(xx>>24), (char)((xx>>16)&8), (char)((xx>>8)&8), (char)(xx&8));
284 return EncoderSession_finish_error(&encoder_session);
288 /* skip any extra data in the COMM chunk */
289 if(!fskip_ahead(infile, skip)) {
290 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping extra COMM data\n", encoder_session.inbasefilename);
291 return EncoderSession_finish_error(&encoder_session);
295 * now that we know the sample rate, canonicalize the
296 * --skip string to a number of samples:
298 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, sample_rate);
299 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
300 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
301 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
303 got_comm_chunk= true;
305 else if(got_ssnd_chunk==false && !memcmp(chunk_id, "SSND", 4)) { /* sound data chunk */
306 unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
307 size_t bytes_per_frame= channels*(bps>>3);
308 FLAC__uint64 total_samples_in_input, trim = 0;
309 FLAC__bool pad= false;
311 if(got_comm_chunk==false) {
312 flac__utils_printf(stderr, 1, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", encoder_session.inbasefilename);
313 return EncoderSession_finish_error(&encoder_session);
316 /* SSND chunk size */
317 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
318 return EncoderSession_finish_error(&encoder_session);
320 pad= (data_bytes & 1U) ? true : false;
321 data_bytes-= 8U; /* discount the offset and block size fields */
324 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
325 return EncoderSession_finish_error(&encoder_session);
330 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
331 return EncoderSession_finish_error(&encoder_session);
333 flac__utils_printf(stderr, 1, "%s: ERROR: block size is %u; must be 0\n", encoder_session.inbasefilename, (unsigned int)xx);
334 return EncoderSession_finish_error(&encoder_session);
338 /* skip any SSND offset bytes */
339 FLAC__ASSERT(offset<=LONG_MAX);
340 if(!fskip_ahead(infile, offset)) {
341 flac__utils_printf(stderr, 1, "%s: ERROR: skipping offset in SSND chunk\n", encoder_session.inbasefilename);
342 return EncoderSession_finish_error(&encoder_session);
344 if(data_bytes!=(sample_frames*bytes_per_frame)) {
345 flac__utils_printf(stderr, 1, "%s: ERROR: SSND chunk size inconsistent with sample frame count\n", encoder_session.inbasefilename);
346 return EncoderSession_finish_error(&encoder_session);
349 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
350 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
351 total_samples_in_input = data_bytes / bytes_per_frame + *options.common.align_reservoir_samples;
354 * now that we know the input size, canonicalize the
355 * --until string to an absolute sample number:
357 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, sample_rate, encoder_session.skip, total_samples_in_input))
358 return EncoderSession_finish_error(&encoder_session);
359 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
360 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
362 if(encoder_session.skip>0U) {
363 if(!fskip_ahead(infile, encoder_session.skip*bytes_per_frame)) {
364 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
365 return EncoderSession_finish_error(&encoder_session);
369 data_bytes-= (unsigned int)encoder_session.skip*bytes_per_frame; /*@@@ WATCHOUT: 4GB limit */
370 encoder_session.total_samples_to_encode= total_samples_in_input - encoder_session.skip;
371 if(encoder_session.until > 0) {
372 trim = total_samples_in_input - encoder_session.until;
373 FLAC__ASSERT(total_samples_in_input > 0);
374 FLAC__ASSERT(!options.common.sector_align);
375 data_bytes-= (unsigned int)trim*bytes_per_frame;
376 encoder_session.total_samples_to_encode-= trim;
378 if(options.common.sector_align) {
379 align_remainder= (unsigned int)(encoder_session.total_samples_to_encode % 588U);
380 if(options.common.is_last_file)
381 encoder_session.total_samples_to_encode+= (588U-align_remainder); /* will pad with zeroes */
383 encoder_session.total_samples_to_encode-= align_remainder; /* will stop short and carry over to next file */
386 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
387 encoder_session.unencoded_size= encoder_session.total_samples_to_encode*bytes_per_frame+54;
389 if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate, /*flac_decoder_data=*/0))
390 return EncoderSession_finish_error(&encoder_session);
392 /* first do any samples in the reservoir */
393 if(options.common.sector_align && *options.common.align_reservoir_samples>0U) {
395 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
396 print_error_with_state(&encoder_session, "ERROR during encoding");
397 return EncoderSession_finish_error(&encoder_session);
401 /* decrement the data_bytes counter if we need to align the file */
402 if(options.common.sector_align) {
403 if(options.common.is_last_file)
404 *options.common.align_reservoir_samples= 0U;
406 *options.common.align_reservoir_samples= align_remainder;
407 data_bytes-= (*options.common.align_reservoir_samples)*bytes_per_frame;
411 /* now do from the file */
412 while(data_bytes>0) {
413 size_t bytes_read= fread(ucbuffer_, 1U, min(data_bytes, CHUNK_OF_SAMPLES*bytes_per_frame), infile);
417 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
418 return EncoderSession_finish_error(&encoder_session);
420 else if(feof(infile)) {
421 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned int)encoder_session.total_samples_to_encode, (unsigned int)encoder_session.samples_written);
426 if(bytes_read % bytes_per_frame != 0U) {
427 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
428 return EncoderSession_finish_error(&encoder_session);
431 unsigned int frames= bytes_read/bytes_per_frame;
432 if(!format_input(input_, frames, is_big_endian_pcm, /*is_unsigned_samples=*/false, channels, bps, /*shift=*/0))
433 return EncoderSession_finish_error(&encoder_session);
435 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, frames)) {
436 print_error_with_state(&encoder_session, "ERROR during encoding");
437 return EncoderSession_finish_error(&encoder_session);
440 data_bytes-= bytes_read;
446 FLAC__ASSERT(!options.common.sector_align);
447 if(!fskip_ahead(infile, trim*bytes_per_frame)) {
448 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
449 return EncoderSession_finish_error(&encoder_session);
453 /* now read unaligned samples into reservoir or pad with zeroes if necessary */
454 if(options.common.sector_align) {
455 if(options.common.is_last_file) {
456 unsigned int pad_frames= 588U-align_remainder;
458 if(pad_frames<588U) {
461 info_align_zero= pad_frames;
462 for(i= 0U; i<channels; ++i)
463 memset(input_[i], 0, sizeof(input_[0][0])*pad_frames);
465 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, pad_frames)) {
466 print_error_with_state(&encoder_session, "ERROR during encoding");
467 return EncoderSession_finish_error(&encoder_session);
472 if(*options.common.align_reservoir_samples > 0) {
473 size_t bytes_read= fread(ucbuffer_, 1U, (*options.common.align_reservoir_samples)*bytes_per_frame, infile);
475 FLAC__ASSERT(CHUNK_OF_SAMPLES>=588U);
476 if(bytes_read==0U && ferror(infile)) {
477 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
478 return EncoderSession_finish_error(&encoder_session);
480 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame) {
481 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned int)bytes_read, (unsigned int)encoder_session.total_samples_to_encode, (unsigned int)encoder_session.samples_written);
484 info_align_carry= *options.common.align_reservoir_samples;
485 if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, is_big_endian_pcm, /*is_unsigned_samples=*/false, channels, bps, /*shift=*/0))
486 return EncoderSession_finish_error(&encoder_session);
495 if(fread(&tmp, 1U, 1U, infile)<1U) {
496 flac__utils_printf(stderr, 1, "%s: ERROR during read of SSND pad byte\n", encoder_session.inbasefilename);
497 return EncoderSession_finish_error(&encoder_session);
501 got_ssnd_chunk= true;
503 else { /* other chunk */
504 if(!memcmp(chunk_id, "COMM", 4)) {
505 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_session.inbasefilename);
507 else if(!memcmp(chunk_id, "SSND", 4)) {
508 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_session.inbasefilename);
511 flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_session.inbasefilename, chunk_id);
515 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
516 return EncoderSession_finish_error(&encoder_session);
518 unsigned long skip= xx+(xx & 1U);
520 FLAC__ASSERT(skip<=LONG_MAX);
521 if(!fskip_ahead(infile, skip)) {
522 fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_session.inbasefilename);
523 return EncoderSession_finish_error(&encoder_session);
529 if(got_ssnd_chunk==false && sample_frames!=0U) {
530 flac__utils_printf(stderr, 1, "%s: ERROR: missing SSND chunk\n", encoder_session.inbasefilename);
531 return EncoderSession_finish_error(&encoder_session);
534 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
537 int flac__encode_wav(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
539 EncoderSession encoder_session;
540 FLAC__bool is_unsigned_samples = false;
541 unsigned channels = 0, bps = 0, sample_rate = 0, shift = 0;
542 size_t bytes_per_wide_sample, bytes_read;
543 FLAC__uint16 x, format; /* format is the wFormatTag word from the 'fmt ' chunk */
544 FLAC__uint32 xx, channel_mask = 0;
545 FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
546 unsigned align_remainder = 0;
547 int info_align_carry = -1, info_align_zero = -1;
551 (void)lookahead_length;
554 EncoderSession_construct(
557 options.common.use_ogg,
561 options.common.verify,
570 * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
572 while(!feof(infile)) {
573 if(!read_little_endian_uint32(infile, &xx, true, encoder_session.inbasefilename))
574 return EncoderSession_finish_error(&encoder_session);
577 if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
578 unsigned block_align, data_bytes;
581 * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
582 * http://windowssdk.msdn.microsoft.com/en-us/library/ms713497.aspx
583 * 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
586 * 4 byte: subchunk size
587 * 2 byte: format type: 1 for WAVE_FORMAT_PCM, 65534 for WAVE_FORMAT_EXTENSIBLE
589 * 4 byte: sample rate (Hz)
590 * 4 byte: avg bytes per sec
591 * 2 byte: block align
592 * 2 byte: bits per sample (not necessarily all significant)
594 * 2 byte: extension size in bytes (usually 0 for WAVEFORMATEX and 22 for WAVEFORMATEXTENSIBLE with PCM)
595 * WAVEFORMATEXTENSIBLE adds
596 * 2 byte: valid bits per sample
597 * 4 byte: channel mask
598 * 16 byte: subformat GUID, first 2 bytes have format type, 1 being PCM
600 * Current spec says WAVEFORMATEX with PCM must have bps == 8 or 16, or any multiple of 8 for WAVEFORMATEXTENSIBLE.
601 * 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.
603 * Block align for WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE is also supposed to be channels*bps/8
605 * If the channel mask has less set bits that # of channels, the extra MSBs are ignored.
606 * If the channel mask has more set bits that # of channels, the extra channels are unassigned to any speaker.
608 * Data is supposed to be unsigned for bps <= 8 else signed.
611 /* fmt sub-chunk size */
612 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
613 return EncoderSession_finish_error(&encoder_session);
615 flac__utils_printf(stderr, 1, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
616 return EncoderSession_finish_error(&encoder_session);
619 /* compression code */
620 if(!read_little_endian_uint16(infile, &format, false, encoder_session.inbasefilename))
621 return EncoderSession_finish_error(&encoder_session);
622 if(format != 1 /*WAVE_FORMAT_PCM*/ && format != 65534 /*WAVE_FORMAT_EXTENSIBLE*/) {
623 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", encoder_session.inbasefilename, (unsigned)format);
624 return EncoderSession_finish_error(&encoder_session);
626 /* number of channels */
627 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
628 return EncoderSession_finish_error(&encoder_session);
629 if(x == 0 || x > FLAC__MAX_CHANNELS) {
630 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u\n", encoder_session.inbasefilename, (unsigned)x);
631 return EncoderSession_finish_error(&encoder_session);
633 else if(options.common.sector_align && x != 2) {
634 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
635 return EncoderSession_finish_error(&encoder_session);
639 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
640 return EncoderSession_finish_error(&encoder_session);
641 if(!FLAC__format_sample_rate_is_valid(xx)) {
642 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned)xx);
643 return EncoderSession_finish_error(&encoder_session);
645 else if(options.common.sector_align && xx != 44100) {
646 flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned)xx);
647 return EncoderSession_finish_error(&encoder_session);
650 /* avg bytes per second (ignored) */
651 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
652 return EncoderSession_finish_error(&encoder_session);
654 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
655 return EncoderSession_finish_error(&encoder_session);
657 /* bits per sample */
658 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
659 return EncoderSession_finish_error(&encoder_session);
661 is_unsigned_samples = (bps <= 8);
663 if(bps != 8 && bps != 16) {
664 #if 0 /* reinstate if we need to get stricter on the input */
665 if(bps == 24 || bps == 32) {
667 /* let these slide with a warning since they're unambiguous */
668 flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file has format type %u but bits-per-sample=%u\n", encoder_session.inbasefilename, (unsigned)format, bps);
669 #if 0 /* reinstate if we need to get stricter on the input */
672 flac__utils_printf(stderr, 1, "%s: ERROR: legacy WAVE file has format type %u but bits-per-sample=%u\n", encoder_session.inbasefilename, (unsigned)format, bps);
673 return EncoderSession_finish_error(&encoder_session);
677 if((bps+7)/8 * channels == block_align) {
679 /* assume legacy file is block aligned with some LSBs zero; this is checked for in format_input() */
680 flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", encoder_session.inbasefilename, (unsigned)format, block_align, bps, channels);
681 shift = 8 - (bps % 8);
688 flac__utils_printf(stderr, 1, "%s: ERROR: illegal WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", encoder_session.inbasefilename, (unsigned)format, block_align, bps, channels);
689 return EncoderSession_finish_error(&encoder_session);
691 FLAC__ASSERT(data_bytes >= 16);
695 if(data_bytes < 40) {
696 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE sub-chunk with size %u\n", encoder_session.inbasefilename, data_bytes);
697 return EncoderSession_finish_error(&encoder_session);
700 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
701 return EncoderSession_finish_error(&encoder_session);
703 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE sub-chunk with cbSize %u\n", encoder_session.inbasefilename, (unsigned)x);
704 return EncoderSession_finish_error(&encoder_session);
707 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
708 return EncoderSession_finish_error(&encoder_session);
709 if((unsigned)x > bps) {
710 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE sub-chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", encoder_session.inbasefilename, (unsigned)x, bps);
711 return EncoderSession_finish_error(&encoder_session);
713 shift = bps - (unsigned)x;
715 if(!read_little_endian_uint32(infile, &channel_mask, false, encoder_session.inbasefilename))
716 return EncoderSession_finish_error(&encoder_session);
717 /* for mono/stereo and unassigned channels, we fake the mask */
718 if(channel_mask == 0) {
720 channel_mask = 0x0001;
721 else if(channels == 2)
722 channel_mask = 0x0003;
724 if(channel_mask != 0x0001 && channel_mask != 0x0003 && channel_mask != 0x003f && channel_mask != 0x060f) {
725 flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE sub-chunk with unsupported channel mask=0x%04X and #channels=%u\n", encoder_session.inbasefilename, (unsigned)channel_mask, channels);
726 return EncoderSession_finish_error(&encoder_session);
728 if(count_channel_mask_bits(channel_mask) < channels) {
729 flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE sub-chunk: channel mask 0x%04X has unassigned channels (#channels=%u)\n", encoder_session.inbasefilename, channel_mask, channels);
730 return EncoderSession_finish_error(&encoder_session);
732 else if(count_channel_mask_bits(channel_mask) > channels)
733 channel_mask = limit_channel_mask(channel_mask, channels);
734 /* first part of GUID */
735 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
736 return EncoderSession_finish_error(&encoder_session);
738 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE sub-chunk with non-PCM format %u\n", encoder_session.inbasefilename, (unsigned)x);
739 return EncoderSession_finish_error(&encoder_session);
744 if(bps-shift < 4 || bps-shift > 24) {
745 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, bps-shift);
746 return EncoderSession_finish_error(&encoder_session);
748 else if(options.common.sector_align && bps-shift != 16) {
749 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, bps-shift);
750 return EncoderSession_finish_error(&encoder_session);
753 /* skip any extra data in the fmt sub-chunk */
754 if(!fskip_ahead(infile, data_bytes)) {
755 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping extra 'fmt' data\n", encoder_session.inbasefilename);
756 return EncoderSession_finish_error(&encoder_session);
760 * now that we know the sample rate, canonicalize the
761 * --skip string to a number of samples:
763 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, sample_rate);
764 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
765 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
766 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
768 got_fmt_chunk = true;
770 else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
771 FLAC__uint64 total_samples_in_input, trim = 0;
772 FLAC__bool pad = false;
776 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
777 return EncoderSession_finish_error(&encoder_session);
779 pad = (data_bytes & 1U) ? true : false;
781 bytes_per_wide_sample = channels * (bps >> 3);
783 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
784 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
785 total_samples_in_input = data_bytes / bytes_per_wide_sample + *options.common.align_reservoir_samples;
788 * now that we know the input size, canonicalize the
789 * --until string to an absolute sample number:
791 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, sample_rate, encoder_session.skip, total_samples_in_input))
792 return EncoderSession_finish_error(&encoder_session);
793 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
794 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
796 if(encoder_session.skip > 0) {
797 if(!fskip_ahead(infile, encoder_session.skip * bytes_per_wide_sample)) {
798 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
799 return EncoderSession_finish_error(&encoder_session);
803 data_bytes -= (unsigned)encoder_session.skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
804 encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
805 if(encoder_session.until > 0) {
806 trim = total_samples_in_input - encoder_session.until;
807 FLAC__ASSERT(total_samples_in_input > 0);
808 FLAC__ASSERT(!options.common.sector_align);
809 data_bytes -= (unsigned int)trim * bytes_per_wide_sample;
810 encoder_session.total_samples_to_encode -= trim;
812 if(options.common.sector_align) {
813 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
814 if(options.common.is_last_file)
815 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
817 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
820 /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
821 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample + 44;
823 if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps-shift, sample_rate, /*flac_decoder_data=*/0))
824 return EncoderSession_finish_error(&encoder_session);
827 * first do any samples in the reservoir
829 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
830 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
831 print_error_with_state(&encoder_session, "ERROR during encoding");
832 return EncoderSession_finish_error(&encoder_session);
837 * decrement the data_bytes counter if we need to align the file
839 if(options.common.sector_align) {
840 if(options.common.is_last_file) {
841 *options.common.align_reservoir_samples = 0;
844 *options.common.align_reservoir_samples = align_remainder;
845 data_bytes -= (*options.common.align_reservoir_samples) * bytes_per_wide_sample;
850 * now do from the file
852 while(data_bytes > 0) {
853 bytes_read = fread(ucbuffer_, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
854 if(bytes_read == 0) {
856 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
857 return EncoderSession_finish_error(&encoder_session);
859 else if(feof(infile)) {
860 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
865 if(bytes_read % bytes_per_wide_sample != 0) {
866 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
867 return EncoderSession_finish_error(&encoder_session);
870 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
871 if(!format_input(input_, wide_samples, /*is_big_endian=*/false, is_unsigned_samples, channels, bps, shift))
872 return EncoderSession_finish_error(&encoder_session);
874 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
875 print_error_with_state(&encoder_session, "ERROR during encoding");
876 return EncoderSession_finish_error(&encoder_session);
878 data_bytes -= bytes_read;
884 FLAC__ASSERT(!options.common.sector_align);
885 if(!fskip_ahead(infile, trim * bytes_per_wide_sample)) {
886 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
887 return EncoderSession_finish_error(&encoder_session);
892 * now read unaligned samples into reservoir or pad with zeroes if necessary
894 if(options.common.sector_align) {
895 if(options.common.is_last_file) {
896 unsigned wide_samples = 588 - align_remainder;
897 if(wide_samples < 588) {
900 info_align_zero = wide_samples;
901 for(channel = 0; channel < channels; channel++)
902 memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
904 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
905 print_error_with_state(&encoder_session, "ERROR during encoding");
906 return EncoderSession_finish_error(&encoder_session);
911 if(*options.common.align_reservoir_samples > 0) {
912 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
913 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
914 if(bytes_read == 0 && ferror(infile)) {
915 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
916 return EncoderSession_finish_error(&encoder_session);
918 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
919 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
922 info_align_carry = *options.common.align_reservoir_samples;
923 if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, /*is_big_endian=*/false, is_unsigned_samples, channels, bps, shift))
924 return EncoderSession_finish_error(&encoder_session);
933 if(fread(&tmp, 1U, 1U, infile) < 1U) {
934 flac__utils_printf(stderr, 1, "%s: ERROR during read of data pad byte\n", encoder_session.inbasefilename);
935 return EncoderSession_finish_error(&encoder_session);
939 got_data_chunk = true;
942 if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
943 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_session.inbasefilename);
945 else if(xx == 0x61746164) { /* "data" */
947 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_session.inbasefilename);
949 else if(!got_fmt_chunk) {
950 flac__utils_printf(stderr, 1, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_session.inbasefilename);
951 return EncoderSession_finish_error(&encoder_session);
958 flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown sub-chunk '%c%c%c%c'\n", encoder_session.inbasefilename, (char)(xx&255), (char)((xx>>8)&255), (char)((xx>>16)&255), (char)(xx>>24));
961 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
962 return EncoderSession_finish_error(&encoder_session);
964 unsigned long skip = xx+(xx & 1U);
966 FLAC__ASSERT(skip<=LONG_MAX);
967 if(!fskip_ahead(infile, skip)) {
968 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_session.inbasefilename);
969 return EncoderSession_finish_error(&encoder_session);
975 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
978 int flac__encode_raw(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, raw_encode_options_t options)
980 EncoderSession encoder_session;
982 const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
983 unsigned align_remainder = 0;
984 int info_align_carry = -1, info_align_zero = -1;
985 FLAC__uint64 total_samples_in_input = 0;
987 FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
988 FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
989 FLAC__ASSERT(!options.common.sector_align || options.sample_rate == 44100);
990 FLAC__ASSERT(!options.common.sector_align || infilesize >= 0);
991 FLAC__ASSERT(!options.common.replay_gain || options.channels <= 2);
992 FLAC__ASSERT(!options.common.replay_gain || grabbag__replaygain_is_valid_sample_frequency(options.sample_rate));
995 EncoderSession_construct(
998 options.common.use_ogg,
1002 options.common.verify,
1011 * now that we know the sample rate, canonicalize the
1012 * --skip string to a number of samples:
1014 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, options.sample_rate);
1015 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
1016 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
1017 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
1020 total_samples_in_input = 0;
1022 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
1023 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
1024 total_samples_in_input = (FLAC__uint64)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
1028 * now that we know the input size, canonicalize the
1029 * --until strings to a number of samples:
1031 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, options.sample_rate, encoder_session.skip, total_samples_in_input))
1032 return EncoderSession_finish_error(&encoder_session);
1033 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
1034 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
1036 infilesize -= (off_t)encoder_session.skip * bytes_per_wide_sample;
1037 encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
1038 if(encoder_session.until > 0) {
1039 const FLAC__uint64 trim = total_samples_in_input - encoder_session.until;
1040 FLAC__ASSERT(total_samples_in_input > 0);
1041 FLAC__ASSERT(!options.common.sector_align);
1042 infilesize -= (off_t)trim * bytes_per_wide_sample;
1043 encoder_session.total_samples_to_encode -= trim;
1045 if(infilesize >= 0 && options.common.sector_align) {
1046 FLAC__ASSERT(encoder_session.skip == 0);
1047 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
1048 if(options.common.is_last_file)
1049 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
1051 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
1053 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample;
1055 if(encoder_session.total_samples_to_encode <= 0)
1056 flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n");
1058 if(encoder_session.skip > 0) {
1059 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)encoder_session.skip;
1060 if(skip_bytes > lookahead_length) {
1061 skip_bytes -= lookahead_length;
1062 lookahead_length = 0;
1063 if(!fskip_ahead(infile, skip_bytes)) {
1064 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1065 return EncoderSession_finish_error(&encoder_session);
1069 lookahead += skip_bytes;
1070 lookahead_length -= skip_bytes;
1074 if(!EncoderSession_init_encoder(&encoder_session, options.common, options.channels, options.bps, options.sample_rate, /*flac_decoder_data=*/0))
1075 return EncoderSession_finish_error(&encoder_session);
1078 * first do any samples in the reservoir
1080 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
1081 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
1082 print_error_with_state(&encoder_session, "ERROR during encoding");
1083 return EncoderSession_finish_error(&encoder_session);
1088 * decrement infilesize if we need to align the file
1090 if(options.common.sector_align) {
1091 FLAC__ASSERT(infilesize >= 0);
1092 if(options.common.is_last_file) {
1093 *options.common.align_reservoir_samples = 0;
1096 *options.common.align_reservoir_samples = align_remainder;
1097 infilesize -= (off_t)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
1098 FLAC__ASSERT(infilesize >= 0);
1103 * now do from the file
1105 if(infilesize < 0) {
1106 while(!feof(infile)) {
1107 if(lookahead_length > 0) {
1108 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1109 memcpy(ucbuffer_, lookahead, lookahead_length);
1110 bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
1111 if(ferror(infile)) {
1112 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1113 return EncoderSession_finish_error(&encoder_session);
1115 lookahead_length = 0;
1118 bytes_read = fread(ucbuffer_, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
1120 if(bytes_read == 0) {
1121 if(ferror(infile)) {
1122 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1123 return EncoderSession_finish_error(&encoder_session);
1126 else if(bytes_read % bytes_per_wide_sample != 0) {
1127 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1128 return EncoderSession_finish_error(&encoder_session);
1131 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1132 if(!format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0))
1133 return EncoderSession_finish_error(&encoder_session);
1135 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1136 print_error_with_state(&encoder_session, "ERROR during encoding");
1137 return EncoderSession_finish_error(&encoder_session);
1143 const FLAC__uint64 max_input_bytes = infilesize;
1144 FLAC__uint64 total_input_bytes_read = 0;
1145 while(total_input_bytes_read < max_input_bytes) {
1147 size_t wanted = (CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1148 wanted = (size_t) min((FLAC__uint64)wanted, max_input_bytes - total_input_bytes_read);
1150 if(lookahead_length > 0) {
1151 FLAC__ASSERT(lookahead_length <= wanted);
1152 memcpy(ucbuffer_, lookahead, lookahead_length);
1153 wanted -= lookahead_length;
1154 bytes_read = lookahead_length;
1156 bytes_read += fread(ucbuffer_+lookahead_length, sizeof(unsigned char), wanted, infile);
1157 if(ferror(infile)) {
1158 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1159 return EncoderSession_finish_error(&encoder_session);
1162 lookahead_length = 0;
1165 bytes_read = fread(ucbuffer_, sizeof(unsigned char), wanted, infile);
1168 if(bytes_read == 0) {
1169 if(ferror(infile)) {
1170 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1171 return EncoderSession_finish_error(&encoder_session);
1173 else if(feof(infile)) {
1174 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
1175 total_input_bytes_read = max_input_bytes;
1179 if(bytes_read % bytes_per_wide_sample != 0) {
1180 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1181 return EncoderSession_finish_error(&encoder_session);
1184 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1185 if(!format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0))
1186 return EncoderSession_finish_error(&encoder_session);
1188 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1189 print_error_with_state(&encoder_session, "ERROR during encoding");
1190 return EncoderSession_finish_error(&encoder_session);
1192 total_input_bytes_read += bytes_read;
1199 * now read unaligned samples into reservoir or pad with zeroes if necessary
1201 if(options.common.sector_align) {
1202 if(options.common.is_last_file) {
1203 unsigned wide_samples = 588 - align_remainder;
1204 if(wide_samples < 588) {
1207 info_align_zero = wide_samples;
1208 for(channel = 0; channel < options.channels; channel++)
1209 memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
1211 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1212 print_error_with_state(&encoder_session, "ERROR during encoding");
1213 return EncoderSession_finish_error(&encoder_session);
1218 if(*options.common.align_reservoir_samples > 0) {
1219 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1220 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
1221 if(bytes_read == 0 && ferror(infile)) {
1222 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1223 return EncoderSession_finish_error(&encoder_session);
1225 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
1226 flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
1229 info_align_carry = *options.common.align_reservoir_samples;
1230 if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0))
1231 return EncoderSession_finish_error(&encoder_session);
1237 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
1240 int flac__encode_flac(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, flac_encode_options_t options)
1242 EncoderSession encoder_session;
1243 FLAC__StreamDecoder *decoder = 0;
1244 FLACDecoderData decoder_data;
1249 EncoderSession_construct(
1251 #ifdef FLAC__HAS_OGG
1252 options.common.use_ogg,
1256 options.common.verify,
1264 decoder_data.encoder_session = &encoder_session;
1265 decoder_data.filesize = (infilesize == (off_t)(-1)? 0 : infilesize);
1266 decoder_data.lookahead = lookahead;
1267 decoder_data.lookahead_length = lookahead_length;
1268 decoder_data.num_metadata_blocks = 0;
1269 decoder_data.samples_left_to_process = 0;
1270 decoder_data.fatal_error = false;
1273 * set up FLAC decoder for the input
1275 if (0 == (decoder = FLAC__stream_decoder_new())) {
1276 flac__utils_printf(stderr, 1, "%s: ERROR: creating decoder for FLAC input\n", encoder_session.inbasefilename);
1277 return EncoderSession_finish_error(&encoder_session);
1280 FLAC__stream_decoder_set_md5_checking(decoder, false) &&
1281 FLAC__stream_decoder_set_metadata_respond_all(decoder)
1283 flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", encoder_session.inbasefilename);
1284 goto fubar1; /*@@@ yuck */
1287 if (FLAC__stream_decoder_init_stream(decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/&decoder_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
1288 flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
1289 goto fubar1; /*@@@ yuck */
1292 if (!FLAC__stream_decoder_process_until_end_of_metadata(decoder) || decoder_data.fatal_error) {
1293 if (decoder_data.fatal_error)
1294 flac__utils_printf(stderr, 1, "%s: ERROR: out of memory or too many metadata blocks while reading metadata in FLAC input\n", encoder_session.inbasefilename);
1296 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
1297 goto fubar1; /*@@@ yuck */
1300 if (decoder_data.num_metadata_blocks == 0) {
1301 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, got no metadata blocks\n", encoder_session.inbasefilename);
1302 goto fubar2; /*@@@ yuck */
1304 else if (decoder_data.metadata_blocks[0]->type != FLAC__METADATA_TYPE_STREAMINFO) {
1305 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, first metadata block is not STREAMINFO\n", encoder_session.inbasefilename);
1306 goto fubar2; /*@@@ yuck */
1308 else if (decoder_data.metadata_blocks[0]->data.stream_info.total_samples == 0) {
1309 flac__utils_printf(stderr, 1, "%s: ERROR: FLAC input has STREAMINFO with unknown total samples which is not supported\n", encoder_session.inbasefilename);
1310 goto fubar2; /*@@@ yuck */
1314 * now that we have the STREAMINFO and know the sample rate,
1315 * canonicalize the --skip string to a number of samples:
1317 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate);
1318 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
1319 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
1320 FLAC__ASSERT(!options.common.sector_align); /* --sector-align with FLAC input is not supported */
1323 FLAC__uint64 total_samples_in_input, trim = 0;
1325 total_samples_in_input = decoder_data.metadata_blocks[0]->data.stream_info.total_samples;
1328 * now that we know the input size, canonicalize the
1329 * --until string to an absolute sample number:
1331 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate, encoder_session.skip, total_samples_in_input))
1332 goto fubar2; /*@@@ yuck */
1333 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
1335 encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
1336 if(encoder_session.until > 0) {
1337 trim = total_samples_in_input - encoder_session.until;
1338 FLAC__ASSERT(total_samples_in_input > 0);
1339 encoder_session.total_samples_to_encode -= trim;
1342 encoder_session.unencoded_size = decoder_data.filesize;
1344 if(!EncoderSession_init_encoder(&encoder_session, options.common, decoder_data.metadata_blocks[0]->data.stream_info.channels, decoder_data.metadata_blocks[0]->data.stream_info.bits_per_sample, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate, &decoder_data))
1345 return EncoderSession_finish_error(&encoder_session);
1348 * have to wait until the FLAC encoder is set up for writing
1349 * before any seeking in the input FLAC file, because the seek
1350 * itself will usually call the decoder's write callback, and
1351 * our decoder's write callback passes samples to our FLAC
1354 decoder_data.samples_left_to_process = encoder_session.total_samples_to_encode;
1355 if(encoder_session.skip > 0) {
1356 if(!FLAC__stream_decoder_seek_absolute(decoder, encoder_session.skip)) {
1357 flac__utils_printf(stderr, 1, "%s: ERROR while skipping samples, FLAC decoder state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
1358 goto fubar2; /*@@@ yuck */
1363 * now do samples from the file
1365 while(!decoder_data.fatal_error && decoder_data.samples_left_to_process > 0) {
1366 if(!FLAC__stream_decoder_process_single(decoder)) {
1367 flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
1368 goto fubar2; /*@@@ yuck */
1373 FLAC__stream_decoder_delete(decoder);
1374 retval = EncoderSession_finish_ok(&encoder_session, -1, -1);
1375 /* have to wail until encoder is completely finished before deleting because of the final step of writing the seekpoint offsets */
1376 for(i = 0; i < decoder_data.num_metadata_blocks; i++)
1377 free(decoder_data.metadata_blocks[i]);
1381 for(i = 0; i < decoder_data.num_metadata_blocks; i++)
1382 free(decoder_data.metadata_blocks[i]);
1384 FLAC__stream_decoder_delete(decoder);
1385 return EncoderSession_finish_error(&encoder_session);
1388 FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FILE *infile, const char *infilename, const char *outfilename)
1391 FLAC__uint32 test = 1;
1394 * initialize globals
1397 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
1399 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1400 input_[i] = &(in_[i][0]);
1404 * initialize instance
1407 #ifdef FLAC__HAS_OGG
1408 e->use_ogg = use_ogg;
1414 e->is_stdout = (0 == strcmp(outfilename, "-"));
1416 e->inbasefilename = grabbag__file_get_basename(infilename);
1417 e->outfilename = outfilename;
1419 e->skip = 0; /* filled in later after the sample_rate is known */
1420 e->unencoded_size = 0;
1421 e->total_samples_to_encode = 0;
1422 e->bytes_written = 0;
1423 e->samples_written = 0;
1427 e->encoder.flac = 0;
1428 #ifdef FLAC__HAS_OGG
1433 e->seek_table_template = 0;
1435 if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1436 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1440 #ifdef FLAC__HAS_OGG
1442 e->encoder.ogg = OggFLAC__stream_encoder_new();
1443 if(0 == e->encoder.ogg) {
1444 flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1445 EncoderSession_destroy(e);
1451 e->encoder.flac = FLAC__stream_encoder_new();
1452 if(0 == e->encoder.flac) {
1453 flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1454 EncoderSession_destroy(e);
1461 void EncoderSession_destroy(EncoderSession *e)
1466 #ifdef FLAC__HAS_OGG
1468 if(0 != e->encoder.ogg) {
1469 OggFLAC__stream_encoder_delete(e->encoder.ogg);
1475 if(0 != e->encoder.flac) {
1476 FLAC__stream_encoder_delete(e->encoder.flac);
1477 e->encoder.flac = 0;
1480 if(0 != e->seek_table_template) {
1481 FLAC__metadata_object_delete(e->seek_table_template);
1482 e->seek_table_template = 0;
1486 int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero)
1488 FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1491 #ifdef FLAC__HAS_OGG
1493 if(e->encoder.ogg) {
1494 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg);
1495 OggFLAC__stream_encoder_finish(e->encoder.ogg);
1500 if(e->encoder.flac) {
1501 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac);
1502 FLAC__stream_encoder_finish(e->encoder.flac);
1505 if(e->total_samples_to_encode > 0) {
1507 flac__utils_printf(stderr, 2, "\n");
1510 if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) {
1511 print_verify_error(e);
1515 if(info_align_carry >= 0) {
1516 flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d samples to be carried over\n", e->inbasefilename, info_align_carry);
1518 if(info_align_zero >= 0) {
1519 flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d zero samples to be appended\n", e->inbasefilename, info_align_zero);
1523 EncoderSession_destroy(e);
1528 int EncoderSession_finish_error(EncoderSession *e)
1530 FLAC__StreamEncoderState fse_state;
1532 if(e->total_samples_to_encode > 0)
1533 flac__utils_printf(stderr, 2, "\n");
1535 #ifdef FLAC__HAS_OGG
1537 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg);
1542 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac);
1545 if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1546 print_verify_error(e);
1548 /*@@@@@@@@@ BUG: if error was caused because the output file already exists but the file encoder could not write on top of it (i.e. it's not writable), this will delete the pre-existing file, which is not what we want */
1549 unlink(e->outfilename);
1551 EncoderSession_destroy(e);
1556 FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, FLACDecoderData *flac_decoder_data)
1558 unsigned num_metadata, i;
1559 FLAC__StreamMetadata padding, *cuesheet = 0;
1560 FLAC__StreamMetadata *static_metadata[4+64]; /* MAGIC +64 is for pictures metadata in options.pictures */
1561 FLAC__StreamMetadata **metadata = static_metadata;
1562 FLAC__StreamEncoderInitStatus init_status;
1563 const FLAC__bool is_cdda = (channels == 1 || channels == 2) && (bps == 16) && (sample_rate == 44100);
1565 FLAC__ASSERT(sizeof(options.pictures)/sizeof(options.pictures[0]) <= 64);
1567 e->replay_gain = options.replay_gain;
1568 e->channels = channels;
1569 e->bits_per_sample = bps;
1570 e->sample_rate = sample_rate;
1572 if(e->replay_gain) {
1573 if(channels != 1 && channels != 2) {
1574 flac__utils_printf(stderr, 1, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
1577 if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) {
1578 flac__utils_printf(stderr, 1, "%s: ERROR, invalid sample rate (%u) for --replay-gain\n", e->inbasefilename, sample_rate);
1581 if(options.is_first_file) {
1582 if(!grabbag__replaygain_init(sample_rate)) {
1583 flac__utils_printf(stderr, 1, "%s: ERROR initializing ReplayGain stage\n", e->inbasefilename);
1590 options.do_mid_side = options.loose_mid_side = false;
1592 if(!parse_cuesheet(&cuesheet, options.cuesheet_filename, e->inbasefilename, is_cdda, e->total_samples_to_encode))
1595 if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? cuesheet : 0, e)) {
1596 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1598 FLAC__metadata_object_delete(cuesheet);
1602 if(flac_decoder_data) {
1604 * we're encoding from FLAC so we will use the FLAC file's
1605 * metadata as the basic for the encoded file
1609 * first handle padding: if --no-padding was specified,
1610 * then delete all padding; else if -P was specified,
1611 * use that instead of existing padding (if any); else
1612 * if existing file has padding, move all existing
1613 * padding blocks to one padding block at the end; else
1614 * use default padding.
1618 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1619 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_PADDING) {
1622 p += flac_decoder_data->metadata_blocks[i]->length;
1623 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1624 flac_decoder_data->metadata_blocks[i] = 0;
1627 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1629 flac_decoder_data->num_metadata_blocks = j;
1630 if(options.padding > 0)
1631 p = options.padding;
1633 p = e->total_samples_to_encode / e->sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8;
1634 if(options.padding != 0) {
1635 if(p > 0 && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1636 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
1637 if(0 == flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]) {
1638 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PADDING block\n", e->inbasefilename);
1640 FLAC__metadata_object_delete(cuesheet);
1643 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->is_last = false; /* the encoder will set this for us */
1644 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->length = p;
1645 flac_decoder_data->num_metadata_blocks++;
1651 * next handle vorbis comment: if any tags were specified
1652 * or there is no existing vorbis comment, we create a
1653 * new vorbis comment (discarding any existing one); else
1654 * we keep the existing one
1657 FLAC__bool vc_found = false;
1658 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1659 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
1661 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT && options.vorbis_comment->data.vorbis_comment.num_comments > 0) {
1662 if(options.vorbis_comment->data.vorbis_comment.num_comments > 0)
1663 flac__utils_printf(stderr, 1, "%s: WARNING, replacing tags from input FLAC file with those given on the command-line\n", e->inbasefilename);
1664 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1665 flac_decoder_data->metadata_blocks[i] = 0;
1668 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1670 flac_decoder_data->num_metadata_blocks = j;
1671 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])) {
1673 FLAC__StreamMetadata *vc = FLAC__metadata_object_clone(options.vorbis_comment);
1675 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for VORBIS_COMMENT block\n", e->inbasefilename);
1677 FLAC__metadata_object_delete(cuesheet);
1680 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1681 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1682 flac_decoder_data->metadata_blocks[1] = vc;
1683 flac_decoder_data->num_metadata_blocks++;
1688 * next handle cuesheet: if --cuesheet was specified, use
1689 * it; else if file has existing CUESHEET and cuesheet's
1690 * lead-out offset is correct, keep it; else no CUESHEET
1693 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1694 FLAC__bool existing_cuesheet_is_bad = false;
1695 /* check if existing cuesheet matches the input audio */
1696 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && 0 == cuesheet) {
1697 const FLAC__StreamMetadata_CueSheet *cs = &flac_decoder_data->metadata_blocks[i]->data.cue_sheet;
1698 if(e->total_samples_to_encode == 0) {
1699 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);
1700 existing_cuesheet_is_bad = true;
1702 else if(e->total_samples_to_encode != cs->tracks[cs->num_tracks-1].offset) {
1703 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);
1704 existing_cuesheet_is_bad = true;
1707 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && (existing_cuesheet_is_bad || 0 != cuesheet)) {
1709 flac__utils_printf(stderr, 1, "%s: WARNING, replacing cuesheet in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1710 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1711 flac_decoder_data->metadata_blocks[i] = 0;
1714 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1716 flac_decoder_data->num_metadata_blocks = j;
1717 if(0 != cuesheet && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1719 FLAC__StreamMetadata *cs = FLAC__metadata_object_clone(cuesheet);
1721 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for CUESHEET block\n", e->inbasefilename);
1723 FLAC__metadata_object_delete(cuesheet);
1726 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1727 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1728 flac_decoder_data->metadata_blocks[1] = cs;
1729 flac_decoder_data->num_metadata_blocks++;
1734 * finally handle seektable: if -S- was specified, no
1735 * SEEKTABLE; else if -S was specified, use it/them;
1736 * else if file has existing SEEKTABLE and input size is
1737 * preserved (no --skip/--until/etc specified), keep it;
1738 * else use default seektable options
1740 * note: meanings of num_requested_seek_points:
1741 * -1 : no -S option given, default to some value
1742 * 0 : -S- given (no seektable)
1743 * >0 : one or more -S options given
1746 FLAC__bool existing_seektable = false;
1747 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1748 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE)
1749 existing_seektable = true;
1750 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)) {
1751 if(options.num_requested_seek_points > 0)
1752 flac__utils_printf(stderr, 1, "%s: WARNING, replacing seektable in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1753 else if(options.num_requested_seek_points == 0)
1754 ; /* no warning, silently delete existing SEEKTABLE since user specified --no-seektable (-S-) */
1756 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);
1757 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1758 flac_decoder_data->metadata_blocks[i] = 0;
1759 existing_seektable = false;
1762 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1764 flac_decoder_data->num_metadata_blocks = j;
1765 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])) {
1767 FLAC__StreamMetadata *st = FLAC__metadata_object_clone(e->seek_table_template);
1769 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for SEEKTABLE block\n", e->inbasefilename);
1771 FLAC__metadata_object_delete(cuesheet);
1774 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1775 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1776 flac_decoder_data->metadata_blocks[1] = st;
1777 flac_decoder_data->num_metadata_blocks++;
1780 metadata = &flac_decoder_data->metadata_blocks[1]; /* don't include STREAMINFO */
1781 num_metadata = flac_decoder_data->num_metadata_blocks - 1;
1785 * we're not encoding from FLAC so we will build the metadata
1789 if(e->seek_table_template->data.seek_table.num_points > 0) {
1790 e->seek_table_template->is_last = false; /* the encoder will set this for us */
1791 metadata[num_metadata++] = e->seek_table_template;
1794 metadata[num_metadata++] = cuesheet;
1795 metadata[num_metadata++] = options.vorbis_comment;
1796 for(i = 0; i < options.num_pictures; i++)
1797 metadata[num_metadata++] = options.pictures[i];
1798 if(options.padding != 0) {
1799 padding.is_last = false; /* the encoder will set this for us */
1800 padding.type = FLAC__METADATA_TYPE_PADDING;
1801 padding.length = (unsigned)(options.padding>0? options.padding : (e->total_samples_to_encode / e->sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8));
1802 metadata[num_metadata++] = &padding;
1806 /* check for a few things that have not already been checked. the
1807 * FLAC__stream_encoder_init*() will check it but only return
1808 * FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA so we check some
1809 * up front to give a better error message.
1811 if(!verify_metadata(e, metadata, num_metadata)) {
1813 FLAC__metadata_object_delete(cuesheet);
1817 e->blocksize = options.blocksize;
1818 e->stats_mask = (options.do_exhaustive_model_search || options.do_qlp_coeff_prec_search)? 0x0f : 0x3f;
1820 #ifdef FLAC__HAS_OGG
1822 OggFLAC__stream_encoder_set_serial_number(e->encoder.ogg, options.serial_number);
1823 OggFLAC__stream_encoder_set_verify(e->encoder.ogg, options.verify);
1824 OggFLAC__stream_encoder_set_streamable_subset(e->encoder.ogg, !options.lax);
1825 OggFLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.ogg, options.do_mid_side);
1826 OggFLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.ogg, options.loose_mid_side);
1827 OggFLAC__stream_encoder_set_channels(e->encoder.ogg, channels);
1828 OggFLAC__stream_encoder_set_bits_per_sample(e->encoder.ogg, bps);
1829 OggFLAC__stream_encoder_set_sample_rate(e->encoder.ogg, sample_rate);
1830 OggFLAC__stream_encoder_set_blocksize(e->encoder.ogg, options.blocksize);
1831 OggFLAC__stream_encoder_set_apodization(e->encoder.ogg, options.apodizations);
1832 OggFLAC__stream_encoder_set_max_lpc_order(e->encoder.ogg, options.max_lpc_order);
1833 OggFLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.ogg, options.qlp_coeff_precision);
1834 OggFLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg, options.do_qlp_coeff_prec_search);
1835 OggFLAC__stream_encoder_set_do_escape_coding(e->encoder.ogg, options.do_escape_coding);
1836 OggFLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.ogg, options.do_exhaustive_model_search);
1837 OggFLAC__stream_encoder_set_min_residual_partition_order(e->encoder.ogg, options.min_residual_partition_order);
1838 OggFLAC__stream_encoder_set_max_residual_partition_order(e->encoder.ogg, options.max_residual_partition_order);
1839 OggFLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.ogg, options.rice_parameter_search_dist);
1840 OggFLAC__stream_encoder_set_total_samples_estimate(e->encoder.ogg, e->total_samples_to_encode);
1841 OggFLAC__stream_encoder_set_metadata(e->encoder.ogg, (num_metadata > 0)? metadata : 0, num_metadata);
1843 OggFLAC__stream_encoder_disable_constant_subframes(e->encoder.ogg, options.debug.disable_constant_subframes);
1844 OggFLAC__stream_encoder_disable_fixed_subframes(e->encoder.ogg, options.debug.disable_fixed_subframes);
1845 OggFLAC__stream_encoder_disable_verbatim_subframes(e->encoder.ogg, options.debug.disable_verbatim_subframes);
1847 init_status = OggFLAC__stream_encoder_init_file(e->encoder.ogg, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
1848 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1849 print_error_with_init_status(e, "ERROR initializing encoder", init_status);
1851 FLAC__metadata_object_delete(cuesheet);
1858 FLAC__stream_encoder_set_verify(e->encoder.flac, options.verify);
1859 FLAC__stream_encoder_set_streamable_subset(e->encoder.flac, !options.lax);
1860 FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.flac, options.do_mid_side);
1861 FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.flac, options.loose_mid_side);
1862 FLAC__stream_encoder_set_channels(e->encoder.flac, channels);
1863 FLAC__stream_encoder_set_bits_per_sample(e->encoder.flac, bps);
1864 FLAC__stream_encoder_set_sample_rate(e->encoder.flac, sample_rate);
1865 FLAC__stream_encoder_set_blocksize(e->encoder.flac, options.blocksize);
1866 FLAC__stream_encoder_set_apodization(e->encoder.flac, options.apodizations);
1867 FLAC__stream_encoder_set_max_lpc_order(e->encoder.flac, options.max_lpc_order);
1868 FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.flac, options.qlp_coeff_precision);
1869 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac, options.do_qlp_coeff_prec_search);
1870 FLAC__stream_encoder_set_do_escape_coding(e->encoder.flac, options.do_escape_coding);
1871 FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.flac, options.do_exhaustive_model_search);
1872 FLAC__stream_encoder_set_min_residual_partition_order(e->encoder.flac, options.min_residual_partition_order);
1873 FLAC__stream_encoder_set_max_residual_partition_order(e->encoder.flac, options.max_residual_partition_order);
1874 FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.flac, options.rice_parameter_search_dist);
1875 FLAC__stream_encoder_set_total_samples_estimate(e->encoder.flac, e->total_samples_to_encode);
1876 FLAC__stream_encoder_set_metadata(e->encoder.flac, (num_metadata > 0)? metadata : 0, num_metadata);
1878 FLAC__stream_encoder_disable_constant_subframes(e->encoder.flac, options.debug.disable_constant_subframes);
1879 FLAC__stream_encoder_disable_fixed_subframes(e->encoder.flac, options.debug.disable_fixed_subframes);
1880 FLAC__stream_encoder_disable_verbatim_subframes(e->encoder.flac, options.debug.disable_verbatim_subframes);
1882 init_status = FLAC__stream_encoder_init_file(e->encoder.flac, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
1883 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1884 print_error_with_init_status(e, "ERROR initializing encoder", init_status);
1886 FLAC__metadata_object_delete(cuesheet);
1892 FLAC__metadata_object_delete(cuesheet);
1897 FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples)
1899 if(e->replay_gain) {
1900 if(!grabbag__replaygain_analyze(buffer, e->channels==2, e->bits_per_sample, samples)) {
1901 flac__utils_printf(stderr, 1, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename);
1905 #ifdef FLAC__HAS_OGG
1907 return OggFLAC__stream_encoder_process(e->encoder.ogg, buffer, samples);
1910 return FLAC__stream_encoder_process(e->encoder.flac, buffer, samples);
1913 FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e)
1915 const FLAC__bool only_placeholders = e->is_stdout;
1916 FLAC__bool has_real_points;
1918 if(num_requested_seek_points == 0 && 0 == cuesheet)
1921 if(num_requested_seek_points < 0) {
1922 requested_seek_points = "10s;";
1923 num_requested_seek_points = 1;
1926 if(num_requested_seek_points > 0) {
1927 if(!grabbag__seektable_convert_specification_to_template(requested_seek_points, only_placeholders, e->total_samples_to_encode, e->sample_rate, e->seek_table_template, &has_real_points))
1933 const FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet;
1934 for(i = 0; i < cs->num_tracks; i++) {
1935 const FLAC__StreamMetadata_CueSheet_Track *tr = cs->tracks+i;
1936 for(j = 0; j < tr->num_indices; j++) {
1937 if(!FLAC__metadata_object_seektable_template_append_point(e->seek_table_template, tr->offset + tr->indices[j].offset))
1939 has_real_points = true;
1943 if(!FLAC__metadata_object_seektable_template_sort(e->seek_table_template, /*compact=*/true))
1947 if(has_real_points) {
1949 flac__utils_printf(stderr, 1, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename);
1956 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
1958 /* convert from mm:ss.sss to sample number if necessary */
1959 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
1961 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
1962 if(spec->is_relative && spec->value.samples == 0) {
1963 spec->is_relative = false;
1967 /* in any other case the total samples in the input must be known */
1968 if(total_samples_in_input == 0) {
1969 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when input length is unknown\n", inbasefilename);
1973 FLAC__ASSERT(spec->value_is_samples);
1975 /* convert relative specifications to absolute */
1976 if(spec->is_relative) {
1977 if(spec->value.samples <= 0)
1978 spec->value.samples += (FLAC__int64)total_samples_in_input;
1980 spec->value.samples += skip;
1981 spec->is_relative = false;
1985 if(spec->value.samples < 0) {
1986 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
1989 if((FLAC__uint64)spec->value.samples <= skip) {
1990 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
1993 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
1994 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
2001 FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata)
2003 FLAC__bool metadata_picture_has_type1 = false;
2004 FLAC__bool metadata_picture_has_type2 = false;
2007 FLAC__ASSERT(0 != metadata);
2008 for(i = 0; i < num_metadata; i++) {
2009 const FLAC__StreamMetadata *m = metadata[i];
2010 if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
2011 if(!FLAC__format_seektable_is_legal(&m->data.seek_table)) {
2012 flac__utils_printf(stderr, 1, "%s: ERROR: SEEKTABLE metadata block is invalid\n", e->inbasefilename);
2016 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
2017 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0)) {
2018 flac__utils_printf(stderr, 1, "%s: ERROR: CUESHEET metadata block is invalid\n", e->inbasefilename);
2022 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
2023 const char *error = 0;
2024 if(!FLAC__format_picture_is_legal(&m->data.picture, &error)) {
2025 flac__utils_printf(stderr, 1, "%s: ERROR: PICTURE metadata block is invalid: %s\n", e->inbasefilename, error);
2028 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
2029 if(metadata_picture_has_type1) {
2030 flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 1 (32x32 icon) in the file\n", e->inbasefilename);
2033 metadata_picture_has_type1 = true;
2035 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
2036 if(metadata_picture_has_type2) {
2037 flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 2 (icon) in the file\n", e->inbasefilename);
2040 metadata_picture_has_type2 = true;
2048 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)
2050 unsigned wide_sample, sample, channel, byte;
2053 if(is_unsigned_samples) {
2054 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2055 for(channel = 0; channel < channels; channel++, sample++)
2056 dest[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
2059 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2060 for(channel = 0; channel < channels; channel++, sample++)
2061 dest[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
2064 else if(bps == 16) {
2065 if(is_big_endian != is_big_endian_host_) {
2067 const unsigned bytes = wide_samples * channels * (bps >> 3);
2068 for(byte = 0; byte < bytes; byte += 2) {
2069 tmp = ucbuffer_[byte];
2070 ucbuffer_[byte] = ucbuffer_[byte+1];
2071 ucbuffer_[byte+1] = tmp;
2074 if(is_unsigned_samples) {
2075 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2076 for(channel = 0; channel < channels; channel++, sample++)
2077 dest[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
2080 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2081 for(channel = 0; channel < channels; channel++, sample++)
2082 dest[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
2085 else if(bps == 24) {
2086 if(!is_big_endian) {
2088 const unsigned bytes = wide_samples * channels * (bps >> 3);
2089 for(byte = 0; byte < bytes; byte += 3) {
2090 tmp = ucbuffer_[byte];
2091 ucbuffer_[byte] = ucbuffer_[byte+2];
2092 ucbuffer_[byte+2] = tmp;
2095 if(is_unsigned_samples) {
2096 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2097 for(channel = 0; channel < channels; channel++, sample++) {
2098 dest[channel][wide_sample] = ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
2099 dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
2100 dest[channel][wide_sample] |= ucbuffer_[byte++];
2101 dest[channel][wide_sample] -= 0x800000;
2105 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2106 for(channel = 0; channel < channels; channel++, sample++) {
2107 dest[channel][wide_sample] = scbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
2108 dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
2109 dest[channel][wide_sample] |= ucbuffer_[byte++];
2117 FLAC__int32 mask = (1<<shift)-1;
2118 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2119 for(channel = 0; channel < channels; channel++) {
2120 if(dest[channel][wide_sample] & mask) {
2121 flac__utils_printf(stderr, 1, "ERROR during read, sample data (channel#%u sample#%u = %d) has non-zero least-significant bits\n WAVE header said the last %u bits are not significant and should be zero.\n", channel, wide_sample, dest[channel][wide_sample], shift);
2124 dest[channel][wide_sample] >>= shift;
2130 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)
2132 EncoderSession *encoder_session = (EncoderSession*)client_data;
2134 (void)encoder, (void)total_frames_estimate;
2136 encoder_session->bytes_written = bytes_written;
2137 encoder_session->samples_written = samples_written;
2139 if(encoder_session->total_samples_to_encode > 0 && !((frames_written-1) & encoder_session->stats_mask))
2140 print_stats(encoder_session);
2143 FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
2146 FLACDecoderData *data = (FLACDecoderData*)client_data;
2149 if (data->fatal_error)
2150 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2152 /* use up lookahead first */
2153 if (data->lookahead_length) {
2154 n = min(data->lookahead_length, *bytes);
2155 memcpy(buffer, data->lookahead, n);
2157 data->lookahead += n;
2158 data->lookahead_length -= n;
2161 /* get the rest from file */
2163 *bytes = n + fread(buffer, 1, *bytes-n, data->encoder_session->fin);
2164 return ferror(data->encoder_session->fin)? FLAC__STREAM_DECODER_READ_STATUS_ABORT : FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2167 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2170 FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2172 FLACDecoderData *data = (FLACDecoderData*)client_data;
2175 if(fseeko(data->encoder_session->fin, (off_t)absolute_byte_offset, SEEK_SET) < 0)
2176 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
2178 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2181 FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2183 FLACDecoderData *data = (FLACDecoderData*)client_data;
2187 if((pos = ftello(data->encoder_session->fin)) < 0)
2188 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
2190 *absolute_byte_offset = (FLAC__uint64)pos;
2191 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2195 FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2197 FLACDecoderData *data = (FLACDecoderData*)client_data;
2200 if(0 == data->filesize)
2201 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
2203 *stream_length = (FLAC__uint64)data->filesize;
2204 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2208 FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data)
2210 FLACDecoderData *data = (FLACDecoderData*)client_data;
2213 return feof(data->encoder_session->fin)? true : false;
2216 FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
2218 FLACDecoderData *data = (FLACDecoderData*)client_data;
2219 FLAC__uint64 n = min(data->samples_left_to_process, frame->header.blocksize);
2222 if(!EncoderSession_process(data->encoder_session, buffer, (unsigned)n)) {
2223 print_error_with_state(data->encoder_session, "ERROR during encoding");
2224 data->fatal_error = true;
2225 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2228 data->samples_left_to_process -= n;
2229 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2232 void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
2234 FLACDecoderData *data = (FLACDecoderData*)client_data;
2237 if (data->fatal_error)
2241 data->num_metadata_blocks == sizeof(data->metadata_blocks)/sizeof(data->metadata_blocks[0]) ||
2242 0 == (data->metadata_blocks[data->num_metadata_blocks] = FLAC__metadata_object_clone(metadata))
2244 data->fatal_error = true;
2246 data->num_metadata_blocks++;
2249 void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
2251 FLACDecoderData *data = (FLACDecoderData*)client_data;
2254 flac__utils_printf(stderr, 1, "%s: ERROR got %s while decoding FLAC input\n", data->encoder_session->inbasefilename, FLAC__StreamDecoderErrorStatusString[status]);
2255 data->fatal_error = true;
2258 FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset)
2261 unsigned last_line_read;
2262 const char *error_message;
2264 if(0 == cuesheet_filename)
2267 if(lead_out_offset == 0) {
2268 flac__utils_printf(stderr, 1, "%s: ERROR cannot import cuesheet when the number of input samples to encode is unknown\n", inbasefilename);
2272 if(0 == (f = fopen(cuesheet_filename, "r"))) {
2273 flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading: %s\n", inbasefilename, cuesheet_filename, strerror(errno));
2277 *cuesheet = grabbag__cuesheet_parse(f, &error_message, &last_line_read, is_cdda, lead_out_offset);
2281 if(0 == *cuesheet) {
2282 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\" on line %u: %s\n", inbasefilename, cuesheet_filename, last_line_read, error_message);
2286 if(!FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/false, &error_message)) {
2287 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\": %s\n", inbasefilename, cuesheet_filename, error_message);
2291 /* if we're expecting CDDA, warn about non-compliance */
2292 if(is_cdda && !FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/true, &error_message)) {
2293 flac__utils_printf(stderr, 1, "%s: WARNING cuesheet \"%s\" is not audio CD compliant: %s\n", inbasefilename, cuesheet_filename, error_message);
2294 (*cuesheet)->data.cue_sheet.is_cd = false;
2300 void print_stats(const EncoderSession *encoder_session)
2302 const FLAC__uint64 samples_written = min(encoder_session->total_samples_to_encode, encoder_session->samples_written);
2303 #if defined _MSC_VER || defined __MINGW32__
2304 /* with MSVC you have to spoon feed it the casting */
2305 const double progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)encoder_session->total_samples_to_encode;
2306 const double ratio = (double)(FLAC__int64)encoder_session->bytes_written / ((double)(FLAC__int64)encoder_session->unencoded_size * min(1.0, progress));
2308 const double progress = (double)samples_written / (double)encoder_session->total_samples_to_encode;
2309 const double ratio = (double)encoder_session->bytes_written / ((double)encoder_session->unencoded_size * min(1.0, progress));
2313 if(samples_written == encoder_session->total_samples_to_encode) {
2314 flac__utils_printf(stderr, 2, "\r%s:%s wrote %u bytes, ratio=%0.3f",
2315 encoder_session->inbasefilename,
2316 encoder_session->verify? " Verify OK," : "",
2317 (unsigned)encoder_session->bytes_written,
2322 flac__utils_printf(stderr, 2, "\r%s: %u%% complete, ratio=%0.3f", encoder_session->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
2326 void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status)
2328 const int ilen = strlen(e->inbasefilename) + 1;
2329 const char *state_string = "";
2331 flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2333 flac__utils_printf(stderr, 1, "%*s init_status = %s\n", ilen, "", FLAC__StreamEncoderInitStatusString[init_status]);
2335 if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR) {
2336 #ifdef FLAC__HAS_OGG
2338 state_string = OggFLAC__stream_encoder_get_resolved_state_string(e->encoder.ogg);
2341 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder.flac);
2343 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2345 /* print out some more info for some errors: */
2347 0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])
2348 #ifdef FLAC__HAS_OGG
2349 || 0 == strcmp(state_string, OggFLAC__StreamEncoderStateString[OggFLAC__STREAM_ENCODER_CLIENT_ERROR])
2352 flac__utils_printf(stderr, 1,
2354 "An error occurred while writing; the most common cause is that the disk is full.\n"
2358 0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_IO_ERROR])
2359 #ifdef FLAC__HAS_OGG
2360 || 0 == strcmp(state_string, OggFLAC__StreamEncoderStateString[OggFLAC__STREAM_ENCODER_IO_ERROR])
2363 flac__utils_printf(stderr, 1,
2365 "An error occurred opening the output file; it is likely that the output\n"
2366 "directory does not exist or is not writable, the output file already exists and\n"
2367 "is not writable, or the disk is full.\n"
2371 else if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE) {
2372 flac__utils_printf(stderr, 1,
2374 "The encoding parameters specified do not conform to the FLAC Subset and may not\n"
2375 "be streamable or playable in hardware devices. Add --lax to the command-line\n"
2376 "options to encode with these parameters anyway.\n"
2381 void print_error_with_state(const EncoderSession *e, const char *message)
2383 const int ilen = strlen(e->inbasefilename) + 1;
2384 const char *state_string;
2386 flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2388 #ifdef FLAC__HAS_OGG
2390 state_string = OggFLAC__stream_encoder_get_resolved_state_string(e->encoder.ogg);
2393 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder.flac);
2395 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2397 /* print out some more info for some errors: */
2399 0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])
2400 #ifdef FLAC__HAS_OGG
2401 || 0 == strcmp(state_string, OggFLAC__StreamEncoderStateString[OggFLAC__STREAM_ENCODER_CLIENT_ERROR])
2404 flac__utils_printf(stderr, 1,
2406 "An error occurred while writing; the most common cause is that the disk is full.\n"
2411 void print_verify_error(EncoderSession *e)
2413 FLAC__uint64 absolute_sample;
2414 unsigned frame_number;
2417 FLAC__int32 expected;
2420 #ifdef FLAC__HAS_OGG
2422 OggFLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.ogg, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2425 FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.flac, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2427 flac__utils_printf(stderr, 1, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
2428 flac__utils_printf(stderr, 1, " Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)absolute_sample, frame_number, channel, sample, expected, got);
2429 flac__utils_printf(stderr, 1, " In all known cases, verify errors are caused by hardware problems,\n");
2430 flac__utils_printf(stderr, 1, " usually overclocking or bad RAM. Delete %s\n", e->outfilename);
2431 flac__utils_printf(stderr, 1, " and repeat the flac command exactly as before. If it does not give a\n");
2432 flac__utils_printf(stderr, 1, " verify error in the exact same place each time you try it, then there is\n");
2433 flac__utils_printf(stderr, 1, " a problem with your hardware; please see the FAQ:\n");
2434 flac__utils_printf(stderr, 1, " http://flac.sourceforge.net/faq.html#tools__hardware_prob\n");
2435 flac__utils_printf(stderr, 1, " If it does fail in the exact same place every time, keep\n");
2436 flac__utils_printf(stderr, 1, " %s and submit a bug report to:\n", e->outfilename);
2437 flac__utils_printf(stderr, 1, " https://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
2438 flac__utils_printf(stderr, 1, " Make sure to upload the FLAC file and use the \"Monitor\" feature to\n");
2439 flac__utils_printf(stderr, 1, " monitor the bug status.\n");
2440 flac__utils_printf(stderr, 1, "Verify FAILED! Do not trust %s\n", e->outfilename);
2443 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
2445 size_t bytes_read = fread(val, 1, 2, f);
2447 if(bytes_read == 0) {
2449 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2455 else if(bytes_read < 2) {
2456 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2460 if(is_big_endian_host_) {
2461 FLAC__byte tmp, *b = (FLAC__byte*)val;
2462 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
2468 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2470 size_t bytes_read = fread(val, 1, 4, f);
2472 if(bytes_read == 0) {
2474 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2480 else if(bytes_read < 4) {
2481 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2485 if(is_big_endian_host_) {
2486 FLAC__byte tmp, *b = (FLAC__byte*)val;
2487 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
2488 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
2494 FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
2496 unsigned char buf[4];
2497 size_t bytes_read= fread(buf, 1, 2, f);
2499 if(bytes_read==0U && eof_ok)
2501 else if(bytes_read<2U) {
2502 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2506 /* this is independent of host endianness */
2507 *val= (FLAC__uint16)(buf[0])<<8 | buf[1];
2512 FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2514 unsigned char buf[4];
2515 size_t bytes_read= fread(buf, 1, 4, f);
2517 if(bytes_read==0U && eof_ok)
2519 else if(bytes_read<4U) {
2520 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2524 /* this is independent of host endianness */
2525 *val= (FLAC__uint32)(buf[0])<<24 | (FLAC__uint32)(buf[1])<<16 |
2526 (FLAC__uint32)(buf[2])<<8 | buf[3];
2531 FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2532 /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
2533 * convert it into an integral value and store in 'val'. Return false if only
2534 * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f' and 'eof_ok' is
2535 * false, or if the value is negative, between zero and one, or too large to be
2536 * represented by 'val'; return true otherwise.
2540 unsigned char buf[10];
2541 size_t bytes_read= fread(buf, 1U, 10U, f);
2542 FLAC__int16 e= ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
2543 FLAC__int16 shift= 63-e;
2546 if(bytes_read==0U && eof_ok)
2548 else if(bytes_read<10U) {
2549 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2552 else if((buf[0]>>7)==1U || e<0 || e>63) {
2553 flac__utils_printf(stderr, 1, "%s: ERROR: invalid floating-point value\n", fn);
2557 for(i= 0U; i<8U; ++i)
2558 p|= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
2559 *val= (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1));
2564 FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset)
2566 static unsigned char dump[8192];
2569 long need = (long)min(offset, LONG_MAX);
2570 if(fseeko(f, need, SEEK_CUR) < 0) {
2571 need = (long)min(offset, sizeof(dump));
2572 if((long)fread(dump, 1, need, f) < need)
2577 #if 0 /* pure non-fseek() version */
2579 const long need = (long)min(offset, sizeof(dump));
2580 if(fread(dump, 1, need, f) < need)
2588 unsigned count_channel_mask_bits(FLAC__uint32 mask)
2599 FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels)
2601 FLAC__uint32 x = 0x80000000;
2602 unsigned count = count_channel_mask_bits(mask);
2603 while(x && count > channels) {
2610 FLAC__ASSERT(count_channel_mask_bits(mask) == channels);