1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002,2003,2004 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.
19 #if defined _WIN32 && !defined __CYGWIN__
20 /* where MSVC puts unlink() */
25 #include <limits.h> /* for LONG_MAX */
26 #include <math.h> /* for floor() */
28 #include <stdio.h> /* for FILE etc. */
29 #include <stdlib.h> /* for malloc */
30 #include <string.h> /* for strcmp() */
31 #if defined _MSC_VER || defined __MINGW32__
37 #include "share/grabbag.h"
45 #include "OggFLAC/stream_encoder.h"
46 #include "OggFLAC/file_encoder.h"
52 #define min(x,y) ((x)<(y)?(x):(y))
56 #define max(x,y) ((x)>(y)?(x):(y))
58 /* this MUST be >= 588 so that sector aligning can take place with one read */
59 #define CHUNK_OF_SAMPLES 2048
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 * We use *.stream for encoding to stdout
86 * We use *.file for encoding to a regular file
90 FLAC__StreamEncoder *stream;
91 FLAC__FileEncoder *file;
95 OggFLAC__StreamEncoder *stream;
96 OggFLAC__FileEncoder *file;
103 FLAC__StreamMetadata *seek_table_template;
107 static FLAC__bool is_big_endian_host_;
109 static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
110 static signed char *scbuffer_ = (signed char *)ucbuffer_;
111 static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_;
112 static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_;
114 static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
115 static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
119 * unpublished debug routines from the FLAC libs
121 extern FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
122 extern FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
123 extern FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
124 extern FLAC__bool FLAC__file_encoder_disable_constant_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
125 extern FLAC__bool FLAC__file_encoder_disable_fixed_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
126 extern FLAC__bool FLAC__file_encoder_disable_verbatim_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
128 extern FLAC__bool OggFLAC__stream_encoder_disable_constant_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
129 extern FLAC__bool OggFLAC__stream_encoder_disable_fixed_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
130 extern FLAC__bool OggFLAC__stream_encoder_disable_verbatim_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
131 extern FLAC__bool OggFLAC__file_encoder_disable_constant_subframes(OggFLAC__FileEncoder *encoder, FLAC__bool value);
132 extern FLAC__bool OggFLAC__file_encoder_disable_fixed_subframes(OggFLAC__FileEncoder *encoder, FLAC__bool value);
133 extern FLAC__bool OggFLAC__file_encoder_disable_verbatim_subframes(OggFLAC__FileEncoder *encoder, FLAC__bool value);
139 static FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FLAC__bool verbose, FILE *infile, const char *infilename, const char *outfilename);
140 static void EncoderSession_destroy(EncoderSession *e);
141 static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero);
142 static int EncoderSession_finish_error(EncoderSession *e);
143 static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate);
144 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
145 static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
146 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
147 static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps);
149 static FLAC__StreamEncoderWriteStatus ogg_stream_encoder_write_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
150 static void ogg_stream_encoder_metadata_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
151 static void ogg_file_encoder_progress_callback(const OggFLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
153 static FLAC__StreamEncoderWriteStatus flac_stream_encoder_write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
154 static void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
155 static void flac_file_encoder_progress_callback(const FLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
156 static FLAC__bool parse_cuesheet_(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__uint64 lead_out_offset);
157 static void print_stats(const EncoderSession *encoder_session);
158 static void print_error_with_state(const EncoderSession *e, const char *message);
159 static void print_verify_error(EncoderSession *e);
160 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
161 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
162 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
163 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
164 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
170 flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const char *outfilename,
171 const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
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;
180 (void)infilesize; /* silence compiler warning about unused parameter */
181 (void)lookahead; /* silence compiler warning about unused parameter */
182 (void)lookahead_length; /* silence compiler warning about unused parameter */
185 EncoderSession_construct(
188 options.common.use_ogg,
192 options.common.verify,
193 options.common.verbose,
201 /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
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 fprintf(stderr, "%s: ERROR: incomplete chunk identifier\n", encoder_session.inbasefilename);
212 return EncoderSession_finish_error(&encoder_session);
215 if(got_comm_chunk==false && !strncmp(chunk_id, "COMM", 4)) { /* common chunk */
218 /* COMM chunk size */
219 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
220 return EncoderSession_finish_error(&encoder_session);
222 fprintf(stderr, "%s: ERROR: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
223 return EncoderSession_finish_error(&encoder_session);
226 fprintf(stderr, "%s: WARNING: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
227 skip= (xx-18U)+(xx & 1U);
229 /* number of channels */
230 if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
231 return EncoderSession_finish_error(&encoder_session);
232 else if(x==0U || x>FLAC__MAX_CHANNELS) {
233 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned int)x);
234 return EncoderSession_finish_error(&encoder_session);
236 else if(options.common.sector_align && x!=2U) {
237 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
238 return EncoderSession_finish_error(&encoder_session);
242 /* number of sample frames */
243 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
244 return EncoderSession_finish_error(&encoder_session);
247 /* bits per sample */
248 if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
249 return EncoderSession_finish_error(&encoder_session);
250 else if(x!=8U && x!=16U && x!=24U) {
251 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_session.inbasefilename, (unsigned int)x);
252 return EncoderSession_finish_error(&encoder_session);
254 else if(options.common.sector_align && x!=16U) {
255 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
256 return EncoderSession_finish_error(&encoder_session);
261 if(!read_sane_extended(infile, &xx, false, encoder_session.inbasefilename))
262 return EncoderSession_finish_error(&encoder_session);
263 else if(!FLAC__format_sample_rate_is_valid(xx)) {
264 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned int)xx);
265 return EncoderSession_finish_error(&encoder_session);
267 else if(options.common.sector_align && xx!=44100U) {
268 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)xx);
269 return EncoderSession_finish_error(&encoder_session);
273 /* skip any extra data in the COMM chunk */
274 FLAC__ASSERT(skip<=LONG_MAX);
275 while(skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
276 unsigned int need= min(skip, sizeof ucbuffer_);
277 if(fread(ucbuffer_, 1U, need, infile)<need) {
278 fprintf(stderr, "%s: ERROR during read while skipping extra COMM data\n", encoder_session.inbasefilename);
279 return EncoderSession_finish_error(&encoder_session);
285 * now that we know the sample rate, canonicalize the
286 * --skip string to a number of samples:
288 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, sample_rate);
289 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
290 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
291 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
293 got_comm_chunk= true;
295 else if(got_ssnd_chunk==false && !strncmp(chunk_id, "SSND", 4)) { /* sound data chunk */
296 unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
297 size_t bytes_per_frame= channels*(bps>>3);
298 FLAC__uint64 total_samples_in_input, trim = 0;
299 FLAC__bool pad= false;
301 if(got_comm_chunk==false) {
302 fprintf(stderr, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", encoder_session.inbasefilename);
303 return EncoderSession_finish_error(&encoder_session);
306 /* SSND chunk size */
307 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
308 return EncoderSession_finish_error(&encoder_session);
309 else if(xx!=(sample_frames*bytes_per_frame + 8U)) {
310 fprintf(stderr, "%s: ERROR: SSND chunk size inconsistent with sample frame count\n", encoder_session.inbasefilename);
311 return EncoderSession_finish_error(&encoder_session);
314 pad= (data_bytes & 1U) ? true : false;
315 data_bytes-= 8U; /* discount the offset and block size fields */
318 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
319 return EncoderSession_finish_error(&encoder_session);
321 fprintf(stderr, "%s: ERROR: offset is %u; must be 0\n", encoder_session.inbasefilename, (unsigned int)xx);
322 return EncoderSession_finish_error(&encoder_session);
327 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
328 return EncoderSession_finish_error(&encoder_session);
330 fprintf(stderr, "%s: ERROR: block size is %u; must be 0\n", encoder_session.inbasefilename, (unsigned int)xx);
331 return EncoderSession_finish_error(&encoder_session);
335 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
336 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
337 total_samples_in_input = data_bytes / bytes_per_frame + *options.common.align_reservoir_samples;
340 * now that we know the input size, canonicalize the
341 * --until string to an absolute sample number:
343 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, sample_rate, encoder_session.skip, total_samples_in_input))
344 return EncoderSession_finish_error(&encoder_session);
345 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
346 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
348 if(encoder_session.skip>0U) {
349 FLAC__uint64 remaining= encoder_session.skip*bytes_per_frame;
351 /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
352 /* is guaranteed to be less than LONG_MAX */
355 unsigned long skip= (unsigned long)(remaining % (1U<<30));
357 FLAC__ASSERT(skip<=LONG_MAX);
358 while(skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
359 unsigned int need= min(skip, sizeof ucbuffer_);
360 if(fread(ucbuffer_, 1U, need, infile)<need) {
361 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
362 return EncoderSession_finish_error(&encoder_session);
371 data_bytes-= (unsigned int)encoder_session.skip*bytes_per_frame; /*@@@ WATCHOUT: 4GB limit */
372 encoder_session.total_samples_to_encode= total_samples_in_input - encoder_session.skip;
373 if(encoder_session.until > 0) {
374 trim = total_samples_in_input - encoder_session.until;
375 FLAC__ASSERT(total_samples_in_input > 0);
376 FLAC__ASSERT(!options.common.sector_align);
377 data_bytes-= (unsigned int)trim*bytes_per_frame;
378 encoder_session.total_samples_to_encode-= trim;
380 if(options.common.sector_align) {
381 align_remainder= (unsigned int)(encoder_session.total_samples_to_encode % 588U);
382 if(options.common.is_last_file)
383 encoder_session.total_samples_to_encode+= (588U-align_remainder); /* will pad with zeroes */
385 encoder_session.total_samples_to_encode-= align_remainder; /* will stop short and carry over to next file */
388 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
389 encoder_session.unencoded_size= encoder_session.total_samples_to_encode*bytes_per_frame+54;
391 if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
392 return EncoderSession_finish_error(&encoder_session);
394 /* first do any samples in the reservoir */
395 if(options.common.sector_align && *options.common.align_reservoir_samples>0U) {
397 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
398 print_error_with_state(&encoder_session, "ERROR during encoding");
399 return EncoderSession_finish_error(&encoder_session);
403 /* decrement the data_bytes counter if we need to align the file */
404 if(options.common.sector_align) {
405 if(options.common.is_last_file)
406 *options.common.align_reservoir_samples= 0U;
408 *options.common.align_reservoir_samples= align_remainder;
409 data_bytes-= (*options.common.align_reservoir_samples)*bytes_per_frame;
413 /* now do from the file */
414 while(data_bytes>0) {
415 size_t bytes_read= fread(ucbuffer_, 1U, min(data_bytes, CHUNK_OF_SAMPLES*bytes_per_frame), infile);
419 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
420 return EncoderSession_finish_error(&encoder_session);
422 else if(feof(infile)) {
423 fprintf(stderr, "%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);
428 if(bytes_read % bytes_per_frame != 0U) {
429 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
430 return EncoderSession_finish_error(&encoder_session);
433 unsigned int frames= bytes_read/bytes_per_frame;
434 format_input(input_, frames, true, false, channels, bps);
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__uint64 remaining= (unsigned int)trim*bytes_per_frame;
449 FLAC__ASSERT(!options.common.sector_align);
451 /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
452 /* is guaranteed to be less than LONG_MAX */
455 unsigned long skip= (unsigned long)(remaining % (1U<<30));
457 FLAC__ASSERT(skip<=LONG_MAX);
458 while(skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
459 unsigned int need= min(skip, sizeof ucbuffer_);
460 if(fread(ucbuffer_, 1U, need, infile)<need) {
461 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
462 return EncoderSession_finish_error(&encoder_session);
471 /* now read unaligned samples into reservoir or pad with zeroes if necessary */
472 if(options.common.sector_align) {
473 if(options.common.is_last_file) {
474 unsigned int pad_frames= 588U-align_remainder;
476 if(pad_frames<588U) {
479 info_align_zero= pad_frames;
480 for(i= 0U; i<channels; ++i)
481 memset(input_[i], 0, pad_frames*(bps>>3));
483 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, pad_frames)) {
484 print_error_with_state(&encoder_session, "ERROR during encoding");
485 return EncoderSession_finish_error(&encoder_session);
490 if(*options.common.align_reservoir_samples > 0) {
491 size_t bytes_read= fread(ucbuffer_, 1U, (*options.common.align_reservoir_samples)*bytes_per_frame, infile);
493 FLAC__ASSERT(CHUNK_OF_SAMPLES>=588U);
494 if(bytes_read==0U && ferror(infile)) {
495 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
496 return EncoderSession_finish_error(&encoder_session);
498 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame)
499 fprintf(stderr, "%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);
501 info_align_carry= *options.common.align_reservoir_samples;
502 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, true, false, channels, bps);
511 if(fread(&tmp, 1U, 1U, infile)<1U) {
512 fprintf(stderr, "%s: ERROR during read of SSND pad byte\n", encoder_session.inbasefilename);
513 return EncoderSession_finish_error(&encoder_session);
517 got_ssnd_chunk= true;
519 else { /* other chunk */
520 if(!strncmp(chunk_id, "COMM", 4))
521 fprintf(stderr, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_session.inbasefilename);
522 else if(!strncmp(chunk_id, "SSND", 4))
523 fprintf(stderr, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_session.inbasefilename);
525 fprintf(stderr, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_session.inbasefilename, chunk_id);
528 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
529 return EncoderSession_finish_error(&encoder_session);
531 unsigned long skip= xx+(xx & 1U);
533 FLAC__ASSERT(skip<=LONG_MAX);
534 while(skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
535 unsigned int need= min(skip, sizeof ucbuffer_);
536 if(fread(ucbuffer_, 1U, need, infile)<need) {
537 fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_session.inbasefilename);
538 return EncoderSession_finish_error(&encoder_session);
546 if(got_ssnd_chunk==false && sample_frames!=0U) {
547 fprintf(stderr, "%s: ERROR: missing SSND chunk\n", encoder_session.inbasefilename);
548 return EncoderSession_finish_error(&encoder_session);
551 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
554 int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
556 EncoderSession encoder_session;
557 FLAC__bool is_unsigned_samples = false;
558 unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
559 size_t bytes_per_wide_sample, bytes_read;
562 FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
563 unsigned align_remainder = 0;
564 int info_align_carry = -1, info_align_zero = -1;
568 (void)lookahead_length;
571 EncoderSession_construct(
574 options.common.use_ogg,
578 options.common.verify,
579 options.common.verbose,
588 * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
590 while(!feof(infile)) {
591 if(!read_little_endian_uint32(infile, &xx, true, encoder_session.inbasefilename))
592 return EncoderSession_finish_error(&encoder_session);
595 if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
596 unsigned block_align;
598 /* fmt sub-chunk size */
599 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
600 return EncoderSession_finish_error(&encoder_session);
602 fprintf(stderr, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
603 return EncoderSession_finish_error(&encoder_session);
605 else if(xx != 16 && xx != 18) {
606 fprintf(stderr, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
609 /* compression code */
610 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
611 return EncoderSession_finish_error(&encoder_session);
613 fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_session.inbasefilename, (unsigned)x);
614 return EncoderSession_finish_error(&encoder_session);
616 /* number of channels */
617 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
618 return EncoderSession_finish_error(&encoder_session);
619 if(x == 0 || x > FLAC__MAX_CHANNELS) {
620 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned)x);
621 return EncoderSession_finish_error(&encoder_session);
623 else if(options.common.sector_align && x != 2) {
624 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
625 return EncoderSession_finish_error(&encoder_session);
629 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
630 return EncoderSession_finish_error(&encoder_session);
631 if(!FLAC__format_sample_rate_is_valid(xx)) {
632 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned)xx);
633 return EncoderSession_finish_error(&encoder_session);
635 else if(options.common.sector_align && xx != 44100) {
636 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned)xx);
637 return EncoderSession_finish_error(&encoder_session);
640 /* avg bytes per second (ignored) */
641 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
642 return EncoderSession_finish_error(&encoder_session);
644 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
645 return EncoderSession_finish_error(&encoder_session);
647 /* bits per sample */
648 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
649 return EncoderSession_finish_error(&encoder_session);
650 if(x != 8 && x != 16 && x != 24) {
651 fprintf(stderr, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, (unsigned)x);
652 return EncoderSession_finish_error(&encoder_session);
654 else if(options.common.sector_align && x != 16) {
655 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
656 return EncoderSession_finish_error(&encoder_session);
659 if(bps * channels != block_align * 8) {
660 fprintf(stderr, "%s: ERROR: unsupported block alignment (%u), for bits-per-sample=%u, channels=%u\n", encoder_session.inbasefilename, block_align, bps, channels);
661 return EncoderSession_finish_error(&encoder_session);
663 is_unsigned_samples = (x == 8);
665 /* skip any extra data in the fmt sub-chunk */
669 for(left = data_bytes; left > 0; ) {
670 need = min(left, CHUNK_OF_SAMPLES);
671 if(fread(ucbuffer_, 1U, need, infile) < need) {
672 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
673 return EncoderSession_finish_error(&encoder_session);
680 * now that we know the sample rate, canonicalize the
681 * --skip string to a number of samples:
683 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, sample_rate);
684 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
685 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
686 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
688 got_fmt_chunk = true;
690 else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
691 FLAC__uint64 total_samples_in_input, trim = 0;
694 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
695 return EncoderSession_finish_error(&encoder_session);
698 bytes_per_wide_sample = channels * (bps >> 3);
700 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
701 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
702 total_samples_in_input = data_bytes / bytes_per_wide_sample + *options.common.align_reservoir_samples;
705 * now that we know the input size, canonicalize the
706 * --until string to an absolute sample number:
708 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, sample_rate, encoder_session.skip, total_samples_in_input))
709 return EncoderSession_finish_error(&encoder_session);
710 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
711 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
713 if(encoder_session.skip > 0) {
714 if(fseek(infile, bytes_per_wide_sample * (unsigned)encoder_session.skip, SEEK_CUR) < 0) {
715 /* can't seek input, read ahead manually... */
717 for(left = (unsigned)encoder_session.skip; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
718 need = min(left, CHUNK_OF_SAMPLES);
719 if(fread(ucbuffer_, bytes_per_wide_sample, need, infile) < need) {
720 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
721 return EncoderSession_finish_error(&encoder_session);
728 data_bytes -= (unsigned)encoder_session.skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
729 encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
730 if(encoder_session.until > 0) {
731 trim = total_samples_in_input - encoder_session.until;
732 FLAC__ASSERT(total_samples_in_input > 0);
733 FLAC__ASSERT(!options.common.sector_align);
734 data_bytes -= (unsigned int)trim * bytes_per_wide_sample;
735 encoder_session.total_samples_to_encode -= trim;
737 if(options.common.sector_align) {
738 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
739 if(options.common.is_last_file)
740 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
742 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
745 /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
746 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample + 44;
748 if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
749 return EncoderSession_finish_error(&encoder_session);
752 * first do any samples in the reservoir
754 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
755 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
756 print_error_with_state(&encoder_session, "ERROR during encoding");
757 return EncoderSession_finish_error(&encoder_session);
762 * decrement the data_bytes counter if we need to align the file
764 if(options.common.sector_align) {
765 if(options.common.is_last_file) {
766 *options.common.align_reservoir_samples = 0;
769 *options.common.align_reservoir_samples = align_remainder;
770 data_bytes -= (*options.common.align_reservoir_samples) * bytes_per_wide_sample;
775 * now do from the file
777 while(data_bytes > 0) {
778 bytes_read = fread(ucbuffer_, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
779 if(bytes_read == 0) {
781 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
782 return EncoderSession_finish_error(&encoder_session);
784 else if(feof(infile)) {
785 fprintf(stderr, "%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);
790 if(bytes_read % bytes_per_wide_sample != 0) {
791 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
792 return EncoderSession_finish_error(&encoder_session);
795 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
796 format_input(input_, wide_samples, false, is_unsigned_samples, channels, bps);
798 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
799 print_error_with_state(&encoder_session, "ERROR during encoding");
800 return EncoderSession_finish_error(&encoder_session);
802 data_bytes -= bytes_read;
808 if(fseek(infile, bytes_per_wide_sample * (unsigned)trim, SEEK_CUR) < 0) {
809 /* can't seek input, read ahead manually... */
811 for(left = (unsigned)trim; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
812 need = min(left, CHUNK_OF_SAMPLES);
813 if(fread(ucbuffer_, bytes_per_wide_sample, need, infile) < need) {
814 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
815 return EncoderSession_finish_error(&encoder_session);
823 * now read unaligned samples into reservoir or pad with zeroes if necessary
825 if(options.common.sector_align) {
826 if(options.common.is_last_file) {
827 unsigned wide_samples = 588 - align_remainder;
828 if(wide_samples < 588) {
831 info_align_zero = wide_samples;
832 data_bytes = wide_samples * (bps >> 3);
833 for(channel = 0; channel < channels; channel++)
834 memset(input_[channel], 0, data_bytes);
836 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
837 print_error_with_state(&encoder_session, "ERROR during encoding");
838 return EncoderSession_finish_error(&encoder_session);
843 if(*options.common.align_reservoir_samples > 0) {
844 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
845 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
846 if(bytes_read == 0 && ferror(infile)) {
847 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
848 return EncoderSession_finish_error(&encoder_session);
850 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
851 fprintf(stderr, "%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);
855 info_align_carry = *options.common.align_reservoir_samples;
856 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, is_unsigned_samples, channels, bps);
862 got_data_chunk = true;
865 if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
866 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_session.inbasefilename);
868 else if(xx == 0x61746164) { /* "data" */
870 fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_session.inbasefilename);
872 else if(!got_fmt_chunk) {
873 fprintf(stderr, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_session.inbasefilename);
874 return EncoderSession_finish_error(&encoder_session);
881 fprintf(stderr, "%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));
884 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
885 return EncoderSession_finish_error(&encoder_session);
886 if(fseek(infile, xx, SEEK_CUR) < 0) {
887 /* can't seek input, read ahead manually... */
889 const unsigned chunk = sizeof(ucbuffer_);
890 for(left = xx; left > 0; ) {
891 need = min(left, chunk);
892 if(fread(ucbuffer_, 1, need, infile) < need) {
893 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_session.inbasefilename);
894 return EncoderSession_finish_error(&encoder_session);
902 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
905 int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, raw_encode_options_t options)
907 EncoderSession encoder_session;
909 const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
910 unsigned align_remainder = 0;
911 int info_align_carry = -1, info_align_zero = -1;
912 FLAC__uint64 total_samples_in_input = 0;;
914 FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
915 FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
916 FLAC__ASSERT(!options.common.sector_align || options.sample_rate == 44100);
917 FLAC__ASSERT(!options.common.sector_align || infilesize >= 0);
918 FLAC__ASSERT(!options.common.replay_gain || options.channels <= 2);
919 FLAC__ASSERT(!options.common.replay_gain || grabbag__replaygain_is_valid_sample_frequency(options.sample_rate));
922 EncoderSession_construct(
925 options.common.use_ogg,
929 options.common.verify,
930 options.common.verbose,
939 * now that we know the sample rate, canonicalize the
940 * --skip string to a number of samples:
942 flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, options.sample_rate);
943 FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
944 encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
945 FLAC__ASSERT(!options.common.sector_align || encoder_session.skip == 0);
948 total_samples_in_input = 0;
950 /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
951 FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
952 total_samples_in_input = (unsigned)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
956 * now that we know the input size, canonicalize the
957 * --until strings to a number of samples:
959 if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, options.sample_rate, encoder_session.skip, total_samples_in_input))
960 return EncoderSession_finish_error(&encoder_session);
961 encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
962 FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
964 encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
965 if(encoder_session.until > 0) {
966 const FLAC__uint64 trim = total_samples_in_input - encoder_session.until;
967 FLAC__ASSERT(total_samples_in_input > 0);
968 FLAC__ASSERT(!options.common.sector_align);
969 encoder_session.total_samples_to_encode -= trim;
971 if(infilesize >= 0 && options.common.sector_align) {
972 FLAC__ASSERT(encoder_session.skip == 0);
973 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
974 if(options.common.is_last_file)
975 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
977 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
979 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample;
981 if(encoder_session.verbose && encoder_session.total_samples_to_encode <= 0)
982 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
984 if(encoder_session.skip > 0) {
985 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)encoder_session.skip;
986 if(skip_bytes > lookahead_length) {
987 skip_bytes -= lookahead_length;
988 lookahead_length = 0;
989 if(fseek(infile, (long)skip_bytes, SEEK_CUR) < 0) {
990 /* can't seek input, read ahead manually... */
992 const unsigned chunk = sizeof(ucbuffer_);
993 for(left = skip_bytes; left > 0; ) {
994 need = min(left, chunk);
995 if(fread(ucbuffer_, 1, need, infile) < need) {
996 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
997 return EncoderSession_finish_error(&encoder_session);
1004 lookahead += skip_bytes;
1005 lookahead_length -= skip_bytes;
1009 if(!EncoderSession_init_encoder(&encoder_session, options.common, options.channels, options.bps, options.sample_rate))
1010 return EncoderSession_finish_error(&encoder_session);
1013 * first do any samples in the reservoir
1015 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
1016 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
1017 print_error_with_state(&encoder_session, "ERROR during encoding");
1018 return EncoderSession_finish_error(&encoder_session);
1023 * decrement infilesize if we need to align the file
1025 if(options.common.sector_align) {
1026 FLAC__ASSERT(infilesize >= 0);
1027 if(options.common.is_last_file) {
1028 *options.common.align_reservoir_samples = 0;
1031 *options.common.align_reservoir_samples = align_remainder;
1032 infilesize -= (long)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
1033 FLAC__ASSERT(infilesize >= 0);
1038 * now do from the file
1040 if(infilesize < 0) {
1041 while(!feof(infile)) {
1042 if(lookahead_length > 0) {
1043 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1044 memcpy(ucbuffer_, lookahead, lookahead_length);
1045 bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
1046 if(ferror(infile)) {
1047 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
1048 return EncoderSession_finish_error(&encoder_session);
1050 lookahead_length = 0;
1053 bytes_read = fread(ucbuffer_, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
1055 if(bytes_read == 0) {
1056 if(ferror(infile)) {
1057 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
1058 return EncoderSession_finish_error(&encoder_session);
1061 else if(bytes_read % bytes_per_wide_sample != 0) {
1062 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1063 return EncoderSession_finish_error(&encoder_session);
1066 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1067 format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
1069 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1070 print_error_with_state(&encoder_session, "ERROR during encoding");
1071 return EncoderSession_finish_error(&encoder_session);
1077 const FLAC__uint64 max_input_bytes = encoder_session.total_samples_to_encode * bytes_per_wide_sample;
1078 FLAC__uint64 total_input_bytes_read = 0;
1079 while(total_input_bytes_read < max_input_bytes) {
1081 size_t wanted = (CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1082 wanted = min(wanted, (size_t)(max_input_bytes - total_input_bytes_read));
1084 if(lookahead_length > 0) {
1085 FLAC__ASSERT(lookahead_length <= wanted);
1086 memcpy(ucbuffer_, lookahead, lookahead_length);
1087 wanted -= lookahead_length;
1088 bytes_read = lookahead_length;
1090 bytes_read += fread(ucbuffer_+lookahead_length, sizeof(unsigned char), wanted, infile);
1091 if(ferror(infile)) {
1092 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
1093 return EncoderSession_finish_error(&encoder_session);
1096 lookahead_length = 0;
1099 bytes_read = fread(ucbuffer_, sizeof(unsigned char), wanted, infile);
1102 if(bytes_read == 0) {
1103 if(ferror(infile)) {
1104 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
1105 return EncoderSession_finish_error(&encoder_session);
1107 else if(feof(infile)) {
1108 fprintf(stderr, "%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);
1109 total_input_bytes_read = max_input_bytes;
1113 if(bytes_read % bytes_per_wide_sample != 0) {
1114 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
1115 return EncoderSession_finish_error(&encoder_session);
1118 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1119 format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
1121 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1122 print_error_with_state(&encoder_session, "ERROR during encoding");
1123 return EncoderSession_finish_error(&encoder_session);
1125 total_input_bytes_read += bytes_read;
1132 * now read unaligned samples into reservoir or pad with zeroes if necessary
1134 if(options.common.sector_align) {
1135 if(options.common.is_last_file) {
1136 unsigned wide_samples = 588 - align_remainder;
1137 if(wide_samples < 588) {
1138 unsigned channel, data_bytes;
1140 info_align_zero = wide_samples;
1141 data_bytes = wide_samples * (options.bps >> 3);
1142 for(channel = 0; channel < options.channels; channel++)
1143 memset(input_[channel], 0, data_bytes);
1145 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1146 print_error_with_state(&encoder_session, "ERROR during encoding");
1147 return EncoderSession_finish_error(&encoder_session);
1152 if(*options.common.align_reservoir_samples > 0) {
1153 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1154 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
1155 if(bytes_read == 0 && ferror(infile)) {
1156 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
1157 return EncoderSession_finish_error(&encoder_session);
1159 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
1160 fprintf(stderr, "%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);
1163 info_align_carry = *options.common.align_reservoir_samples;
1164 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, options.is_unsigned_samples, options.channels, options.bps);
1170 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
1173 FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FLAC__bool verbose, FILE *infile, const char *infilename, const char *outfilename)
1176 FLAC__uint32 test = 1;
1179 * initialize globals
1182 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
1184 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1185 input_[i] = &(in_[i][0]);
1189 * initialize instance
1192 #ifdef FLAC__HAS_OGG
1193 e->use_ogg = use_ogg;
1198 e->verbose = verbose;
1200 e->is_stdout = (0 == strcmp(outfilename, "-"));
1202 e->inbasefilename = grabbag__file_get_basename(infilename);
1203 e->outfilename = outfilename;
1205 e->skip = 0; /* filled in later after the sample_rate is known */
1206 e->unencoded_size = 0;
1207 e->total_samples_to_encode = 0;
1208 e->bytes_written = 0;
1209 e->samples_written = 0;
1213 e->encoder.flac.stream = 0;
1214 e->encoder.flac.file = 0;
1215 #ifdef FLAC__HAS_OGG
1216 e->encoder.ogg.stream = 0;
1217 e->encoder.ogg.file = 0;
1222 e->seek_table_template = 0;
1225 e->fout = grabbag__file_get_binary_stdout();
1228 if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1229 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1233 #ifdef FLAC__HAS_OGG
1236 e->encoder.ogg.stream = OggFLAC__stream_encoder_new();
1237 if(0 == e->encoder.ogg.stream) {
1238 fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1239 EncoderSession_destroy(e);
1244 e->encoder.ogg.file = OggFLAC__file_encoder_new();
1245 if(0 == e->encoder.ogg.file) {
1246 fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1247 EncoderSession_destroy(e);
1255 e->encoder.flac.stream = FLAC__stream_encoder_new();
1256 if(0 == e->encoder.flac.stream) {
1257 fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1258 EncoderSession_destroy(e);
1263 e->encoder.flac.file = FLAC__file_encoder_new();
1264 if(0 == e->encoder.flac.file) {
1265 fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1266 EncoderSession_destroy(e);
1274 void EncoderSession_destroy(EncoderSession *e)
1278 if(0 != e->fout && e->fout != stdout)
1281 #ifdef FLAC__HAS_OGG
1284 if(0 != e->encoder.ogg.stream) {
1285 OggFLAC__stream_encoder_delete(e->encoder.ogg.stream);
1286 e->encoder.ogg.stream = 0;
1290 if(0 != e->encoder.ogg.file) {
1291 OggFLAC__file_encoder_delete(e->encoder.ogg.file);
1292 e->encoder.ogg.file = 0;
1299 if(0 != e->encoder.flac.stream) {
1300 FLAC__stream_encoder_delete(e->encoder.flac.stream);
1301 e->encoder.flac.stream = 0;
1305 if(0 != e->encoder.flac.file) {
1306 FLAC__file_encoder_delete(e->encoder.flac.file);
1307 e->encoder.flac.file = 0;
1311 if(0 != e->seek_table_template) {
1312 FLAC__metadata_object_delete(e->seek_table_template);
1313 e->seek_table_template = 0;
1317 int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero)
1319 FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1322 #ifdef FLAC__HAS_OGG
1325 if(e->encoder.ogg.stream) {
1326 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1327 OggFLAC__stream_encoder_finish(e->encoder.ogg.stream);
1331 if(e->encoder.ogg.file) {
1332 fse_state = OggFLAC__file_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.file);
1333 OggFLAC__file_encoder_finish(e->encoder.ogg.file);
1340 if(e->encoder.flac.stream) {
1341 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1342 FLAC__stream_encoder_finish(e->encoder.flac.stream);
1346 if(e->encoder.flac.file) {
1347 fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1348 FLAC__file_encoder_finish(e->encoder.flac.file);
1352 if(e->verbose && e->total_samples_to_encode > 0) {
1354 fprintf(stderr, "\n");
1357 if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) {
1358 print_verify_error(e);
1362 if(info_align_carry >= 0)
1363 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", e->inbasefilename, info_align_carry);
1364 if(info_align_zero >= 0)
1365 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", e->inbasefilename, info_align_zero);
1368 EncoderSession_destroy(e);
1373 int EncoderSession_finish_error(EncoderSession *e)
1375 FLAC__StreamEncoderState fse_state;
1377 if(e->verbose && e->total_samples_to_encode > 0)
1378 fprintf(stderr, "\n");
1380 #ifdef FLAC__HAS_OGG
1383 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1386 fse_state = OggFLAC__file_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.file);
1392 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1395 fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1398 if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1399 print_verify_error(e);
1401 unlink(e->outfilename);
1403 EncoderSession_destroy(e);
1408 FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate)
1410 unsigned num_metadata;
1411 FLAC__StreamMetadata padding, *cuesheet = 0;
1412 FLAC__StreamMetadata *metadata[4];
1414 e->replay_gain = options.replay_gain;
1415 e->channels = channels;
1416 e->bits_per_sample = bps;
1417 e->sample_rate = sample_rate;
1419 if(e->replay_gain) {
1420 if(channels != 1 && channels != 2) {
1421 fprintf(stderr, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
1424 if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) {
1425 fprintf(stderr, "%s: ERROR, invalid sample rate (%u) for --replay-gain\n", e->inbasefilename, sample_rate);
1428 if(options.is_first_file) {
1429 if(!grabbag__replaygain_init(sample_rate)) {
1430 fprintf(stderr, "%s: ERROR initializing ReplayGain stage\n", e->inbasefilename);
1437 options.do_mid_side = options.loose_mid_side = false;
1439 if(!parse_cuesheet_(&cuesheet, options.cuesheet_filename, e->inbasefilename, e->total_samples_to_encode))
1442 if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? cuesheet : 0, e)) {
1443 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1450 if(e->seek_table_template->data.seek_table.num_points > 0) {
1451 e->seek_table_template->is_last = false; /* the encoder will set this for us */
1452 metadata[num_metadata++] = e->seek_table_template;
1455 metadata[num_metadata++] = cuesheet;
1456 metadata[num_metadata++] = options.vorbis_comment;
1457 if(options.padding > 0) {
1458 padding.is_last = false; /* the encoder will set this for us */
1459 padding.type = FLAC__METADATA_TYPE_PADDING;
1460 padding.length = (unsigned)options.padding;
1461 metadata[num_metadata++] = &padding;
1464 e->blocksize = options.blocksize;
1465 e->stats_mask = (options.do_exhaustive_model_search || options.do_qlp_coeff_prec_search)? 0x0f : 0x3f;
1467 /* set a random serial number if one has not yet been specified */
1468 if(!options.has_serial_number) {
1470 options.serial_number = rand();
1471 options.has_serial_number = true;
1474 #ifdef FLAC__HAS_OGG
1477 if(options.has_serial_number)
1478 OggFLAC__stream_encoder_set_serial_number(e->encoder.ogg.stream, options.serial_number);
1479 OggFLAC__stream_encoder_set_verify(e->encoder.ogg.stream, options.verify);
1480 OggFLAC__stream_encoder_set_streamable_subset(e->encoder.ogg.stream, !options.lax);
1481 OggFLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.ogg.stream, options.do_mid_side);
1482 OggFLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.ogg.stream, options.loose_mid_side);
1483 OggFLAC__stream_encoder_set_channels(e->encoder.ogg.stream, channels);
1484 OggFLAC__stream_encoder_set_bits_per_sample(e->encoder.ogg.stream, bps);
1485 OggFLAC__stream_encoder_set_sample_rate(e->encoder.ogg.stream, sample_rate);
1486 OggFLAC__stream_encoder_set_blocksize(e->encoder.ogg.stream, options.blocksize);
1487 OggFLAC__stream_encoder_set_max_lpc_order(e->encoder.ogg.stream, options.max_lpc_order);
1488 OggFLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.ogg.stream, options.qlp_coeff_precision);
1489 OggFLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg.stream, options.do_qlp_coeff_prec_search);
1490 OggFLAC__stream_encoder_set_do_escape_coding(e->encoder.ogg.stream, options.do_escape_coding);
1491 OggFLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.ogg.stream, options.do_exhaustive_model_search);
1492 OggFLAC__stream_encoder_set_min_residual_partition_order(e->encoder.ogg.stream, options.min_residual_partition_order);
1493 OggFLAC__stream_encoder_set_max_residual_partition_order(e->encoder.ogg.stream, options.max_residual_partition_order);
1494 OggFLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.ogg.stream, options.rice_parameter_search_dist);
1495 OggFLAC__stream_encoder_set_total_samples_estimate(e->encoder.ogg.stream, e->total_samples_to_encode);
1496 OggFLAC__stream_encoder_set_metadata(e->encoder.ogg.stream, (num_metadata > 0)? metadata : 0, num_metadata);
1497 OggFLAC__stream_encoder_set_write_callback(e->encoder.ogg.stream, ogg_stream_encoder_write_callback);
1498 OggFLAC__stream_encoder_set_metadata_callback(e->encoder.ogg.stream, ogg_stream_encoder_metadata_callback);
1499 OggFLAC__stream_encoder_set_client_data(e->encoder.ogg.stream, e);
1501 OggFLAC__stream_encoder_disable_constant_subframes(e->encoder.ogg.stream, options.debug.disable_constant_subframes);
1502 OggFLAC__stream_encoder_disable_fixed_subframes(e->encoder.ogg.stream, options.debug.disable_fixed_subframes);
1503 OggFLAC__stream_encoder_disable_verbatim_subframes(e->encoder.ogg.stream, options.debug.disable_verbatim_subframes);
1505 if(OggFLAC__stream_encoder_init(e->encoder.ogg.stream) != FLAC__STREAM_ENCODER_OK) {
1506 print_error_with_state(e, "ERROR initializing encoder");
1513 if(options.has_serial_number)
1514 OggFLAC__file_encoder_set_serial_number(e->encoder.ogg.file, options.serial_number);
1515 OggFLAC__file_encoder_set_filename(e->encoder.ogg.file, e->outfilename);
1516 OggFLAC__file_encoder_set_verify(e->encoder.ogg.file, options.verify);
1517 OggFLAC__file_encoder_set_streamable_subset(e->encoder.ogg.file, !options.lax);
1518 OggFLAC__file_encoder_set_do_mid_side_stereo(e->encoder.ogg.file, options.do_mid_side);
1519 OggFLAC__file_encoder_set_loose_mid_side_stereo(e->encoder.ogg.file, options.loose_mid_side);
1520 OggFLAC__file_encoder_set_channels(e->encoder.ogg.file, channels);
1521 OggFLAC__file_encoder_set_bits_per_sample(e->encoder.ogg.file, bps);
1522 OggFLAC__file_encoder_set_sample_rate(e->encoder.ogg.file, sample_rate);
1523 OggFLAC__file_encoder_set_blocksize(e->encoder.ogg.file, options.blocksize);
1524 OggFLAC__file_encoder_set_max_lpc_order(e->encoder.ogg.file, options.max_lpc_order);
1525 OggFLAC__file_encoder_set_qlp_coeff_precision(e->encoder.ogg.file, options.qlp_coeff_precision);
1526 OggFLAC__file_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg.file, options.do_qlp_coeff_prec_search);
1527 OggFLAC__file_encoder_set_do_escape_coding(e->encoder.ogg.file, options.do_escape_coding);
1528 OggFLAC__file_encoder_set_do_exhaustive_model_search(e->encoder.ogg.file, options.do_exhaustive_model_search);
1529 OggFLAC__file_encoder_set_min_residual_partition_order(e->encoder.ogg.file, options.min_residual_partition_order);
1530 OggFLAC__file_encoder_set_max_residual_partition_order(e->encoder.ogg.file, options.max_residual_partition_order);
1531 OggFLAC__file_encoder_set_rice_parameter_search_dist(e->encoder.ogg.file, options.rice_parameter_search_dist);
1532 OggFLAC__file_encoder_set_total_samples_estimate(e->encoder.ogg.file, e->total_samples_to_encode);
1533 OggFLAC__file_encoder_set_metadata(e->encoder.ogg.file, (num_metadata > 0)? metadata : 0, num_metadata);
1534 OggFLAC__file_encoder_set_progress_callback(e->encoder.ogg.file, ogg_file_encoder_progress_callback);
1535 OggFLAC__file_encoder_set_client_data(e->encoder.ogg.file, e);
1537 OggFLAC__file_encoder_disable_constant_subframes(e->encoder.ogg.file, options.debug.disable_constant_subframes);
1538 OggFLAC__file_encoder_disable_fixed_subframes(e->encoder.ogg.file, options.debug.disable_fixed_subframes);
1539 OggFLAC__file_encoder_disable_verbatim_subframes(e->encoder.ogg.file, options.debug.disable_verbatim_subframes);
1541 if(OggFLAC__file_encoder_init(e->encoder.ogg.file) != OggFLAC__FILE_ENCODER_OK) {
1542 print_error_with_state(e, "ERROR initializing encoder");
1552 FLAC__stream_encoder_set_verify(e->encoder.flac.stream, options.verify);
1553 FLAC__stream_encoder_set_streamable_subset(e->encoder.flac.stream, !options.lax);
1554 FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.flac.stream, options.do_mid_side);
1555 FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.flac.stream, options.loose_mid_side);
1556 FLAC__stream_encoder_set_channels(e->encoder.flac.stream, channels);
1557 FLAC__stream_encoder_set_bits_per_sample(e->encoder.flac.stream, bps);
1558 FLAC__stream_encoder_set_sample_rate(e->encoder.flac.stream, sample_rate);
1559 FLAC__stream_encoder_set_blocksize(e->encoder.flac.stream, options.blocksize);
1560 FLAC__stream_encoder_set_max_lpc_order(e->encoder.flac.stream, options.max_lpc_order);
1561 FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.flac.stream, options.qlp_coeff_precision);
1562 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.stream, options.do_qlp_coeff_prec_search);
1563 FLAC__stream_encoder_set_do_escape_coding(e->encoder.flac.stream, options.do_escape_coding);
1564 FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.flac.stream, options.do_exhaustive_model_search);
1565 FLAC__stream_encoder_set_min_residual_partition_order(e->encoder.flac.stream, options.min_residual_partition_order);
1566 FLAC__stream_encoder_set_max_residual_partition_order(e->encoder.flac.stream, options.max_residual_partition_order);
1567 FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.flac.stream, options.rice_parameter_search_dist);
1568 FLAC__stream_encoder_set_total_samples_estimate(e->encoder.flac.stream, e->total_samples_to_encode);
1569 FLAC__stream_encoder_set_metadata(e->encoder.flac.stream, (num_metadata > 0)? metadata : 0, num_metadata);
1570 FLAC__stream_encoder_set_write_callback(e->encoder.flac.stream, flac_stream_encoder_write_callback);
1571 FLAC__stream_encoder_set_metadata_callback(e->encoder.flac.stream, flac_stream_encoder_metadata_callback);
1572 FLAC__stream_encoder_set_client_data(e->encoder.flac.stream, e);
1574 FLAC__stream_encoder_disable_constant_subframes(e->encoder.flac.stream, options.debug.disable_constant_subframes);
1575 FLAC__stream_encoder_disable_fixed_subframes(e->encoder.flac.stream, options.debug.disable_fixed_subframes);
1576 FLAC__stream_encoder_disable_verbatim_subframes(e->encoder.flac.stream, options.debug.disable_verbatim_subframes);
1578 if(FLAC__stream_encoder_init(e->encoder.flac.stream) != FLAC__STREAM_ENCODER_OK) {
1579 print_error_with_state(e, "ERROR initializing encoder");
1586 FLAC__file_encoder_set_filename(e->encoder.flac.file, e->outfilename);
1587 FLAC__file_encoder_set_verify(e->encoder.flac.file, options.verify);
1588 FLAC__file_encoder_set_streamable_subset(e->encoder.flac.file, !options.lax);
1589 FLAC__file_encoder_set_do_mid_side_stereo(e->encoder.flac.file, options.do_mid_side);
1590 FLAC__file_encoder_set_loose_mid_side_stereo(e->encoder.flac.file, options.loose_mid_side);
1591 FLAC__file_encoder_set_channels(e->encoder.flac.file, channels);
1592 FLAC__file_encoder_set_bits_per_sample(e->encoder.flac.file, bps);
1593 FLAC__file_encoder_set_sample_rate(e->encoder.flac.file, sample_rate);
1594 FLAC__file_encoder_set_blocksize(e->encoder.flac.file, options.blocksize);
1595 FLAC__file_encoder_set_max_lpc_order(e->encoder.flac.file, options.max_lpc_order);
1596 FLAC__file_encoder_set_qlp_coeff_precision(e->encoder.flac.file, options.qlp_coeff_precision);
1597 FLAC__file_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.file, options.do_qlp_coeff_prec_search);
1598 FLAC__file_encoder_set_do_escape_coding(e->encoder.flac.file, options.do_escape_coding);
1599 FLAC__file_encoder_set_do_exhaustive_model_search(e->encoder.flac.file, options.do_exhaustive_model_search);
1600 FLAC__file_encoder_set_min_residual_partition_order(e->encoder.flac.file, options.min_residual_partition_order);
1601 FLAC__file_encoder_set_max_residual_partition_order(e->encoder.flac.file, options.max_residual_partition_order);
1602 FLAC__file_encoder_set_rice_parameter_search_dist(e->encoder.flac.file, options.rice_parameter_search_dist);
1603 FLAC__file_encoder_set_total_samples_estimate(e->encoder.flac.file, e->total_samples_to_encode);
1604 FLAC__file_encoder_set_metadata(e->encoder.flac.file, (num_metadata > 0)? metadata : 0, num_metadata);
1605 FLAC__file_encoder_set_progress_callback(e->encoder.flac.file, flac_file_encoder_progress_callback);
1606 FLAC__file_encoder_set_client_data(e->encoder.flac.file, e);
1608 FLAC__file_encoder_disable_constant_subframes(e->encoder.flac.file, options.debug.disable_constant_subframes);
1609 FLAC__file_encoder_disable_fixed_subframes(e->encoder.flac.file, options.debug.disable_fixed_subframes);
1610 FLAC__file_encoder_disable_verbatim_subframes(e->encoder.flac.file, options.debug.disable_verbatim_subframes);
1612 if(FLAC__file_encoder_init(e->encoder.flac.file) != FLAC__FILE_ENCODER_OK) {
1613 print_error_with_state(e, "ERROR initializing encoder");
1626 FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples)
1628 if(e->replay_gain) {
1629 if(!grabbag__replaygain_analyze(buffer, e->channels==2, e->bits_per_sample, samples))
1630 fprintf(stderr, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename);
1633 #ifdef FLAC__HAS_OGG
1636 return OggFLAC__stream_encoder_process(e->encoder.ogg.stream, buffer, samples);
1639 return OggFLAC__file_encoder_process(e->encoder.ogg.file, buffer, samples);
1645 return FLAC__stream_encoder_process(e->encoder.flac.stream, buffer, samples);
1648 return FLAC__file_encoder_process(e->encoder.flac.file, buffer, samples);
1652 FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e)
1654 const FLAC__bool only_placeholders = e->is_stdout;
1655 FLAC__bool has_real_points;
1657 if(num_requested_seek_points == 0 && 0 == cuesheet)
1660 if(num_requested_seek_points < 0) {
1661 requested_seek_points = "10s;";
1662 num_requested_seek_points = 1;
1665 if(num_requested_seek_points > 0) {
1666 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))
1672 const FLAC__StreamMetadata_CueSheet *cs = &cuesheet->data.cue_sheet;
1673 for(i = 0; i < cs->num_tracks; i++) {
1674 const FLAC__StreamMetadata_CueSheet_Track *tr = cs->tracks+i;
1675 for(j = 0; j < tr->num_indices; j++) {
1676 if(!FLAC__metadata_object_seektable_template_append_point(e->seek_table_template, tr->offset + tr->indices[j].offset))
1678 has_real_points = true;
1682 if(!FLAC__metadata_object_seektable_template_sort(e->seek_table_template, /*compact=*/true))
1686 if(has_real_points) {
1688 fprintf(stderr, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename);
1694 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
1696 /* convert from mm:ss.sss to sample number if necessary */
1697 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
1699 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
1700 if(spec->is_relative && spec->value.samples == 0) {
1701 spec->is_relative = false;
1705 /* in any other case the total samples in the input must be known */
1706 if(total_samples_in_input == 0) {
1707 fprintf(stderr, "%s: ERROR, cannot use --until when input length is unknown\n", inbasefilename);
1711 FLAC__ASSERT(spec->value_is_samples);
1713 /* convert relative specifications to absolute */
1714 if(spec->is_relative) {
1715 if(spec->value.samples <= 0)
1716 spec->value.samples += (FLAC__int64)total_samples_in_input;
1718 spec->value.samples += skip;
1719 spec->is_relative = false;
1723 if(spec->value.samples < 0) {
1724 fprintf(stderr, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
1727 if((FLAC__uint64)spec->value.samples <= skip) {
1728 fprintf(stderr, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
1731 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
1732 fprintf(stderr, "%s: ERROR, --until value is after end of input\n", inbasefilename);
1739 void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps)
1741 unsigned wide_sample, sample, channel, byte;
1744 if(is_unsigned_samples) {
1745 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1746 for(channel = 0; channel < channels; channel++, sample++)
1747 dest[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
1750 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1751 for(channel = 0; channel < channels; channel++, sample++)
1752 dest[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
1755 else if(bps == 16) {
1756 if(is_big_endian != is_big_endian_host_) {
1758 const unsigned bytes = wide_samples * channels * (bps >> 3);
1759 for(byte = 0; byte < bytes; byte += 2) {
1760 tmp = ucbuffer_[byte];
1761 ucbuffer_[byte] = ucbuffer_[byte+1];
1762 ucbuffer_[byte+1] = tmp;
1765 if(is_unsigned_samples) {
1766 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1767 for(channel = 0; channel < channels; channel++, sample++)
1768 dest[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
1771 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1772 for(channel = 0; channel < channels; channel++, sample++)
1773 dest[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
1776 else if(bps == 24) {
1777 if(!is_big_endian) {
1779 const unsigned bytes = wide_samples * channels * (bps >> 3);
1780 for(byte = 0; byte < bytes; byte += 3) {
1781 tmp = ucbuffer_[byte];
1782 ucbuffer_[byte] = ucbuffer_[byte+2];
1783 ucbuffer_[byte+2] = tmp;
1786 if(is_unsigned_samples) {
1787 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1788 for(channel = 0; channel < channels; channel++, sample++) {
1789 dest[channel][wide_sample] = ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1790 dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1791 dest[channel][wide_sample] |= ucbuffer_[byte++];
1792 dest[channel][wide_sample] -= 0x800000;
1796 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1797 for(channel = 0; channel < channels; channel++, sample++) {
1798 dest[channel][wide_sample] = scbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1799 dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1800 dest[channel][wide_sample] |= ucbuffer_[byte++];
1809 #ifdef FLAC__HAS_OGG
1810 FLAC__StreamEncoderWriteStatus ogg_stream_encoder_write_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
1812 EncoderSession *encoder_session = (EncoderSession*)client_data;
1816 encoder_session->bytes_written += bytes;
1818 * With Ogg FLAC we don't get one write callback per frame and
1819 * we don't have a good number for 'samples', so we estimate based
1820 * on the frame number and the knowledge that all blocks (except
1821 * the last) are the same size.
1824 encoder_session->samples_written = (current_frame+1) * encoder_session->blocksize;
1826 if(encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
1827 print_stats(encoder_session);
1829 if(flac__utils_fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
1830 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1832 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1835 void ogg_stream_encoder_metadata_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
1837 // do nothing, for compatibilty. soon we will be using the ogg file encoder anyway.
1838 (void)encoder, (void)metadata, (void)client_data;
1841 void ogg_file_encoder_progress_callback(const OggFLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
1843 EncoderSession *encoder_session = (EncoderSession*)client_data;
1848 * With Ogg FLAC we don't get a value for 'samples_written', so we
1849 * estimate based on the frames written and the knowledge that all
1850 * blocks (except the last) are the same size.
1852 samples_written = frames_written * encoder_session->blocksize;
1853 flac_file_encoder_progress_callback(0, bytes_written, samples_written, frames_written, total_frames_estimate, client_data);
1858 FLAC__StreamEncoderWriteStatus flac_stream_encoder_write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
1860 EncoderSession *encoder_session = (EncoderSession*)client_data;
1864 encoder_session->bytes_written += bytes;
1865 encoder_session->samples_written += samples;
1867 if(samples && encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
1868 print_stats(encoder_session);
1870 if(flac__utils_fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
1871 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1873 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1876 void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
1879 * Nothing to do; if we get here, we're decoding to stdout, in
1880 * which case we can't seek backwards to write new metadata.
1882 (void)encoder, (void)metadata, (void)client_data;
1885 void flac_file_encoder_progress_callback(const FLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
1887 EncoderSession *encoder_session = (EncoderSession*)client_data;
1889 (void)encoder, (void)total_frames_estimate;
1891 encoder_session->bytes_written = bytes_written;
1892 encoder_session->samples_written = samples_written;
1894 if(encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !((frames_written-1) & encoder_session->stats_mask))
1895 print_stats(encoder_session);
1898 FLAC__bool parse_cuesheet_(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__uint64 lead_out_offset)
1901 unsigned last_line_read;
1902 const char *error_message;
1904 if(0 == cuesheet_filename)
1907 if(lead_out_offset == 0) {
1908 fprintf(stderr, "%s: ERROR cannot import cuesheet when the number of input samples to encode is unknown\n", inbasefilename);
1912 if(0 == (f = fopen(cuesheet_filename, "r"))) {
1913 fprintf(stderr, "%s: ERROR opening cuesheet \"%s\" for reading\n", inbasefilename, cuesheet_filename);
1917 *cuesheet = grabbag__cuesheet_parse(f, &error_message, &last_line_read, /*@@@is_cdda=*/true, lead_out_offset);
1921 if(0 == *cuesheet) {
1922 fprintf(stderr, "%s: ERROR parsing cuesheet \"%s\" on line %u: %s\n", inbasefilename, cuesheet_filename, last_line_read, error_message);
1929 void print_stats(const EncoderSession *encoder_session)
1931 const FLAC__uint64 samples_written = min(encoder_session->total_samples_to_encode, encoder_session->samples_written);
1932 #if defined _MSC_VER || defined __MINGW32__
1933 /* with VC++ you have to spoon feed it the casting */
1934 const double progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)encoder_session->total_samples_to_encode;
1935 const double ratio = (double)(FLAC__int64)encoder_session->bytes_written / ((double)(FLAC__int64)encoder_session->unencoded_size * progress);
1937 const double progress = (double)samples_written / (double)encoder_session->total_samples_to_encode;
1938 const double ratio = (double)encoder_session->bytes_written / ((double)encoder_session->unencoded_size * max(1.0, progress));
1941 if(samples_written == encoder_session->total_samples_to_encode) {
1942 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1943 encoder_session->inbasefilename,
1944 encoder_session->verify? " Verify OK," : "",
1945 (unsigned)encoder_session->bytes_written,
1950 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_session->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1954 void print_error_with_state(const EncoderSession *e, const char *message)
1956 const int ilen = strlen(e->inbasefilename) + 1;
1957 const char *state_string;
1959 fprintf(stderr, "\n%s: %s\n", e->inbasefilename, message);
1961 #ifdef FLAC__HAS_OGG
1964 state_string = OggFLAC__stream_encoder_get_resolved_state_string(e->encoder.ogg.stream);
1967 state_string = OggFLAC__file_encoder_get_resolved_state_string(e->encoder.ogg.file);
1973 state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder.flac.stream);
1976 state_string = FLAC__file_encoder_get_resolved_state_string(e->encoder.flac.file);
1979 fprintf(stderr, "%*s state = %s\n", ilen, "", state_string);
1982 void print_verify_error(EncoderSession *e)
1984 FLAC__uint64 absolute_sample;
1985 unsigned frame_number;
1988 FLAC__int32 expected;
1991 #ifdef FLAC__HAS_OGG
1994 OggFLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.ogg.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1997 OggFLAC__file_encoder_get_verify_decoder_error_stats(e->encoder.ogg.file, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2003 FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.flac.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2006 FLAC__file_encoder_get_verify_decoder_error_stats(e->encoder.flac.file, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
2009 fprintf(stderr, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
2010 fprintf(stderr, " Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)absolute_sample, frame_number, channel, sample, expected, got);
2011 fprintf(stderr, " Please submit a bug report to\n");
2012 fprintf(stderr, " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
2013 fprintf(stderr, " Make sure to include an email contact in the comment and/or use the\n");
2014 fprintf(stderr, " \"Monitor\" feature to monitor the bug status.\n");
2015 fprintf(stderr, "Verify FAILED! Do not trust %s\n", e->outfilename);
2018 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
2020 size_t bytes_read = fread(val, 1, 2, f);
2022 if(bytes_read == 0) {
2024 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
2030 else if(bytes_read < 2) {
2031 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
2035 if(is_big_endian_host_) {
2036 FLAC__byte tmp, *b = (FLAC__byte*)val;
2037 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
2043 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2045 size_t bytes_read = fread(val, 1, 4, f);
2047 if(bytes_read == 0) {
2049 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
2055 else if(bytes_read < 4) {
2056 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
2060 if(is_big_endian_host_) {
2061 FLAC__byte tmp, *b = (FLAC__byte*)val;
2062 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
2063 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
2070 read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
2072 unsigned char buf[4];
2073 size_t bytes_read= fread(buf, 1, 2, f);
2075 if(bytes_read==0U && eof_ok)
2077 else if(bytes_read<2U) {
2078 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
2082 /* this is independent of host endianness */
2083 *val= (FLAC__uint16)(buf[0])<<8 | buf[1];
2089 read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2091 unsigned char buf[4];
2092 size_t bytes_read= fread(buf, 1, 4, f);
2094 if(bytes_read==0U && eof_ok)
2096 else if(bytes_read<4U) {
2097 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
2101 /* this is independent of host endianness */
2102 *val= (FLAC__uint32)(buf[0])<<24 | (FLAC__uint32)(buf[1])<<16 |
2103 (FLAC__uint32)(buf[2])<<8 | buf[3];
2109 read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
2110 /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
2111 * convert it into an integral value and store in 'val'. Return false if only
2112 * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f' and 'eof_ok' is
2113 * false, or if the value is negative, between zero and one, or too large to be
2114 * represented by 'val'; return true otherwise.
2118 unsigned char buf[10];
2119 size_t bytes_read= fread(buf, 1U, 10U, f);
2120 FLAC__int16 e= ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
2121 FLAC__int16 shift= 63-e;
2124 if(bytes_read==0U && eof_ok)
2126 else if(bytes_read<10U) {
2127 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
2130 else if((buf[0]>>7)==1U || e<0 || e>63) {
2131 fprintf(stderr, "%s: ERROR: invalid floating-point value\n", fn);
2135 for(i= 0U; i<8U; ++i)
2136 p|= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
2137 *val= (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1));