1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006 Josh Coalson
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 #if defined _WIN32 && !defined __CYGWIN__
24 /* where MSVC puts unlink() */
29 #if defined _MSC_VER || defined __MINGW32__
30 #include <sys/types.h> /* for off_t */
31 #if _MSC_VER <= 1200 /* @@@ [2G limit] */
37 #include <limits.h> /* for LONG_MAX */
38 #include <math.h> /* for floor() */
39 #include <stdio.h> /* for FILE etc. */
40 #include <stdlib.h> /* for malloc */
41 #include <string.h> /* for strcmp(), strerror( */
43 #include "share/grabbag.h"
47 #include "OggFLAC/stream_encoder.h"
53 #define min(x,y) ((x)<(y)?(x):(y))
57 #define max(x,y) ((x)>(y)?(x):(y))
59 /* this MUST be >= 588 so that sector aligning can take place with one read */
60 #define CHUNK_OF_SAMPLES 2048
68 const char *inbasefilename;
69 const char *outfilename;
72 FLAC__uint64 until; /* a value of 0 mean end-of-stream (i.e. --until=-0) */
73 FLAC__bool replay_gain;
75 unsigned bits_per_sample;
77 FLAC__uint64 unencoded_size;
78 FLAC__uint64 total_samples_to_encode;
79 FLAC__uint64 bytes_written;
80 FLAC__uint64 samples_written;
85 FLAC__StreamEncoder *flac;
87 OggFLAC__StreamEncoder *ogg;
92 FLAC__StreamMetadata *seek_table_template;
95 /* this is data attached to the FLAC decoder when encoding from a FLAC file */
97 EncoderSession *encoder_session;
99 const FLAC__byte *lookahead;
100 unsigned lookahead_length;
101 size_t num_metadata_blocks;
102 FLAC__StreamMetadata *metadata_blocks[1024]; /*@@@ BAD MAGIC number */
103 FLAC__uint64 samples_left_to_process;
104 FLAC__bool fatal_error;
107 const int FLAC_ENCODE__DEFAULT_PADDING = 8192;
109 static FLAC__bool is_big_endian_host_;
111 static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
112 static signed char *scbuffer_ = (signed char *)ucbuffer_;
113 static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_;
114 static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_;
116 static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
117 static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
121 * unpublished debug routines from the FLAC libs
123 extern FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
124 extern FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
125 extern FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
127 extern FLAC__bool OggFLAC__stream_encoder_disable_constant_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
128 extern FLAC__bool OggFLAC__stream_encoder_disable_fixed_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
129 extern FLAC__bool OggFLAC__stream_encoder_disable_verbatim_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
135 static FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FILE *infile, const char *infilename, const char *outfilename);
136 static void EncoderSession_destroy(EncoderSession *e);
137 static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero);
138 static int EncoderSession_finish_error(EncoderSession *e);
139 static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, FLACDecoderData *flac_decoder_data);
140 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
141 static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
142 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
143 static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata);
144 static FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift);
145 static void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
146 static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
147 static FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
148 static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
149 static FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
150 static FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data);
151 static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
152 static void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
153 static void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
154 static FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset);
155 static void print_stats(const EncoderSession *encoder_session);
156 static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
157 static void print_error_with_state(const EncoderSession *e, const char *message);
158 static void print_verify_error(EncoderSession *e);
159 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
160 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
161 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
162 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
163 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
164 static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
165 static unsigned count_channel_mask_bits(FLAC__uint32 mask);
166 static unsigned limit_channel_mask(FLAC__uint32 mask, unsigned channels);
171 int flac__encode_aif(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options, FLAC__bool is_aifc)
173 EncoderSession encoder_session;
176 unsigned int channels= 0U, bps= 0U, sample_rate= 0U, sample_frames= 0U;
177 FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
178 int info_align_carry= -1, info_align_zero= -1;
179 FLAC__bool is_big_endian_pcm = true;
181 (void)infilesize; /* silence compiler warning about unused parameter */
182 (void)lookahead; /* silence compiler warning about unused parameter */
183 (void)lookahead_length; /* silence compiler warning about unused parameter */
186 EncoderSession_construct(
189 options.common.use_ogg,
193 options.common.verify,
201 /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
205 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 */
207 /* chunk identifier; really conservative about behavior of fread() and feof() */
208 if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
210 else if(c<4U || feof(infile)) {
211 flac__utils_printf(stderr, 1, "%s: ERROR: incomplete chunk identifier\n", encoder_session.inbasefilename);
212 return EncoderSession_finish_error(&encoder_session);
215 if(got_comm_chunk==false && !memcmp(chunk_id, "COMM", 4)) { /* common chunk */
217 const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18);
219 /* COMM chunk size */
220 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
221 return EncoderSession_finish_error(&encoder_session);
222 else if(xx<minimum_comm_size) {
223 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);
224 return EncoderSession_finish_error(&encoder_session);
226 else if(!is_aifc && xx!=minimum_comm_size) {
227 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);
229 skip= (xx-minimum_comm_size)+(xx & 1U);
231 /* number of channels */
232 if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
233 return EncoderSession_finish_error(&encoder_session);
234 else if(x==0U || x>FLAC__MAX_CHANNELS) {
235 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned int)x);
236 return EncoderSession_finish_error(&encoder_session);
238 else if(options.common.sector_align && x!=2U) {
239 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
240 return EncoderSession_finish_error(&encoder_session);
244 /* number of sample frames */
245 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
246 return EncoderSession_finish_error(&encoder_session);
249 /* bits per sample */
250 if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
251 return EncoderSession_finish_error(&encoder_session);
252 else if(x!=8U && x!=16U && x!=24U) {
253 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits per sample %u\n", encoder_session.inbasefilename, (unsigned int)x);
254 return EncoderSession_finish_error(&encoder_session);
256 else if(options.common.sector_align && x!=16U) {
257 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);
258 return EncoderSession_finish_error(&encoder_session);
263 if(!read_sane_extended(infile, &xx, false, encoder_session.inbasefilename))
264 return EncoderSession_finish_error(&encoder_session);
265 else if(!FLAC__format_sample_rate_is_valid(xx)) {
266 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned int)xx);
267 return EncoderSession_finish_error(&encoder_session);
269 else if(options.common.sector_align && xx!=44100U) {
270 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);
271 return EncoderSession_finish_error(&encoder_session);
275 /* check compression type for AIFF-C */
277 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
278 return EncoderSession_finish_error(&encoder_session);
279 if(xx == 0x736F7774) /* "sowt" */
280 is_big_endian_pcm = false;
281 else if(xx == 0x4E4F4E45) /* "NONE" */
282 ; /* nothing to do, we already default to big-endian */
284 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));
285 return EncoderSession_finish_error(&encoder_session);
289 /* skip any extra data in the COMM chunk */
290 if(!fskip_ahead(infile, skip)) {
291 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping extra COMM data\n", encoder_session.inbasefilename);
292 return EncoderSession_finish_error(&encoder_session);
296 * now that we know the sample rate, canonicalize the
297 * --skip string to a number of samples:
299 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, sample_rate);
300 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
301 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
302 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
304 got_comm_chunk= true;
306 else if(got_ssnd_chunk==false && !memcmp(chunk_id, "SSND", 4)) { /* sound data chunk */
307 unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
308 size_t bytes_per_frame= channels*(bps>>3);
309 FLAC__uint64 total_samples_in_input, trim = 0;
310 FLAC__bool pad= false;
312 if(got_comm_chunk==false) {
313 flac__utils_printf(stderr, 1, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", encoder_session.inbasefilename);
314 return EncoderSession_finish_error(&encoder_session);
317 /* SSND chunk size */
318 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
319 return EncoderSession_finish_error(&encoder_session);
321 pad= (data_bytes & 1U) ? true : false;
322 data_bytes-= 8U; /* discount the offset and block size fields */
325 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
326 return EncoderSession_finish_error(&encoder_session);
331 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
332 return EncoderSession_finish_error(&encoder_session);
334 flac__utils_printf(stderr, 1, "%s: ERROR: block size is %u; must be 0\n", encoder_session.inbasefilename, (unsigned int)xx);
335 return EncoderSession_finish_error(&encoder_session);
339 /* skip any SSND offset bytes */
340 FLAC__ASSERT(offset<=LONG_MAX);
341 if(!fskip_ahead(infile, offset)) {
342 flac__utils_printf(stderr, 1, "%s: ERROR: skipping offset in SSND chunk\n", encoder_session.inbasefilename);
343 return EncoderSession_finish_error(&encoder_session);
345 if(data_bytes!=(sample_frames*bytes_per_frame)) {
346 flac__utils_printf(stderr, 1, "%s: ERROR: SSND chunk size inconsistent with sample frame count\n", encoder_session.inbasefilename);
347 return EncoderSession_finish_error(&encoder_session);
350 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
351 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
352 total_samples_in_input = data_bytes / bytes_per_frame + *options.common.align_reservoir_samples;
355 * now that we know the input size, canonicalize the
356 * --until string to an absolute sample number:
358 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, sample_rate, encoder_session.skip, total_samples_in_input))
359 return EncoderSession_finish_error(&encoder_session);
360 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
361 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
363 if(encoder_session.skip>0U) {
364 if(!fskip_ahead(infile, encoder_session.skip*bytes_per_frame)) {
365 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
366 return EncoderSession_finish_error(&encoder_session);
370 data_bytes-= (unsigned int)encoder_session.skip*bytes_per_frame; /*@@@ WATCHOUT: 4GB limit */
371 encoder_session.total_samples_to_encode= total_samples_in_input - encoder_session.skip;
372 if(encoder_session.until > 0) {
373 trim = total_samples_in_input - encoder_session.until;
374 FLAC__ASSERT(total_samples_in_input > 0);
375 FLAC__ASSERT(!options.common.sector_align);
376 data_bytes-= (unsigned int)trim*bytes_per_frame;
377 encoder_session.total_samples_to_encode-= trim;
379 if(options.common.sector_align) {
380 align_remainder= (unsigned int)(encoder_session.total_samples_to_encode % 588U);
381 if(options.common.is_last_file)
382 encoder_session.total_samples_to_encode+= (588U-align_remainder); /* will pad with zeroes */
384 encoder_session.total_samples_to_encode-= align_remainder; /* will stop short and carry over to next file */
387 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
388 encoder_session.unencoded_size= encoder_session.total_samples_to_encode*bytes_per_frame+54;
390 if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate, /*flac_decoder_data=*/0))
391 return EncoderSession_finish_error(&encoder_session);
393 /* first do any samples in the reservoir */
394 if(options.common.sector_align && *options.common.align_reservoir_samples>0U) {
396 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
397 print_error_with_state(&encoder_session, "ERROR during encoding");
398 return EncoderSession_finish_error(&encoder_session);
402 /* decrement the data_bytes counter if we need to align the file */
403 if(options.common.sector_align) {
404 if(options.common.is_last_file)
405 *options.common.align_reservoir_samples= 0U;
407 *options.common.align_reservoir_samples= align_remainder;
408 data_bytes-= (*options.common.align_reservoir_samples)*bytes_per_frame;
412 /* now do from the file */
413 while(data_bytes>0) {
414 size_t bytes_read= fread(ucbuffer_, 1U, min(data_bytes, CHUNK_OF_SAMPLES*bytes_per_frame), infile);
418 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
419 return EncoderSession_finish_error(&encoder_session);
421 else if(feof(infile)) {
422 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);
427 if(bytes_read % bytes_per_frame != 0U) {
428 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
429 return EncoderSession_finish_error(&encoder_session);
432 unsigned int frames= bytes_read/bytes_per_frame;
433 if(!format_input(input_, frames, is_big_endian_pcm, /*is_unsigned_samples=*/false, channels, bps, /*shift=*/0))
434 return EncoderSession_finish_error(&encoder_session);
436 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, frames)) {
437 print_error_with_state(&encoder_session, "ERROR during encoding");
438 return EncoderSession_finish_error(&encoder_session);
441 data_bytes-= bytes_read;
447 FLAC__ASSERT(!options.common.sector_align);
448 if(!fskip_ahead(infile, trim*bytes_per_frame)) {
449 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
450 return EncoderSession_finish_error(&encoder_session);
454 /* now read unaligned samples into reservoir or pad with zeroes if necessary */
455 if(options.common.sector_align) {
456 if(options.common.is_last_file) {
457 unsigned int pad_frames= 588U-align_remainder;
459 if(pad_frames<588U) {
462 info_align_zero= pad_frames;
463 for(i= 0U; i<channels; ++i)
464 memset(input_[i], 0, sizeof(input_[0][0])*pad_frames);
466 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, pad_frames)) {
467 print_error_with_state(&encoder_session, "ERROR during encoding");
468 return EncoderSession_finish_error(&encoder_session);
473 if(*options.common.align_reservoir_samples > 0) {
474 size_t bytes_read= fread(ucbuffer_, 1U, (*options.common.align_reservoir_samples)*bytes_per_frame, infile);
476 FLAC__ASSERT(CHUNK_OF_SAMPLES>=588U);
477 if(bytes_read==0U && ferror(infile)) {
478 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
479 return EncoderSession_finish_error(&encoder_session);
481 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame) {
482 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);
485 info_align_carry= *options.common.align_reservoir_samples;
486 if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, is_big_endian_pcm, /*is_unsigned_samples=*/false, channels, bps, /*shift=*/0))
487 return EncoderSession_finish_error(&encoder_session);
496 if(fread(&tmp, 1U, 1U, infile)<1U) {
497 flac__utils_printf(stderr, 1, "%s: ERROR during read of SSND pad byte\n", encoder_session.inbasefilename);
498 return EncoderSession_finish_error(&encoder_session);
502 got_ssnd_chunk= true;
504 else { /* other chunk */
505 if(!memcmp(chunk_id, "COMM", 4)) {
506 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_session.inbasefilename);
508 else if(!memcmp(chunk_id, "SSND", 4)) {
509 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_session.inbasefilename);
512 flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_session.inbasefilename, chunk_id);
516 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
517 return EncoderSession_finish_error(&encoder_session);
519 unsigned long skip= xx+(xx & 1U);
521 FLAC__ASSERT(skip<=LONG_MAX);
522 if(!fskip_ahead(infile, skip)) {
523 fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_session.inbasefilename);
524 return EncoderSession_finish_error(&encoder_session);
530 if(got_ssnd_chunk==false && sample_frames!=0U) {
531 flac__utils_printf(stderr, 1, "%s: ERROR: missing SSND chunk\n", encoder_session.inbasefilename);
532 return EncoderSession_finish_error(&encoder_session);
535 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
538 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)
540 EncoderSession encoder_session;
541 FLAC__bool is_unsigned_samples = false;
542 unsigned channels = 0, bps = 0, sample_rate = 0, shift = 0;
543 size_t bytes_per_wide_sample, bytes_read;
544 FLAC__uint16 x, format; /* format is the wFormatTag word from the 'fmt ' chunk */
545 FLAC__uint32 xx, channel_mask = 0;
546 FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
547 unsigned align_remainder = 0;
548 int info_align_carry = -1, info_align_zero = -1;
552 (void)lookahead_length;
555 EncoderSession_construct(
558 options.common.use_ogg,
562 options.common.verify,
571 * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
573 while(!feof(infile)) {
574 if(!read_little_endian_uint32(infile, &xx, true, encoder_session.inbasefilename))
575 return EncoderSession_finish_error(&encoder_session);
578 if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
579 unsigned block_align, data_bytes;
582 * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
583 * http://windowssdk.msdn.microsoft.com/en-us/library/ms713497.aspx
584 * 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
587 * 4 byte: subchunk size
588 * 2 byte: format type: 1 for WAVE_FORMAT_PCM, 65534 for WAVE_FORMAT_EXTENSIBLE
590 * 4 byte: sample rate (Hz)
591 * 4 byte: avg bytes per sec
592 * 2 byte: block align
593 * 2 byte: bits per sample (not necessarily all significant)
595 * 2 byte: extension size in bytes (usually 0 for WAVEFORMATEX and 22 for WAVEFORMATEXTENSIBLE with PCM)
596 * WAVEFORMATEXTENSIBLE adds
597 * 2 byte: valid bits per sample
598 * 4 byte: channel mask
599 * 16 byte: subformat GUID, first 2 bytes have format type, 1 being PCM
601 * Current spec says WAVEFORMATEX with PCM must have bps == 8 or 16, or any multiple of 8 for WAVEFORMATEXTENSIBLE.
602 * 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.
604 * Block align for WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE is also supposed to be channels*bps/8
606 * If the channel mask has less set bits that # of channels, the extra MSBs are ignored.
607 * If the channel mask has more set bits that # of channels, the extra channels are unassigned to any speaker.
609 * Data is supposed to be unsigned for bps <= 8 else signed.
612 /* fmt sub-chunk size */
613 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
614 return EncoderSession_finish_error(&encoder_session);
616 flac__utils_printf(stderr, 1, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
617 return EncoderSession_finish_error(&encoder_session);
620 /* compression code */
621 if(!read_little_endian_uint16(infile, &format, false, encoder_session.inbasefilename))
622 return EncoderSession_finish_error(&encoder_session);
623 if(format != 1 /*WAVE_FORMAT_PCM*/ && format != 65534 /*WAVE_FORMAT_EXTENSIBLE*/) {
624 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", encoder_session.inbasefilename, (unsigned)format);
625 return EncoderSession_finish_error(&encoder_session);
627 /* number of channels */
628 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
629 return EncoderSession_finish_error(&encoder_session);
630 if(x == 0 || x > FLAC__MAX_CHANNELS) {
631 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u\n", encoder_session.inbasefilename, (unsigned)x);
632 return EncoderSession_finish_error(&encoder_session);
634 else if(options.common.sector_align && x != 2) {
635 flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
636 return EncoderSession_finish_error(&encoder_session);
640 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
641 return EncoderSession_finish_error(&encoder_session);
642 if(!FLAC__format_sample_rate_is_valid(xx)) {
643 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned)xx);
644 return EncoderSession_finish_error(&encoder_session);
646 else if(options.common.sector_align && xx != 44100) {
647 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);
648 return EncoderSession_finish_error(&encoder_session);
651 /* avg bytes per second (ignored) */
652 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
653 return EncoderSession_finish_error(&encoder_session);
655 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
656 return EncoderSession_finish_error(&encoder_session);
658 /* bits per sample */
659 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
660 return EncoderSession_finish_error(&encoder_session);
662 is_unsigned_samples = (bps <= 8);
664 if(bps != 8 && bps != 16) {
665 #if 0 /* reinstate if we need to get stricter on the input */
666 if(bps == 24 || bps == 32) {
668 /* let these slide with a warning since they're unambiguous */
669 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);
670 #if 0 /* reinstate if we need to get stricter on the input */
673 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);
674 return EncoderSession_finish_error(&encoder_session);
678 if((bps+7)/8 * channels == block_align) {
680 /* assume legacy file is block aligned with some LSBs zero; this is checked for in format_input() */
681 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);
682 shift = 8 - (bps % 8);
689 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);
690 return EncoderSession_finish_error(&encoder_session);
692 FLAC__ASSERT(data_bytes >= 16);
696 if(data_bytes < 40) {
697 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE sub-chunk with size %u\n", encoder_session.inbasefilename, data_bytes);
698 return EncoderSession_finish_error(&encoder_session);
701 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
702 return EncoderSession_finish_error(&encoder_session);
704 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE sub-chunk with cbSize %u\n", encoder_session.inbasefilename, (unsigned)x);
705 return EncoderSession_finish_error(&encoder_session);
708 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
709 return EncoderSession_finish_error(&encoder_session);
710 if((unsigned)x > bps) {
711 flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE sub-chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", encoder_session.inbasefilename, (unsigned)x, bps);
712 return EncoderSession_finish_error(&encoder_session);
714 shift = bps - (unsigned)x;
716 if(!read_little_endian_uint32(infile, &channel_mask, false, encoder_session.inbasefilename))
717 return EncoderSession_finish_error(&encoder_session);
718 /* for mono/stereo and unassigned channels, we fake the mask */
719 if(channel_mask == 0) {
721 channel_mask = 0x0001;
722 else if(channels == 2)
723 channel_mask = 0x0003;
725 if(channel_mask != 0x0001 && channel_mask != 0x0003 && channel_mask != 0x003f && channel_mask != 0x060f) {
726 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);
727 return EncoderSession_finish_error(&encoder_session);
729 if(count_channel_mask_bits(channel_mask) < channels) {
730 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);
731 return EncoderSession_finish_error(&encoder_session);
733 else if(count_channel_mask_bits(channel_mask) > channels)
734 channel_mask = limit_channel_mask(channel_mask, channels);
735 /* first part of GUID */
736 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
737 return EncoderSession_finish_error(&encoder_session);
739 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE sub-chunk with non-PCM format %u\n", encoder_session.inbasefilename, (unsigned)x);
740 return EncoderSession_finish_error(&encoder_session);
745 if(bps-shift < 4 || bps-shift > 24) {
746 flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, bps-shift);
747 return EncoderSession_finish_error(&encoder_session);
749 else if(options.common.sector_align && bps-shift != 16) {
750 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);
751 return EncoderSession_finish_error(&encoder_session);
754 /* skip any extra data in the fmt sub-chunk */
755 if(!fskip_ahead(infile, data_bytes)) {
756 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping extra 'fmt' data\n", encoder_session.inbasefilename);
757 return EncoderSession_finish_error(&encoder_session);
761 * now that we know the sample rate, canonicalize the
762 * --skip string to a number of samples:
764 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, sample_rate);
765 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
766 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
767 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
769 got_fmt_chunk = true;
771 else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
772 FLAC__uint64 total_samples_in_input, trim = 0;
773 FLAC__bool pad = false;
777 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
778 return EncoderSession_finish_error(&encoder_session);
780 pad = (data_bytes & 1U) ? true : false;
782 bytes_per_wide_sample = channels * (bps >> 3);
784 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
785 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
786 total_samples_in_input = data_bytes / bytes_per_wide_sample + *options.common.align_reservoir_samples;
789 * now that we know the input size, canonicalize the
790 * --until string to an absolute sample number:
792 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, sample_rate, encoder_session.skip, total_samples_in_input))
793 return EncoderSession_finish_error(&encoder_session);
794 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
795 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
797 if(encoder_session.skip > 0) {
798 if(!fskip_ahead(infile, encoder_session.skip * bytes_per_wide_sample)) {
799 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
800 return EncoderSession_finish_error(&encoder_session);
804 data_bytes -= (unsigned)encoder_session.skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
805 encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
806 if(encoder_session.until > 0) {
807 trim = total_samples_in_input - encoder_session.until;
808 FLAC__ASSERT(total_samples_in_input > 0);
809 FLAC__ASSERT(!options.common.sector_align);
810 data_bytes -= (unsigned int)trim * bytes_per_wide_sample;
811 encoder_session.total_samples_to_encode -= trim;
813 if(options.common.sector_align) {
814 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
815 if(options.common.is_last_file)
816 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
818 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
821 /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
822 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample + 44;
824 if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps-shift, sample_rate, /*flac_decoder_data=*/0))
825 return EncoderSession_finish_error(&encoder_session);
828 * first do any samples in the reservoir
830 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
831 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
832 print_error_with_state(&encoder_session, "ERROR during encoding");
833 return EncoderSession_finish_error(&encoder_session);
838 * decrement the data_bytes counter if we need to align the file
840 if(options.common.sector_align) {
841 if(options.common.is_last_file) {
842 *options.common.align_reservoir_samples = 0;
845 *options.common.align_reservoir_samples = align_remainder;
846 data_bytes -= (*options.common.align_reservoir_samples) * bytes_per_wide_sample;
851 * now do from the file
853 while(data_bytes > 0) {
854 bytes_read = fread(ucbuffer_, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
855 if(bytes_read == 0) {
857 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
858 return EncoderSession_finish_error(&encoder_session);
860 else if(feof(infile)) {
861 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);
866 if(bytes_read % bytes_per_wide_sample != 0) {
867 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
868 return EncoderSession_finish_error(&encoder_session);
871 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
872 if(!format_input(input_, wide_samples, /*is_big_endian=*/false, is_unsigned_samples, channels, bps, shift))
873 return EncoderSession_finish_error(&encoder_session);
875 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
876 print_error_with_state(&encoder_session, "ERROR during encoding");
877 return EncoderSession_finish_error(&encoder_session);
879 data_bytes -= bytes_read;
885 FLAC__ASSERT(!options.common.sector_align);
886 if(!fskip_ahead(infile, trim * bytes_per_wide_sample)) {
887 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
888 return EncoderSession_finish_error(&encoder_session);
893 * now read unaligned samples into reservoir or pad with zeroes if necessary
895 if(options.common.sector_align) {
896 if(options.common.is_last_file) {
897 unsigned wide_samples = 588 - align_remainder;
898 if(wide_samples < 588) {
901 info_align_zero = wide_samples;
902 for(channel = 0; channel < channels; channel++)
903 memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
905 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
906 print_error_with_state(&encoder_session, "ERROR during encoding");
907 return EncoderSession_finish_error(&encoder_session);
912 if(*options.common.align_reservoir_samples > 0) {
913 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
914 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
915 if(bytes_read == 0 && ferror(infile)) {
916 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
917 return EncoderSession_finish_error(&encoder_session);
919 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
920 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);
923 info_align_carry = *options.common.align_reservoir_samples;
924 if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, /*is_big_endian=*/false, is_unsigned_samples, channels, bps, shift))
925 return EncoderSession_finish_error(&encoder_session);
934 if(fread(&tmp, 1U, 1U, infile) < 1U) {
935 flac__utils_printf(stderr, 1, "%s: ERROR during read of data pad byte\n", encoder_session.inbasefilename);
936 return EncoderSession_finish_error(&encoder_session);
940 got_data_chunk = true;
943 if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
944 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_session.inbasefilename);
946 else if(xx == 0x61746164) { /* "data" */
948 flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_session.inbasefilename);
950 else if(!got_fmt_chunk) {
951 flac__utils_printf(stderr, 1, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_session.inbasefilename);
952 return EncoderSession_finish_error(&encoder_session);
959 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));
962 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
963 return EncoderSession_finish_error(&encoder_session);
965 unsigned long skip = xx+(xx & 1U);
967 FLAC__ASSERT(skip<=LONG_MAX);
968 if(!fskip_ahead(infile, skip)) {
969 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_session.inbasefilename);
970 return EncoderSession_finish_error(&encoder_session);
976 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
979 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)
981 EncoderSession encoder_session;
983 const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
984 unsigned align_remainder = 0;
985 int info_align_carry = -1, info_align_zero = -1;
986 FLAC__uint64 total_samples_in_input = 0;
988 FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
989 FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
990 FLAC__ASSERT(!options.common.sector_align || options.sample_rate == 44100);
991 FLAC__ASSERT(!options.common.sector_align || infilesize >= 0);
992 FLAC__ASSERT(!options.common.replay_gain || options.channels <= 2);
993 FLAC__ASSERT(!options.common.replay_gain || grabbag__replaygain_is_valid_sample_frequency(options.sample_rate));
996 EncoderSession_construct(
999 options.common.use_ogg,
1003 options.common.verify,
1012 * now that we know the sample rate, canonicalize the
1013 * --skip string to a number of samples:
1015 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, options.sample_rate);
1016 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
1017 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
1018 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
1021 total_samples_in_input = 0;
1023 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
1024 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
1025 total_samples_in_input = (FLAC__uint64)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
1029 * now that we know the input size, canonicalize the
1030 * --until strings to a number of samples:
1032 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, options.sample_rate, encoder_session.skip, total_samples_in_input))
1033 return EncoderSession_finish_error(&encoder_session);
1034 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
1035 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
1037 infilesize -= (off_t)encoder_session.skip * bytes_per_wide_sample;
1038 encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
1039 if(encoder_session.until > 0) {
1040 const FLAC__uint64 trim = total_samples_in_input - encoder_session.until;
1041 FLAC__ASSERT(total_samples_in_input > 0);
1042 FLAC__ASSERT(!options.common.sector_align);
1043 infilesize -= (off_t)trim * bytes_per_wide_sample;
1044 encoder_session.total_samples_to_encode -= trim;
1046 if(infilesize >= 0 && options.common.sector_align) {
1047 FLAC__ASSERT(encoder_session.skip == 0);
1048 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
1049 if(options.common.is_last_file)
1050 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
1052 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
1054 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample;
1056 if(encoder_session.total_samples_to_encode <= 0)
1057 flac__utils_printf(stderr, 2, "(No runtime statistics possible; please wait for encoding to finish...)\n");
1059 if(encoder_session.skip > 0) {
1060 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)encoder_session.skip;
1061 if(skip_bytes > lookahead_length) {
1062 skip_bytes -= lookahead_length;
1063 lookahead_length = 0;
1064 if(!fskip_ahead(infile, skip_bytes)) {
1065 flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
1066 return EncoderSession_finish_error(&encoder_session);
1070 lookahead += skip_bytes;
1071 lookahead_length -= skip_bytes;
1075 if(!EncoderSession_init_encoder(&encoder_session, options.common, options.channels, options.bps, options.sample_rate, /*flac_decoder_data=*/0))
1076 return EncoderSession_finish_error(&encoder_session);
1079 * first do any samples in the reservoir
1081 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
1082 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
1083 print_error_with_state(&encoder_session, "ERROR during encoding");
1084 return EncoderSession_finish_error(&encoder_session);
1089 * decrement infilesize if we need to align the file
1091 if(options.common.sector_align) {
1092 FLAC__ASSERT(infilesize >= 0);
1093 if(options.common.is_last_file) {
1094 *options.common.align_reservoir_samples = 0;
1097 *options.common.align_reservoir_samples = align_remainder;
1098 infilesize -= (off_t)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
1099 FLAC__ASSERT(infilesize >= 0);
1104 * now do from the file
1106 if(infilesize < 0) {
1107 while(!feof(infile)) {
1108 if(lookahead_length > 0) {
1109 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1110 memcpy(ucbuffer_, lookahead, lookahead_length);
1111 bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
1112 if(ferror(infile)) {
1113 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1114 return EncoderSession_finish_error(&encoder_session);
1116 lookahead_length = 0;
1119 bytes_read = fread(ucbuffer_, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
1121 if(bytes_read == 0) {
1122 if(ferror(infile)) {
1123 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1124 return EncoderSession_finish_error(&encoder_session);
1127 else if(bytes_read % bytes_per_wide_sample != 0) {
1128 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1129 return EncoderSession_finish_error(&encoder_session);
1132 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1133 if(!format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0))
1134 return EncoderSession_finish_error(&encoder_session);
1136 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1137 print_error_with_state(&encoder_session, "ERROR during encoding");
1138 return EncoderSession_finish_error(&encoder_session);
1144 const FLAC__uint64 max_input_bytes = infilesize;
1145 FLAC__uint64 total_input_bytes_read = 0;
1146 while(total_input_bytes_read < max_input_bytes) {
1148 size_t wanted = (CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1149 wanted = (size_t) min((FLAC__uint64)wanted, max_input_bytes - total_input_bytes_read);
1151 if(lookahead_length > 0) {
1152 FLAC__ASSERT(lookahead_length <= wanted);
1153 memcpy(ucbuffer_, lookahead, lookahead_length);
1154 wanted -= lookahead_length;
1155 bytes_read = lookahead_length;
1157 bytes_read += fread(ucbuffer_+lookahead_length, sizeof(unsigned char), wanted, infile);
1158 if(ferror(infile)) {
1159 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1160 return EncoderSession_finish_error(&encoder_session);
1163 lookahead_length = 0;
1166 bytes_read = fread(ucbuffer_, sizeof(unsigned char), wanted, infile);
1169 if(bytes_read == 0) {
1170 if(ferror(infile)) {
1171 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1172 return EncoderSession_finish_error(&encoder_session);
1174 else if(feof(infile)) {
1175 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);
1176 total_input_bytes_read = max_input_bytes;
1180 if(bytes_read % bytes_per_wide_sample != 0) {
1181 flac__utils_printf(stderr, 1, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1182 return EncoderSession_finish_error(&encoder_session);
1185 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1186 if(!format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0))
1187 return EncoderSession_finish_error(&encoder_session);
1189 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1190 print_error_with_state(&encoder_session, "ERROR during encoding");
1191 return EncoderSession_finish_error(&encoder_session);
1193 total_input_bytes_read += bytes_read;
1200 * now read unaligned samples into reservoir or pad with zeroes if necessary
1202 if(options.common.sector_align) {
1203 if(options.common.is_last_file) {
1204 unsigned wide_samples = 588 - align_remainder;
1205 if(wide_samples < 588) {
1208 info_align_zero = wide_samples;
1209 for(channel = 0; channel < options.channels; channel++)
1210 memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
1212 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1213 print_error_with_state(&encoder_session, "ERROR during encoding");
1214 return EncoderSession_finish_error(&encoder_session);
1219 if(*options.common.align_reservoir_samples > 0) {
1220 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1221 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
1222 if(bytes_read == 0 && ferror(infile)) {
1223 flac__utils_printf(stderr, 1, "%s: ERROR during read\n", encoder_session.inbasefilename);
1224 return EncoderSession_finish_error(&encoder_session);
1226 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
1227 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);
1230 info_align_carry = *options.common.align_reservoir_samples;
1231 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))
1232 return EncoderSession_finish_error(&encoder_session);
1238 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
1241 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)
1243 EncoderSession encoder_session;
1244 FLAC__StreamDecoder *decoder = 0;
1245 FLACDecoderData decoder_data;
1250 EncoderSession_construct(
1252 #ifdef FLAC__HAS_OGG
1253 options.common.use_ogg,
1257 options.common.verify,
1265 decoder_data.encoder_session = &encoder_session;
1266 decoder_data.filesize = (infilesize == (off_t)(-1)? 0 : infilesize);
1267 decoder_data.lookahead = lookahead;
1268 decoder_data.lookahead_length = lookahead_length;
1269 decoder_data.num_metadata_blocks = 0;
1270 decoder_data.samples_left_to_process = 0;
1271 decoder_data.fatal_error = false;
1274 * set up FLAC decoder for the input
1276 if (0 == (decoder = FLAC__stream_decoder_new())) {
1277 flac__utils_printf(stderr, 1, "%s: ERROR: creating decoder for FLAC input\n", encoder_session.inbasefilename);
1278 return EncoderSession_finish_error(&encoder_session);
1281 FLAC__stream_decoder_set_md5_checking(decoder, false) &&
1282 FLAC__stream_decoder_set_metadata_respond_all(decoder)
1284 flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", encoder_session.inbasefilename);
1285 goto fubar1; /*@@@ yuck */
1288 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) {
1289 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));
1290 goto fubar1; /*@@@ yuck */
1293 if (!FLAC__stream_decoder_process_until_end_of_metadata(decoder) || decoder_data.fatal_error) {
1294 if (decoder_data.fatal_error)
1295 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);
1297 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));
1298 goto fubar1; /*@@@ yuck */
1301 if (decoder_data.num_metadata_blocks == 0) {
1302 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, got no metadata blocks\n", encoder_session.inbasefilename);
1303 goto fubar2; /*@@@ yuck */
1305 else if (decoder_data.metadata_blocks[0]->type != FLAC__METADATA_TYPE_STREAMINFO) {
1306 flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, first metadata block is not STREAMINFO\n", encoder_session.inbasefilename);
1307 goto fubar2; /*@@@ yuck */
1309 else if (decoder_data.metadata_blocks[0]->data.stream_info.total_samples == 0) {
1310 flac__utils_printf(stderr, 1, "%s: ERROR: FLAC input has STREAMINFO with unknown total samples which is not supported\n", encoder_session.inbasefilename);
1311 goto fubar2; /*@@@ yuck */
1315 * now that we have the STREAMINFO and know the sample rate,
1316 * canonicalize the --skip string to a number of samples:
1318 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate);
1319 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
1320 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
1321 FLAC__ASSERT(!options.common.sector_align); /* --sector-align with FLAC input is not supported */
1324 FLAC__uint64 total_samples_in_input, trim = 0;
1326 total_samples_in_input = decoder_data.metadata_blocks[0]->data.stream_info.total_samples;
1329 * now that we know the input size, canonicalize the
1330 * --until string to an absolute sample number:
1332 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))
1333 goto fubar2; /*@@@ yuck */
1334 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
1336 encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
1337 if(encoder_session.until > 0) {
1338 trim = total_samples_in_input - encoder_session.until;
1339 FLAC__ASSERT(total_samples_in_input > 0);
1340 encoder_session.total_samples_to_encode -= trim;
1343 encoder_session.unencoded_size = decoder_data.filesize;
1345 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))
1346 return EncoderSession_finish_error(&encoder_session);
1349 * have to wait until the FLAC encoder is set up for writing
1350 * before any seeking in the input FLAC file, because the seek
1351 * itself will usually call the decoder's write callback, and
1352 * our decoder's write callback passes samples to our FLAC
1355 decoder_data.samples_left_to_process = encoder_session.total_samples_to_encode;
1356 if(encoder_session.skip > 0) {
1357 if(!FLAC__stream_decoder_seek_absolute(decoder, encoder_session.skip)) {
1358 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));
1359 goto fubar2; /*@@@ yuck */
1364 * now do samples from the file
1366 while(!decoder_data.fatal_error && decoder_data.samples_left_to_process > 0) {
1367 if(!FLAC__stream_decoder_process_single(decoder)) {
1368 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));
1369 goto fubar2; /*@@@ yuck */
1374 FLAC__stream_decoder_delete(decoder);
1375 retval = EncoderSession_finish_ok(&encoder_session, -1, -1);
1376 /* have to wail until encoder is completely finished before deleting because of the final step of writing the seekpoint offsets */
1377 for(i = 0; i < decoder_data.num_metadata_blocks; i++)
1378 free(decoder_data.metadata_blocks[i]);
1382 for(i = 0; i < decoder_data.num_metadata_blocks; i++)
1383 free(decoder_data.metadata_blocks[i]);
1385 FLAC__stream_decoder_delete(decoder);
1386 return EncoderSession_finish_error(&encoder_session);
1389 FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FILE *infile, const char *infilename, const char *outfilename)
1392 FLAC__uint32 test = 1;
1395 * initialize globals
1398 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
1400 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1401 input_[i] = &(in_[i][0]);
1405 * initialize instance
1408 #ifdef FLAC__HAS_OGG
1409 e->use_ogg = use_ogg;
1415 e->is_stdout = (0 == strcmp(outfilename, "-"));
1417 e->inbasefilename = grabbag__file_get_basename(infilename);
1418 e->outfilename = outfilename;
1420 e->skip = 0; /* filled in later after the sample_rate is known */
1421 e->unencoded_size = 0;
1422 e->total_samples_to_encode = 0;
1423 e->bytes_written = 0;
1424 e->samples_written = 0;
1428 e->encoder.flac = 0;
1429 #ifdef FLAC__HAS_OGG
1434 e->seek_table_template = 0;
1436 if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1437 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1441 #ifdef FLAC__HAS_OGG
1443 e->encoder.ogg = OggFLAC__stream_encoder_new();
1444 if(0 == e->encoder.ogg) {
1445 flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1446 EncoderSession_destroy(e);
1452 e->encoder.flac = FLAC__stream_encoder_new();
1453 if(0 == e->encoder.flac) {
1454 flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1455 EncoderSession_destroy(e);
1462 void EncoderSession_destroy(EncoderSession *e)
1467 #ifdef FLAC__HAS_OGG
1469 if(0 != e->encoder.ogg) {
1470 OggFLAC__stream_encoder_delete(e->encoder.ogg);
1476 if(0 != e->encoder.flac) {
1477 FLAC__stream_encoder_delete(e->encoder.flac);
1478 e->encoder.flac = 0;
1481 if(0 != e->seek_table_template) {
1482 FLAC__metadata_object_delete(e->seek_table_template);
1483 e->seek_table_template = 0;
1487 int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero)
1489 FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1492 #ifdef FLAC__HAS_OGG
1494 if(e->encoder.ogg) {
1495 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg);
1496 OggFLAC__stream_encoder_finish(e->encoder.ogg);
1501 if(e->encoder.flac) {
1502 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac);
1503 FLAC__stream_encoder_finish(e->encoder.flac);
1506 if(e->total_samples_to_encode > 0) {
1508 flac__utils_printf(stderr, 2, "\n");
1511 if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) {
1512 print_verify_error(e);
1516 if(info_align_carry >= 0) {
1517 flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d samples to be carried over\n", e->inbasefilename, info_align_carry);
1519 if(info_align_zero >= 0) {
1520 flac__utils_printf(stderr, 1, "%s: INFO: sector alignment causing %d zero samples to be appended\n", e->inbasefilename, info_align_zero);
1524 EncoderSession_destroy(e);
1529 int EncoderSession_finish_error(EncoderSession *e)
1531 FLAC__StreamEncoderState fse_state;
1533 if(e->total_samples_to_encode > 0)
1534 flac__utils_printf(stderr, 2, "\n");
1536 #ifdef FLAC__HAS_OGG
1538 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg);
1543 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac);
1546 if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1547 print_verify_error(e);
1549 /*@@@@@@@@@ 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 */
1550 unlink(e->outfilename);
1552 EncoderSession_destroy(e);
1557 FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, FLACDecoderData *flac_decoder_data)
1559 unsigned num_metadata, i;
1560 FLAC__StreamMetadata padding, *cuesheet = 0;
1561 FLAC__StreamMetadata *static_metadata[4+64]; /* MAGIC +64 is for pictures metadata in options.pictures */
1562 FLAC__StreamMetadata **metadata = static_metadata;
1563 FLAC__StreamEncoderInitStatus init_status;
1564 const FLAC__bool is_cdda = (channels == 1 || channels == 2) && (bps == 16) && (sample_rate == 44100);
1566 FLAC__ASSERT(sizeof(options.pictures)/sizeof(options.pictures[0]) <= 64);
1568 e->replay_gain = options.replay_gain;
1569 e->channels = channels;
1570 e->bits_per_sample = bps;
1571 e->sample_rate = sample_rate;
1573 if(e->replay_gain) {
1574 if(channels != 1 && channels != 2) {
1575 flac__utils_printf(stderr, 1, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
1578 if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) {
1579 flac__utils_printf(stderr, 1, "%s: ERROR, invalid sample rate (%u) for --replay-gain\n", e->inbasefilename, sample_rate);
1582 if(options.is_first_file) {
1583 if(!grabbag__replaygain_init(sample_rate)) {
1584 flac__utils_printf(stderr, 1, "%s: ERROR initializing ReplayGain stage\n", e->inbasefilename);
1591 options.do_mid_side = options.loose_mid_side = false;
1593 if(!parse_cuesheet(&cuesheet, options.cuesheet_filename, e->inbasefilename, is_cdda, e->total_samples_to_encode))
1596 if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? cuesheet : 0, e)) {
1597 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1599 FLAC__metadata_object_delete(cuesheet);
1603 if(flac_decoder_data) {
1605 * we're encoding from FLAC so we will use the FLAC file's
1606 * metadata as the basic for the encoded file
1610 * first handle padding: if --no-padding was specified,
1611 * then delete all padding; else if -P was specified,
1612 * use that instead of existing padding (if any); else
1613 * if existing file has padding, move all existing
1614 * padding blocks to one padding block at the end; else
1615 * use default padding.
1619 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1620 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_PADDING) {
1623 p += flac_decoder_data->metadata_blocks[i]->length;
1624 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1625 flac_decoder_data->metadata_blocks[i] = 0;
1628 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1630 flac_decoder_data->num_metadata_blocks = j;
1631 if(options.padding > 0)
1632 p = options.padding;
1634 p = e->total_samples_to_encode / e->sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8;
1635 if(options.padding != 0) {
1636 if(p > 0 && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1637 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
1638 if(0 == flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]) {
1639 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PADDING block\n", e->inbasefilename);
1641 FLAC__metadata_object_delete(cuesheet);
1644 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->is_last = false; /* the encoder will set this for us */
1645 flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->length = p;
1646 flac_decoder_data->num_metadata_blocks++;
1652 * next handle vorbis comment: if any tags were specified
1653 * or there is no existing vorbis comment, we create a
1654 * new vorbis comment (discarding any existing one); else
1655 * we keep the existing one
1658 FLAC__bool vc_found = false;
1659 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1660 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
1662 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT && options.vorbis_comment->data.vorbis_comment.num_comments > 0) {
1663 if(options.vorbis_comment->data.vorbis_comment.num_comments > 0)
1664 flac__utils_printf(stderr, 1, "%s: WARNING, replacing tags from input FLAC file with those given on the command-line\n", e->inbasefilename);
1665 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1666 flac_decoder_data->metadata_blocks[i] = 0;
1669 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1671 flac_decoder_data->num_metadata_blocks = j;
1672 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])) {
1674 FLAC__StreamMetadata *vc = FLAC__metadata_object_clone(options.vorbis_comment);
1676 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for VORBIS_COMMENT block\n", e->inbasefilename);
1678 FLAC__metadata_object_delete(cuesheet);
1681 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1682 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1683 flac_decoder_data->metadata_blocks[1] = vc;
1684 flac_decoder_data->num_metadata_blocks++;
1689 * next handle cuesheet: if --cuesheet was specified, use
1690 * it; else if file has existing CUESHEET and cuesheet's
1691 * lead-out offset is correct, keep it; else no CUESHEET
1694 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1695 FLAC__bool existing_cuesheet_is_bad = false;
1696 /* check if existing cuesheet matches the input audio */
1697 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && 0 == cuesheet) {
1698 const FLAC__StreamMetadata_CueSheet *cs = &flac_decoder_data->metadata_blocks[i]->data.cue_sheet;
1699 if(e->total_samples_to_encode == 0) {
1700 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);
1701 existing_cuesheet_is_bad = true;
1703 else if(e->total_samples_to_encode != cs->tracks[cs->num_tracks-1].offset) {
1704 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);
1705 existing_cuesheet_is_bad = true;
1708 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && (existing_cuesheet_is_bad || 0 != cuesheet)) {
1710 flac__utils_printf(stderr, 1, "%s: WARNING, replacing cuesheet in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1711 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1712 flac_decoder_data->metadata_blocks[i] = 0;
1715 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1717 flac_decoder_data->num_metadata_blocks = j;
1718 if(0 != cuesheet && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
1720 FLAC__StreamMetadata *cs = FLAC__metadata_object_clone(cuesheet);
1722 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for CUESHEET block\n", e->inbasefilename);
1724 FLAC__metadata_object_delete(cuesheet);
1727 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1728 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1729 flac_decoder_data->metadata_blocks[1] = cs;
1730 flac_decoder_data->num_metadata_blocks++;
1735 * finally handle seektable: if -S- was specified, no
1736 * SEEKTABLE; else if -S was specified, use it/them;
1737 * else if file has existing SEEKTABLE and input size is
1738 * preserved (no --skip/--until/etc specified), keep it;
1739 * else use default seektable options
1741 * note: meanings of num_requested_seek_points:
1742 * -1 : no -S option given, default to some value
1743 * 0 : -S- given (no seektable)
1744 * >0 : one or more -S options given
1747 FLAC__bool existing_seektable = false;
1748 for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
1749 if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE)
1750 existing_seektable = true;
1751 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)) {
1752 if(options.num_requested_seek_points > 0)
1753 flac__utils_printf(stderr, 1, "%s: WARNING, replacing seektable in input FLAC file with the one given on the command-line\n", e->inbasefilename);
1754 else if(options.num_requested_seek_points == 0)
1755 ; /* no warning, silently delete existing SEEKTABLE since user specified --no-seektable (-S-) */
1757 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);
1758 FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
1759 flac_decoder_data->metadata_blocks[i] = 0;
1760 existing_seektable = false;
1763 flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
1765 flac_decoder_data->num_metadata_blocks = j;
1766 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])) {
1768 FLAC__StreamMetadata *st = FLAC__metadata_object_clone(e->seek_table_template);
1770 flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for SEEKTABLE block\n", e->inbasefilename);
1772 FLAC__metadata_object_delete(cuesheet);
1775 for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
1776 flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
1777 flac_decoder_data->metadata_blocks[1] = st;
1778 flac_decoder_data->num_metadata_blocks++;
1781 metadata = &flac_decoder_data->metadata_blocks[1]; /* don't include STREAMINFO */
1782 num_metadata = flac_decoder_data->num_metadata_blocks - 1;
1786 * we're not encoding from FLAC so we will build the metadata
1790 if(e->seek_table_template->data.seek_table.num_points > 0) {
1791 e->seek_table_template->is_last = false; /* the encoder will set this for us */
1792 metadata[num_metadata++] = e->seek_table_template;
1795 metadata[num_metadata++] = cuesheet;
1796 metadata[num_metadata++] = options.vorbis_comment;
1797 for(i = 0; i < options.num_pictures; i++)
1798 metadata[num_metadata++] = options.pictures[i];
1799 if(options.padding != 0) {
1800 padding.is_last = false; /* the encoder will set this for us */
1801 padding.type = FLAC__METADATA_TYPE_PADDING;
1802 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));
1803 metadata[num_metadata++] = &padding;
1807 /* check for a few things that have not already been checked. the
1808 * FLAC__stream_encoder_init*() will check it but only return
1809 * FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA so we check some
1810 * up front to give a better error message.
1812 if(!verify_metadata(e, metadata, num_metadata)) {
1814 FLAC__metadata_object_delete(cuesheet);
1818 e->blocksize = options.blocksize;
1819 e->stats_mask = (options.do_exhaustive_model_search || options.do_qlp_coeff_prec_search)? 0x0f : 0x3f;
1821 #ifdef FLAC__HAS_OGG
1823 OggFLAC__stream_encoder_set_serial_number(e->encoder.ogg, options.serial_number);
1824 OggFLAC__stream_encoder_set_verify(e->encoder.ogg, options.verify);
1825 OggFLAC__stream_encoder_set_streamable_subset(e->encoder.ogg, !options.lax);
1826 OggFLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.ogg, options.do_mid_side);
1827 OggFLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.ogg, options.loose_mid_side);
1828 OggFLAC__stream_encoder_set_channels(e->encoder.ogg, channels);
1829 OggFLAC__stream_encoder_set_bits_per_sample(e->encoder.ogg, bps);
1830 OggFLAC__stream_encoder_set_sample_rate(e->encoder.ogg, sample_rate);
1831 OggFLAC__stream_encoder_set_blocksize(e->encoder.ogg, options.blocksize);
1832 OggFLAC__stream_encoder_set_apodization(e->encoder.ogg, options.apodizations);
1833 OggFLAC__stream_encoder_set_max_lpc_order(e->encoder.ogg, options.max_lpc_order);
1834 OggFLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.ogg, options.qlp_coeff_precision);
1835 OggFLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg, options.do_qlp_coeff_prec_search);
1836 OggFLAC__stream_encoder_set_do_escape_coding(e->encoder.ogg, options.do_escape_coding);
1837 OggFLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.ogg, options.do_exhaustive_model_search);
1838 OggFLAC__stream_encoder_set_min_residual_partition_order(e->encoder.ogg, options.min_residual_partition_order);
1839 OggFLAC__stream_encoder_set_max_residual_partition_order(e->encoder.ogg, options.max_residual_partition_order);
1840 OggFLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.ogg, options.rice_parameter_search_dist);
1841 OggFLAC__stream_encoder_set_total_samples_estimate(e->encoder.ogg, e->total_samples_to_encode);
1842 OggFLAC__stream_encoder_set_metadata(e->encoder.ogg, (num_metadata > 0)? metadata : 0, num_metadata);
1844 OggFLAC__stream_encoder_disable_constant_subframes(e->encoder.ogg, options.debug.disable_constant_subframes);
1845 OggFLAC__stream_encoder_disable_fixed_subframes(e->encoder.ogg, options.debug.disable_fixed_subframes);
1846 OggFLAC__stream_encoder_disable_verbatim_subframes(e->encoder.ogg, options.debug.disable_verbatim_subframes);
1848 init_status = OggFLAC__stream_encoder_init_file(e->encoder.ogg, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
1849 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1850 print_error_with_init_status(e, "ERROR initializing encoder", init_status);
1852 FLAC__metadata_object_delete(cuesheet);
1859 FLAC__stream_encoder_set_verify(e->encoder.flac, options.verify);
1860 FLAC__stream_encoder_set_streamable_subset(e->encoder.flac, !options.lax);
1861 FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.flac, options.do_mid_side);
1862 FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.flac, options.loose_mid_side);
1863 FLAC__stream_encoder_set_channels(e->encoder.flac, channels);
1864 FLAC__stream_encoder_set_bits_per_sample(e->encoder.flac, bps);
1865 FLAC__stream_encoder_set_sample_rate(e->encoder.flac, sample_rate);
1866 FLAC__stream_encoder_set_blocksize(e->encoder.flac, options.blocksize);
1867 FLAC__stream_encoder_set_apodization(e->encoder.flac, options.apodizations);
1868 FLAC__stream_encoder_set_max_lpc_order(e->encoder.flac, options.max_lpc_order);
1869 FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.flac, options.qlp_coeff_precision);
1870 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac, options.do_qlp_coeff_prec_search);
1871 FLAC__stream_encoder_set_do_escape_coding(e->encoder.flac, options.do_escape_coding);
1872 FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.flac, options.do_exhaustive_model_search);
1873 FLAC__stream_encoder_set_min_residual_partition_order(e->encoder.flac, options.min_residual_partition_order);
1874 FLAC__stream_encoder_set_max_residual_partition_order(e->encoder.flac, options.max_residual_partition_order);
1875 FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.flac, options.rice_parameter_search_dist);
1876 FLAC__stream_encoder_set_total_samples_estimate(e->encoder.flac, e->total_samples_to_encode);
1877 FLAC__stream_encoder_set_metadata(e->encoder.flac, (num_metadata > 0)? metadata : 0, num_metadata);
1879 FLAC__stream_encoder_disable_constant_subframes(e->encoder.flac, options.debug.disable_constant_subframes);
1880 FLAC__stream_encoder_disable_fixed_subframes(e->encoder.flac, options.debug.disable_fixed_subframes);
1881 FLAC__stream_encoder_disable_verbatim_subframes(e->encoder.flac, options.debug.disable_verbatim_subframes);
1883 init_status = FLAC__stream_encoder_init_file(e->encoder.flac, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
1884 if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1885 print_error_with_init_status(e, "ERROR initializing encoder", init_status);
1887 FLAC__metadata_object_delete(cuesheet);
1893 FLAC__metadata_object_delete(cuesheet);
1898 FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples)
1900 if(e->replay_gain) {
1901 if(!grabbag__replaygain_analyze(buffer, e->channels==2, e->bits_per_sample, samples)) {
1902 flac__utils_printf(stderr, 1, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename);
1906 #ifdef FLAC__HAS_OGG
1908 return OggFLAC__stream_encoder_process(e->encoder.ogg, buffer, samples);
1911 return FLAC__stream_encoder_process(e->encoder.flac, buffer, samples);
1914 FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e)
1916 const FLAC__bool only_placeholders = e->is_stdout;
1917 FLAC__bool has_real_points;
1919 if(num_requested_seek_points == 0 && 0 == cuesheet)
1922 if(num_requested_seek_points < 0) {
1923 requested_seek_points = "10s;";
1924 num_requested_seek_points = 1;
1927 if(num_requested_seek_points > 0) {
1928 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))
1934 const FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet;
1935 for(i = 0; i < cs->num_tracks; i++) {
1936 const FLAC__StreamMetadata_CueSheet_Track *tr = cs->tracks+i;
1937 for(j = 0; j < tr->num_indices; j++) {
1938 if(!FLAC__metadata_object_seektable_template_append_point(e->seek_table_template, tr->offset + tr->indices[j].offset))
1940 has_real_points = true;
1944 if(!FLAC__metadata_object_seektable_template_sort(e->seek_table_template, /*compact=*/true))
1948 if(has_real_points) {
1950 flac__utils_printf(stderr, 1, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename);
1957 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
1959 /* convert from mm:ss.sss to sample number if necessary */
1960 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
1962 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
1963 if(spec->is_relative && spec->value.samples == 0) {
1964 spec->is_relative = false;
1968 /* in any other case the total samples in the input must be known */
1969 if(total_samples_in_input == 0) {
1970 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when input length is unknown\n", inbasefilename);
1974 FLAC__ASSERT(spec->value_is_samples);
1976 /* convert relative specifications to absolute */
1977 if(spec->is_relative) {
1978 if(spec->value.samples <= 0)
1979 spec->value.samples += (FLAC__int64)total_samples_in_input;
1981 spec->value.samples += skip;
1982 spec->is_relative = false;
1986 if(spec->value.samples < 0) {
1987 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
1990 if((FLAC__uint64)spec->value.samples <= skip) {
1991 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
1994 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
1995 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
2002 FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata)
2004 FLAC__bool metadata_picture_has_type1 = false;
2005 FLAC__bool metadata_picture_has_type2 = false;
2008 FLAC__ASSERT(0 != metadata);
2009 for(i = 0; i < num_metadata; i++) {
2010 const FLAC__StreamMetadata *m = metadata[i];
2011 if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
2012 if(!FLAC__format_seektable_is_legal(&m->data.seek_table)) {
2013 flac__utils_printf(stderr, 1, "%s: ERROR: SEEKTABLE metadata block is invalid\n", e->inbasefilename);
2017 else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
2018 if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0)) {
2019 flac__utils_printf(stderr, 1, "%s: ERROR: CUESHEET metadata block is invalid\n", e->inbasefilename);
2023 else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
2024 const char *error = 0;
2025 if(!FLAC__format_picture_is_legal(&m->data.picture, &error)) {
2026 flac__utils_printf(stderr, 1, "%s: ERROR: PICTURE metadata block is invalid: %s\n", e->inbasefilename, error);
2029 if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
2030 if(metadata_picture_has_type1) {
2031 flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 1 (32x32 icon) in the file\n", e->inbasefilename);
2034 metadata_picture_has_type1 = true;
2036 else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
2037 if(metadata_picture_has_type2) {
2038 flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 2 (icon) in the file\n", e->inbasefilename);
2041 metadata_picture_has_type2 = true;
2049 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)
2051 unsigned wide_sample, sample, channel, byte;
2054 if(is_unsigned_samples) {
2055 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2056 for(channel = 0; channel < channels; channel++, sample++)
2057 dest[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
2060 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2061 for(channel = 0; channel < channels; channel++, sample++)
2062 dest[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
2065 else if(bps == 16) {
2066 if(is_big_endian != is_big_endian_host_) {
2068 const unsigned bytes = wide_samples * channels * (bps >> 3);
2069 for(byte = 0; byte < bytes; byte += 2) {
2070 tmp = ucbuffer_[byte];
2071 ucbuffer_[byte] = ucbuffer_[byte+1];
2072 ucbuffer_[byte+1] = tmp;
2075 if(is_unsigned_samples) {
2076 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2077 for(channel = 0; channel < channels; channel++, sample++)
2078 dest[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
2081 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2082 for(channel = 0; channel < channels; channel++, sample++)
2083 dest[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
2086 else if(bps == 24) {
2087 if(!is_big_endian) {
2089 const unsigned bytes = wide_samples * channels * (bps >> 3);
2090 for(byte = 0; byte < bytes; byte += 3) {
2091 tmp = ucbuffer_[byte];
2092 ucbuffer_[byte] = ucbuffer_[byte+2];
2093 ucbuffer_[byte+2] = tmp;
2096 if(is_unsigned_samples) {
2097 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2098 for(channel = 0; channel < channels; channel++, sample++) {
2099 dest[channel][wide_sample] = ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
2100 dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
2101 dest[channel][wide_sample] |= ucbuffer_[byte++];
2102 dest[channel][wide_sample] -= 0x800000;
2106 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2107 for(channel = 0; channel < channels; channel++, sample++) {
2108 dest[channel][wide_sample] = scbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
2109 dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
2110 dest[channel][wide_sample] |= ucbuffer_[byte++];
2118 FLAC__int32 mask = (1<<shift)-1;
2119 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
2120 for(channel = 0; channel < channels; channel++) {
2121 if(dest[channel][wide_sample] & mask) {
2122 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);
2125 dest[channel][wide_sample] >>= shift;
2131 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)
2133 EncoderSession *encoder_session = (EncoderSession*)client_data;
2135 (void)encoder, (void)total_frames_estimate;
2137 encoder_session->bytes_written = bytes_written;
2138 encoder_session->samples_written = samples_written;
2140 if(encoder_session->total_samples_to_encode > 0 && !((frames_written-1) & encoder_session->stats_mask))
2141 print_stats(encoder_session);
2144 FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
2147 FLACDecoderData *data = (FLACDecoderData*)client_data;
2150 if (data->fatal_error)
2151 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2153 /* use up lookahead first */
2154 if (data->lookahead_length) {
2155 n = min(data->lookahead_length, *bytes);
2156 memcpy(buffer, data->lookahead, n);
2158 data->lookahead += n;
2159 data->lookahead_length -= n;
2162 /* get the rest from file */
2164 *bytes = n + fread(buffer, 1, *bytes-n, data->encoder_session->fin);
2165 return ferror(data->encoder_session->fin)? FLAC__STREAM_DECODER_READ_STATUS_ABORT : FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2168 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2171 FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
2173 FLACDecoderData *data = (FLACDecoderData*)client_data;
2176 if(fseeko(data->encoder_session->fin, (off_t)absolute_byte_offset, SEEK_SET) < 0)
2177 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
2179 return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
2182 FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
2184 FLACDecoderData *data = (FLACDecoderData*)client_data;
2188 if((pos = ftello(data->encoder_session->fin)) < 0)
2189 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
2191 *absolute_byte_offset = (FLAC__uint64)pos;
2192 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
2196 FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
2198 FLACDecoderData *data = (FLACDecoderData*)client_data;
2201 if(0 == data->filesize)
2202 return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
2204 *stream_length = (FLAC__uint64)data->filesize;
2205 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
2209 FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data)
2211 FLACDecoderData *data = (FLACDecoderData*)client_data;
2214 return feof(data->encoder_session->fin)? true : false;
2217 FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
2219 FLACDecoderData *data = (FLACDecoderData*)client_data;
2220 FLAC__uint64 n = min(data->samples_left_to_process, frame->header.blocksize);
2223 if(!EncoderSession_process(data->encoder_session, buffer, (unsigned)n)) {
2224 print_error_with_state(data->encoder_session, "ERROR during encoding");
2225 data->fatal_error = true;
2226 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2229 data->samples_left_to_process -= n;
2230 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2233 void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
2235 FLACDecoderData *data = (FLACDecoderData*)client_data;
2238 if (data->fatal_error)
2242 data->num_metadata_blocks == sizeof(data->metadata_blocks)/sizeof(data->metadata_blocks[0]) ||
2243 0 == (data->metadata_blocks[data->num_metadata_blocks] = FLAC__metadata_object_clone(metadata))
2245 data->fatal_error = true;
2247 data->num_metadata_blocks++;
2250 void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
2252 FLACDecoderData *data = (FLACDecoderData*)client_data;
2255 flac__utils_printf(stderr, 1, "%s: ERROR got %s while decoding FLAC input\n", data->encoder_session->inbasefilename, FLAC__StreamDecoderErrorStatusString[status]);
2256 data->fatal_error = true;
2259 FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset)
2262 unsigned last_line_read;
2263 const char *error_message;
2265 if(0 == cuesheet_filename)
2268 if(lead_out_offset == 0) {
2269 flac__utils_printf(stderr, 1, "%s: ERROR cannot import cuesheet when the number of input samples to encode is unknown\n", inbasefilename);
2273 if(0 == (f = fopen(cuesheet_filename, "r"))) {
2274 flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading: %s\n", inbasefilename, cuesheet_filename, strerror(errno));
2278 *cuesheet = grabbag__cuesheet_parse(f, &error_message, &last_line_read, is_cdda, lead_out_offset);
2282 if(0 == *cuesheet) {
2283 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\" on line %u: %s\n", inbasefilename, cuesheet_filename, last_line_read, error_message);
2287 if(!FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/false, &error_message)) {
2288 flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\": %s\n", inbasefilename, cuesheet_filename, error_message);
2292 /* if we're expecting CDDA, warn about non-compliance */
2293 if(is_cdda && !FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/true, &error_message)) {
2294 flac__utils_printf(stderr, 1, "%s: WARNING cuesheet \"%s\" is not audio CD compliant: %s\n", inbasefilename, cuesheet_filename, error_message);
2295 (*cuesheet)->data.cue_sheet.is_cd = false;
2301 void print_stats(const EncoderSession *encoder_session)
2303 const FLAC__uint64 samples_written = min(encoder_session->total_samples_to_encode, encoder_session->samples_written);
2304 #if defined _MSC_VER || defined __MINGW32__
2305 /* with MSVC you have to spoon feed it the casting */
2306 const double progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)encoder_session->total_samples_to_encode;
2307 const double ratio = (double)(FLAC__int64)encoder_session->bytes_written / ((double)(FLAC__int64)encoder_session->unencoded_size * min(1.0, progress));
2309 const double progress = (double)samples_written / (double)encoder_session->total_samples_to_encode;
2310 const double ratio = (double)encoder_session->bytes_written / ((double)encoder_session->unencoded_size * min(1.0, progress));
2314 if(samples_written == encoder_session->total_samples_to_encode) {
2315 flac__utils_printf(stderr, 2, "\r%s:%s wrote %u bytes, ratio=%0.3f",
2316 encoder_session->inbasefilename,
2317 encoder_session->verify? " Verify OK," : "",
2318 (unsigned)encoder_session->bytes_written,
2323 flac__utils_printf(stderr, 2, "\r%s: %u%% complete, ratio=%0.3f", encoder_session->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
2327 void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status)
2329 const int ilen = strlen(e->inbasefilename) + 1;
2330 const char *state_string = "";
2332 flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2334 flac__utils_printf(stderr, 1, "%*s init_status = %s\n", ilen, "", FLAC__StreamEncoderInitStatusString[init_status]);
2336 if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR) {
2337 #ifdef FLAC__HAS_OGG
2339 state_string = OggFLAC__stream_encoder_get_resolved_state_string(e->encoder.ogg);
2342 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder.flac);
2344 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2346 /* print out some more info for some errors: */
2348 0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])
2349 #ifdef FLAC__HAS_OGG
2350 || 0 == strcmp(state_string, OggFLAC__StreamEncoderStateString[OggFLAC__STREAM_ENCODER_CLIENT_ERROR])
2353 flac__utils_printf(stderr, 1,
2355 "An error occurred while writing; the most common cause is that the disk is full.\n"
2359 0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_IO_ERROR])
2360 #ifdef FLAC__HAS_OGG
2361 || 0 == strcmp(state_string, OggFLAC__StreamEncoderStateString[OggFLAC__STREAM_ENCODER_IO_ERROR])
2364 flac__utils_printf(stderr, 1,
2366 "An error occurred opening the output file; it is likely that the output\n"
2367 "directory does not exist or is not writable, the output file already exists and\n"
2368 "is not writable, or the disk is full.\n"
2372 else if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE) {
2373 flac__utils_printf(stderr, 1,
2375 "The encoding parameters specified do not conform to the FLAC Subset and may not\n"
2376 "be streamable or playable in hardware devices. Add --lax to the command-line\n"
2377 "options to encode with these parameters anyway.\n"
2382 void print_error_with_state(const EncoderSession *e, const char *message)
2384 const int ilen = strlen(e->inbasefilename) + 1;
2385 const char *state_string;
2387 flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
2389 #ifdef FLAC__HAS_OGG
2391 state_string = OggFLAC__stream_encoder_get_resolved_state_string(e->encoder.ogg);
2394 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder.flac);
2396 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
2398 /* print out some more info for some errors: */
2400 0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])
2401 #ifdef FLAC__HAS_OGG
2402 || 0 == strcmp(state_string, OggFLAC__StreamEncoderStateString[OggFLAC__STREAM_ENCODER_CLIENT_ERROR])
2405 flac__utils_printf(stderr, 1,
2407 "An error occurred while writing; the most common cause is that the disk is full.\n"
2412 void print_verify_error(EncoderSession *e)
2414 FLAC__uint64 absolute_sample;
2415 unsigned frame_number;
2418 FLAC__int32 expected;
2421 #ifdef FLAC__HAS_OGG
2423 OggFLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.ogg, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2426 FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.flac, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2428 flac__utils_printf(stderr, 1, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
2429 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);
2430 flac__utils_printf(stderr, 1, " In all known cases, verify errors are caused by hardware problems,\n");
2431 flac__utils_printf(stderr, 1, " usually overclocking or bad RAM. Delete %s\n", e->outfilename);
2432 flac__utils_printf(stderr, 1, " and repeat the flac command exactly as before. If it does not give a\n");
2433 flac__utils_printf(stderr, 1, " verify error in the exact same place each time you try it, then there is\n");
2434 flac__utils_printf(stderr, 1, " a problem with your hardware; please see the FAQ:\n");
2435 flac__utils_printf(stderr, 1, " http://flac.sourceforge.net/faq.html#tools__hardware_prob\n");
2436 flac__utils_printf(stderr, 1, " If it does fail in the exact same place every time, keep\n");
2437 flac__utils_printf(stderr, 1, " %s and submit a bug report to:\n", e->outfilename);
2438 flac__utils_printf(stderr, 1, " https://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
2439 flac__utils_printf(stderr, 1, " Make sure to upload the FLAC file and use the \"Monitor\" feature to\n");
2440 flac__utils_printf(stderr, 1, " monitor the bug status.\n");
2441 flac__utils_printf(stderr, 1, "Verify FAILED! Do not trust %s\n", e->outfilename);
2444 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
2446 size_t bytes_read = fread(val, 1, 2, f);
2448 if(bytes_read == 0) {
2450 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2456 else if(bytes_read < 2) {
2457 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2461 if(is_big_endian_host_) {
2462 FLAC__byte tmp, *b = (FLAC__byte*)val;
2463 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
2469 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2471 size_t bytes_read = fread(val, 1, 4, f);
2473 if(bytes_read == 0) {
2475 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2481 else if(bytes_read < 4) {
2482 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2486 if(is_big_endian_host_) {
2487 FLAC__byte tmp, *b = (FLAC__byte*)val;
2488 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
2489 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
2495 FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
2497 unsigned char buf[4];
2498 size_t bytes_read= fread(buf, 1, 2, f);
2500 if(bytes_read==0U && eof_ok)
2502 else if(bytes_read<2U) {
2503 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2507 /* this is independent of host endianness */
2508 *val= (FLAC__uint16)(buf[0])<<8 | buf[1];
2513 FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2515 unsigned char buf[4];
2516 size_t bytes_read= fread(buf, 1, 4, f);
2518 if(bytes_read==0U && eof_ok)
2520 else if(bytes_read<4U) {
2521 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2525 /* this is independent of host endianness */
2526 *val= (FLAC__uint32)(buf[0])<<24 | (FLAC__uint32)(buf[1])<<16 |
2527 (FLAC__uint32)(buf[2])<<8 | buf[3];
2532 FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2533 /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
2534 * convert it into an integral value and store in 'val'. Return false if only
2535 * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f' and 'eof_ok' is
2536 * false, or if the value is negative, between zero and one, or too large to be
2537 * represented by 'val'; return true otherwise.
2541 unsigned char buf[10];
2542 size_t bytes_read= fread(buf, 1U, 10U, f);
2543 FLAC__int16 e= ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
2544 FLAC__int16 shift= 63-e;
2547 if(bytes_read==0U && eof_ok)
2549 else if(bytes_read<10U) {
2550 flac__utils_printf(stderr, 1, "%s: ERROR: unexpected EOF\n", fn);
2553 else if((buf[0]>>7)==1U || e<0 || e>63) {
2554 flac__utils_printf(stderr, 1, "%s: ERROR: invalid floating-point value\n", fn);
2558 for(i= 0U; i<8U; ++i)
2559 p|= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
2560 *val= (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1));
2565 FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset)
2567 static unsigned char dump[8192];
2570 long need = (long)min(offset, LONG_MAX);
2571 if(fseeko(f, need, SEEK_CUR) < 0) {
2572 need = (long)min(offset, sizeof(dump));
2573 if((long)fread(dump, 1, need, f) < need)
2578 #if 0 /* pure non-fseek() version */
2580 const long need = (long)min(offset, sizeof(dump));
2581 if(fread(dump, 1, need, f) < need)
2589 unsigned count_channel_mask_bits(FLAC__uint32 mask)
2600 FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels)
2602 FLAC__uint32 x = 0x80000000;
2603 unsigned count = count_channel_mask_bits(mask);
2604 while(x && count > channels) {
2611 FLAC__ASSERT(count_channel_mask_bits(mask) == channels);