1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002 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() */
35 #include "OggFLAC/stream_encoder.h"
41 #define min(x,y) ((x)<(y)?(x):(y))
43 /* this MUST be >= 588 so that sector aligning can take place with one read */
44 #define CHUNK_OF_SAMPLES 2048
53 const char *inbasefilename;
54 const char *outfilename;
56 FLAC__uint64 unencoded_size;
57 FLAC__uint64 total_samples_to_encode;
58 FLAC__uint64 bytes_written;
59 FLAC__uint64 samples_written;
64 * We use flac.stream for encoding native FLAC to stdout
65 * We use flac.file for encoding native FLAC to a regular file
66 * We use ogg.stream for encoding Ogg FLAC to either stdout or a regular file
70 FLAC__StreamEncoder *stream;
71 FLAC__FileEncoder *file;
75 OggFLAC__StreamEncoder *stream;
82 FLAC__StreamMetadata *seek_table_template;
86 static FLAC__bool is_big_endian_host_;
88 static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
89 static signed char *scbuffer_ = (signed char *)ucbuffer_;
90 static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_;
91 static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_;
93 static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
94 static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
100 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);
101 static void EncoderSession_destroy(EncoderSession *e);
102 static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero);
103 static int EncoderSession_finish_error(EncoderSession *e);
104 static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate);
105 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
106 static FLAC__bool convert_to_seek_table_template(char *requested_seek_points, int num_requested_seek_points, EncoderSession *e);
107 static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps);
109 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);
111 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);
112 static void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
113 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);
114 static void print_stats(const EncoderSession *encoder_session);
115 static void print_error_with_state(const EncoderSession *e, const char *message);
116 static void print_verify_error(EncoderSession *e);
117 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
118 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
119 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
120 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
121 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
127 flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const char *outfilename,
128 const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
130 EncoderSession encoder_session;
133 unsigned int channels= 0U, bps= 0U, sample_rate= 0U, sample_frames= 0U;
134 FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
135 int info_align_carry= -1, info_align_zero= -1;
137 FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
139 (void)infilesize; /* silence compiler warning about unused parameter */
140 (void)lookahead; /* silence compiler warning about unused parameter */
141 (void)lookahead_length; /* silence compiler warning about unused parameter */
144 EncoderSession_construct(
147 options.common.use_ogg,
151 options.common.verify,
152 options.common.verbose,
160 /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
166 /* chunk identifier; really conservative about behavior of fread() and feof() */
167 if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
169 else if(c<4U || feof(infile)) {
170 fprintf(stderr, "%s: ERROR: incomplete chunk identifier\n", encoder_session.inbasefilename);
171 return EncoderSession_finish_error(&encoder_session);
174 if(got_comm_chunk==false && !strncmp(chunk_id, "COMM", 4)) { /* common chunk */
177 /* COMM chunk size */
178 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
179 return EncoderSession_finish_error(&encoder_session);
181 fprintf(stderr, "%s: ERROR: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
182 return EncoderSession_finish_error(&encoder_session);
185 fprintf(stderr, "%s: WARNING: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
186 skip= (xx-18U)+(xx & 1U);
188 /* number of channels */
189 if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
190 return EncoderSession_finish_error(&encoder_session);
191 else if(x==0U || x>FLAC__MAX_CHANNELS) {
192 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned int)x);
193 return EncoderSession_finish_error(&encoder_session);
195 else if(options.common.sector_align && x!=2U) {
196 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
197 return EncoderSession_finish_error(&encoder_session);
201 /* number of sample frames */
202 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
203 return EncoderSession_finish_error(&encoder_session);
206 /* bits per sample */
207 if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
208 return EncoderSession_finish_error(&encoder_session);
209 else if(x!=8U && x!=16U && x!=24U) {
210 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_session.inbasefilename, (unsigned int)x);
211 return EncoderSession_finish_error(&encoder_session);
213 else if(options.common.sector_align && x!=16U) {
214 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
215 return EncoderSession_finish_error(&encoder_session);
220 if(!read_sane_extended(infile, &xx, false, encoder_session.inbasefilename))
221 return EncoderSession_finish_error(&encoder_session);
222 else if(!FLAC__format_sample_rate_is_valid(xx)) {
223 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned int)xx);
224 return EncoderSession_finish_error(&encoder_session);
226 else if(options.common.sector_align && xx!=44100U) {
227 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)xx);
228 return EncoderSession_finish_error(&encoder_session);
232 /* skip any extra data in the COMM chunk */
233 FLAC__ASSERT(skip<=LONG_MAX);
234 while(skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
235 unsigned int need= min(skip, sizeof ucbuffer_);
236 if(fread(ucbuffer_, 1U, need, infile)<need) {
237 fprintf(stderr, "%s: ERROR during read while skipping extra COMM data\n", encoder_session.inbasefilename);
238 return EncoderSession_finish_error(&encoder_session);
243 got_comm_chunk= true;
245 else if(got_ssnd_chunk==false && !strncmp(chunk_id, "SSND", 4)) { /* sound data chunk */
246 unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
247 size_t bytes_per_frame= channels*(bps>>3);
248 FLAC__bool pad= false;
250 if(got_comm_chunk==false) {
251 fprintf(stderr, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", encoder_session.inbasefilename);
252 return EncoderSession_finish_error(&encoder_session);
255 /* SSND chunk size */
256 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
257 return EncoderSession_finish_error(&encoder_session);
258 else if(xx!=(sample_frames*bytes_per_frame + 8U)) {
259 fprintf(stderr, "%s: ERROR: SSND chunk size inconsistent with sample frame count\n", encoder_session.inbasefilename);
260 return EncoderSession_finish_error(&encoder_session);
263 pad= (data_bytes & 1U) ? true : false;
266 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
267 return EncoderSession_finish_error(&encoder_session);
269 fprintf(stderr, "%s: ERROR: offset is %u; must be 0\n", encoder_session.inbasefilename, (unsigned int)xx);
270 return EncoderSession_finish_error(&encoder_session);
275 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
276 return EncoderSession_finish_error(&encoder_session);
278 fprintf(stderr, "%s: ERROR: block size is %u; must be 0\n", encoder_session.inbasefilename, (unsigned int)xx);
279 return EncoderSession_finish_error(&encoder_session);
283 if(options.common.skip>0U) {
284 FLAC__uint64 remaining= options.common.skip*bytes_per_frame;
286 /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
287 /* is guaranteed to be less than LONG_MAX */
288 for(; remaining>0U; remaining-= remaining>(1U<<30) ? remaining : (1U<<30))
290 unsigned long skip= (unsigned long)(remaining % (1U<<30));
292 FLAC__ASSERT(skip<=LONG_MAX);
293 while(skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
294 unsigned int need= min(skip, sizeof ucbuffer_);
295 if(fread(ucbuffer_, 1U, need, infile)<need) {
296 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
297 return EncoderSession_finish_error(&encoder_session);
304 data_bytes-= (8U + (unsigned int)options.common.skip*bytes_per_frame); /*@@@ WATCHOUT: 4GB limit */
305 encoder_session.total_samples_to_encode= data_bytes/bytes_per_frame + *options.common.align_reservoir_samples;
306 if(options.common.sector_align) {
307 align_remainder= (unsigned int)(encoder_session.total_samples_to_encode % 588U);
308 if(options.common.is_last_file)
309 encoder_session.total_samples_to_encode+= (588U-align_remainder); /* will pad with zeroes */
311 encoder_session.total_samples_to_encode-= align_remainder; /* will stop short and carry over to next file */
314 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
315 encoder_session.unencoded_size= encoder_session.total_samples_to_encode*bytes_per_frame+54;
317 if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
318 return EncoderSession_finish_error(&encoder_session);
320 /* first do any samples in the reservoir */
321 if(options.common.sector_align && *options.common.align_reservoir_samples>0U) {
323 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
324 print_error_with_state(&encoder_session, "ERROR during encoding");
325 return EncoderSession_finish_error(&encoder_session);
329 /* decrement the data_bytes counter if we need to align the file */
330 if(options.common.sector_align) {
331 if(options.common.is_last_file)
332 *options.common.align_reservoir_samples= 0U;
334 *options.common.align_reservoir_samples= align_remainder;
335 data_bytes-= (*options.common.align_reservoir_samples)*bytes_per_frame;
339 /* now do from the file */
340 while(data_bytes>0) {
341 size_t bytes_read= fread(ucbuffer_, 1U, min(data_bytes, CHUNK_OF_SAMPLES*bytes_per_frame), infile);
345 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
346 return EncoderSession_finish_error(&encoder_session);
348 else if(feof(infile)) {
349 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);
354 if(bytes_read % bytes_per_frame != 0U) {
355 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
356 return EncoderSession_finish_error(&encoder_session);
359 unsigned int frames= bytes_read/bytes_per_frame;
360 format_input(input_, frames, true, false, channels, bps);
362 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, frames)) {
363 print_error_with_state(&encoder_session, "ERROR during encoding");
364 return EncoderSession_finish_error(&encoder_session);
367 data_bytes-= bytes_read;
372 /* now read unaligned samples into reservoir or pad with zeroes if necessary */
373 if(options.common.sector_align) {
374 if(options.common.is_last_file) {
375 unsigned int pad_frames= 588U-align_remainder;
377 if(pad_frames<588U) {
380 info_align_zero= pad_frames;
381 for(i= 0U; i<channels; ++i)
382 memset(input_[i], 0, pad_frames*(bps>>3));
384 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, pad_frames)) {
385 print_error_with_state(&encoder_session, "ERROR during encoding");
386 return EncoderSession_finish_error(&encoder_session);
391 if(*options.common.align_reservoir_samples > 0) {
392 size_t bytes_read= fread(ucbuffer_, 1U, (*options.common.align_reservoir_samples)*bytes_per_frame, infile);
394 FLAC__ASSERT(CHUNK_OF_SAMPLES>=588U);
395 if(bytes_read==0U && ferror(infile)) {
396 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
397 return EncoderSession_finish_error(&encoder_session);
399 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame)
400 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);
402 info_align_carry= *options.common.align_reservoir_samples;
403 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, true, false, channels, bps);
412 if(fread(&tmp, 1U, 1U, infile)<1U) {
413 fprintf(stderr, "%s: ERROR during read of SSND pad byte\n", encoder_session.inbasefilename);
414 return EncoderSession_finish_error(&encoder_session);
418 got_ssnd_chunk= true;
420 else { /* other chunk */
421 if(!strncmp(chunk_id, "COMM", 4))
422 fprintf(stderr, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_session.inbasefilename);
423 else if(!strncmp(chunk_id, "SSND", 4))
424 fprintf(stderr, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_session.inbasefilename);
426 fprintf(stderr, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_session.inbasefilename, chunk_id);
429 if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
430 return EncoderSession_finish_error(&encoder_session);
432 unsigned long skip= xx+(xx & 1U);
434 FLAC__ASSERT(skip<=LONG_MAX);
435 while(skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
436 unsigned int need= min(skip, sizeof ucbuffer_);
437 if(fread(ucbuffer_, 1U, need, infile)<need) {
438 fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_session.inbasefilename);
439 return EncoderSession_finish_error(&encoder_session);
447 if(got_ssnd_chunk==false && sample_frames!=0U) {
448 fprintf(stderr, "%s: ERROR: missing SSND chunk\n", encoder_session.inbasefilename);
449 return EncoderSession_finish_error(&encoder_session);
452 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
455 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)
457 EncoderSession encoder_session;
458 FLAC__bool is_unsigned_samples = false;
459 unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
460 size_t bytes_per_wide_sample, bytes_read;
463 FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
464 unsigned align_remainder = 0;
465 int info_align_carry = -1, info_align_zero = -1;
467 FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
471 (void)lookahead_length;
474 EncoderSession_construct(
477 options.common.use_ogg,
481 options.common.verify,
482 options.common.verbose,
491 * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
493 while(!feof(infile)) {
494 if(!read_little_endian_uint32(infile, &xx, true, encoder_session.inbasefilename))
495 return EncoderSession_finish_error(&encoder_session);
498 if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
499 /* fmt sub-chunk size */
500 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
501 return EncoderSession_finish_error(&encoder_session);
503 fprintf(stderr, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
504 return EncoderSession_finish_error(&encoder_session);
506 else if(xx != 16 && xx != 18) {
507 fprintf(stderr, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
510 /* compression code */
511 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
512 return EncoderSession_finish_error(&encoder_session);
514 fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_session.inbasefilename, (unsigned)x);
515 return EncoderSession_finish_error(&encoder_session);
517 /* number of channels */
518 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
519 return EncoderSession_finish_error(&encoder_session);
520 if(x == 0 || x > FLAC__MAX_CHANNELS) {
521 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned)x);
522 return EncoderSession_finish_error(&encoder_session);
524 else if(options.common.sector_align && x != 2) {
525 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
526 return EncoderSession_finish_error(&encoder_session);
530 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
531 return EncoderSession_finish_error(&encoder_session);
532 if(!FLAC__format_sample_rate_is_valid(xx)) {
533 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned)xx);
534 return EncoderSession_finish_error(&encoder_session);
536 else if(options.common.sector_align && xx != 44100) {
537 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned)xx);
538 return EncoderSession_finish_error(&encoder_session);
541 /* avg bytes per second (ignored) */
542 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
543 return EncoderSession_finish_error(&encoder_session);
544 /* block align (ignored) */
545 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
546 return EncoderSession_finish_error(&encoder_session);
547 /* bits per sample */
548 if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
549 return EncoderSession_finish_error(&encoder_session);
550 if(x != 8 && x != 16 && x != 24) {
551 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_session.inbasefilename, (unsigned)x);
552 return EncoderSession_finish_error(&encoder_session);
554 else if(options.common.sector_align && x != 16) {
555 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
556 return EncoderSession_finish_error(&encoder_session);
559 is_unsigned_samples = (x == 8);
561 /* skip any extra data in the fmt sub-chunk */
565 for(left = data_bytes; left > 0; ) {
566 need = min(left, CHUNK_OF_SAMPLES);
567 if(fread(ucbuffer_, 1U, need, infile) < need) {
568 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
569 return EncoderSession_finish_error(&encoder_session);
575 got_fmt_chunk = true;
577 else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
579 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
580 return EncoderSession_finish_error(&encoder_session);
583 bytes_per_wide_sample = channels * (bps >> 3);
585 if(options.common.skip > 0) {
586 if(fseek(infile, bytes_per_wide_sample * (unsigned)options.common.skip, SEEK_CUR) < 0) {
587 /* can't seek input, read ahead manually... */
589 for(left = (unsigned)options.common.skip; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
590 need = min(left, CHUNK_OF_SAMPLES);
591 if(fread(ucbuffer_, bytes_per_wide_sample, need, infile) < need) {
592 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
593 return EncoderSession_finish_error(&encoder_session);
600 data_bytes -= (unsigned)options.common.skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
601 encoder_session.total_samples_to_encode = data_bytes / bytes_per_wide_sample + *options.common.align_reservoir_samples;
602 if(options.common.sector_align) {
603 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
604 if(options.common.is_last_file)
605 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
607 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
610 /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
611 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample + 44;
613 if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
614 return EncoderSession_finish_error(&encoder_session);
617 * first do any samples in the reservoir
619 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
620 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
621 print_error_with_state(&encoder_session, "ERROR during encoding");
622 return EncoderSession_finish_error(&encoder_session);
627 * decrement the data_bytes counter if we need to align the file
629 if(options.common.sector_align) {
630 if(options.common.is_last_file) {
631 *options.common.align_reservoir_samples = 0;
634 *options.common.align_reservoir_samples = align_remainder;
635 data_bytes -= (*options.common.align_reservoir_samples) * bytes_per_wide_sample;
640 * now do from the file
642 while(data_bytes > 0) {
643 bytes_read = fread(ucbuffer_, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
644 if(bytes_read == 0) {
646 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
647 return EncoderSession_finish_error(&encoder_session);
649 else if(feof(infile)) {
650 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);
655 if(bytes_read % bytes_per_wide_sample != 0) {
656 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
657 return EncoderSession_finish_error(&encoder_session);
660 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
661 format_input(input_, wide_samples, false, is_unsigned_samples, channels, bps);
663 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
664 print_error_with_state(&encoder_session, "ERROR during encoding");
665 return EncoderSession_finish_error(&encoder_session);
667 data_bytes -= bytes_read;
673 * now read unaligned samples into reservoir or pad with zeroes if necessary
675 if(options.common.sector_align) {
676 if(options.common.is_last_file) {
677 unsigned wide_samples = 588 - align_remainder;
678 if(wide_samples < 588) {
681 info_align_zero = wide_samples;
682 data_bytes = wide_samples * (bps >> 3);
683 for(channel = 0; channel < channels; channel++)
684 memset(input_[channel], 0, data_bytes);
686 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
687 print_error_with_state(&encoder_session, "ERROR during encoding");
688 return EncoderSession_finish_error(&encoder_session);
693 if(*options.common.align_reservoir_samples > 0) {
694 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
695 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
696 if(bytes_read == 0 && ferror(infile)) {
697 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
698 return EncoderSession_finish_error(&encoder_session);
700 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
701 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);
705 info_align_carry = *options.common.align_reservoir_samples;
706 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, is_unsigned_samples, channels, bps);
712 got_data_chunk = true;
715 if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
716 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_session.inbasefilename);
718 else if(xx == 0x61746164) { /* "data" */
720 fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_session.inbasefilename);
722 else if(!got_fmt_chunk) {
723 fprintf(stderr, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_session.inbasefilename);
724 return EncoderSession_finish_error(&encoder_session);
731 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));
734 if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
735 return EncoderSession_finish_error(&encoder_session);
736 if(fseek(infile, xx, SEEK_CUR) < 0) {
737 /* can't seek input, read ahead manually... */
739 const unsigned chunk = sizeof(ucbuffer_);
740 for(left = xx; left > 0; ) {
741 need = min(left, chunk);
742 if(fread(ucbuffer_, 1, need, infile) < need) {
743 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_session.inbasefilename);
744 return EncoderSession_finish_error(&encoder_session);
752 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
755 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)
757 EncoderSession encoder_session;
759 const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
760 unsigned align_remainder = 0;
761 int info_align_carry = -1, info_align_zero = -1;
763 FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
764 FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
765 FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
766 FLAC__ASSERT(!options.common.sector_align || options.sample_rate == 44100);
767 FLAC__ASSERT(!options.common.sector_align || infilesize >= 0);
770 EncoderSession_construct(
773 options.common.use_ogg,
777 options.common.verify,
778 options.common.verbose,
786 /* get the file length */
788 encoder_session.total_samples_to_encode = encoder_session.unencoded_size = 0;
791 if(options.common.sector_align) {
792 FLAC__ASSERT(options.common.skip == 0);
793 encoder_session.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
794 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
795 if(options.common.is_last_file)
796 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
798 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
801 encoder_session.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - options.common.skip;
804 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample;
807 if(encoder_session.verbose && encoder_session.total_samples_to_encode <= 0)
808 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
810 if(options.common.skip > 0) {
811 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)options.common.skip;
812 if(skip_bytes > lookahead_length) {
813 skip_bytes -= lookahead_length;
814 lookahead_length = 0;
815 if(fseek(infile, (long)skip_bytes, SEEK_CUR) < 0) {
816 /* can't seek input, read ahead manually... */
818 const unsigned chunk = sizeof(ucbuffer_);
819 for(left = skip_bytes; left > 0; ) {
820 need = min(left, chunk);
821 if(fread(ucbuffer_, 1, need, infile) < need) {
822 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
823 return EncoderSession_finish_error(&encoder_session);
830 lookahead += skip_bytes;
831 lookahead_length -= skip_bytes;
835 if(!EncoderSession_init_encoder(&encoder_session, options.common, options.channels, options.bps, options.sample_rate))
836 return EncoderSession_finish_error(&encoder_session);
839 * first do any samples in the reservoir
841 if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
842 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
843 print_error_with_state(&encoder_session, "ERROR during encoding");
844 return EncoderSession_finish_error(&encoder_session);
849 * decrement infilesize if we need to align the file
851 if(options.common.sector_align) {
852 FLAC__ASSERT(infilesize >= 0);
853 if(options.common.is_last_file) {
854 *options.common.align_reservoir_samples = 0;
857 *options.common.align_reservoir_samples = align_remainder;
858 infilesize -= (long)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
863 * now do from the file
865 while(!feof(infile)) {
866 if(lookahead_length > 0) {
867 FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
868 memcpy(ucbuffer_, lookahead, lookahead_length);
869 bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
871 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
872 return EncoderSession_finish_error(&encoder_session);
874 lookahead_length = 0;
877 bytes_read = fread(ucbuffer_, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
879 if(bytes_read == 0) {
881 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
882 return EncoderSession_finish_error(&encoder_session);
885 else if(bytes_read % bytes_per_wide_sample != 0) {
886 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
887 return EncoderSession_finish_error(&encoder_session);
890 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
891 format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
893 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
894 print_error_with_state(&encoder_session, "ERROR during encoding");
895 return EncoderSession_finish_error(&encoder_session);
901 * now read unaligned samples into reservoir or pad with zeroes if necessary
903 if(options.common.sector_align) {
904 if(options.common.is_last_file) {
905 unsigned wide_samples = 588 - align_remainder;
906 if(wide_samples < 588) {
907 unsigned channel, data_bytes;
909 info_align_zero = wide_samples;
910 data_bytes = wide_samples * (options.bps >> 3);
911 for(channel = 0; channel < options.channels; channel++)
912 memset(input_[channel], 0, data_bytes);
914 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
915 print_error_with_state(&encoder_session, "ERROR during encoding");
916 return EncoderSession_finish_error(&encoder_session);
921 if(*options.common.align_reservoir_samples > 0) {
922 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
923 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
924 if(bytes_read == 0 && ferror(infile)) {
925 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
926 return EncoderSession_finish_error(&encoder_session);
928 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
929 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);
932 info_align_carry = *options.common.align_reservoir_samples;
933 format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, options.is_unsigned_samples, options.channels, options.bps);
939 return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
942 FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FLAC__bool verbose, FILE *infile, const char *infilename, const char *outfilename)
945 FLAC__uint32 test = 1;
951 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
953 for(i = 0; i < FLAC__MAX_CHANNELS; i++)
954 input_[i] = &(in_[i][0]);
958 * initialize instance
962 e->use_ogg = use_ogg;
967 e->verbose = verbose;
969 e->is_stdout = (0 == strcmp(outfilename, "-"));
971 e->inbasefilename = flac__file_get_basename(infilename);
972 e->outfilename = outfilename;
974 e->unencoded_size = 0;
975 e->total_samples_to_encode = 0;
976 e->bytes_written = 0;
977 e->samples_written = 0;
981 e->encoder.flac.stream = 0;
982 e->encoder.flac.file = 0;
984 e->encoder.ogg.stream = 0;
989 e->seek_table_template = 0;
992 e->fout = file__get_binary_stdout();
997 if(0 == (e->fout = fopen(outfilename, "wb"))) {
998 fprintf(stderr, "%s: ERROR: can't open output file %s\n", e->inbasefilename, outfilename);
999 EncoderSession_destroy(e);
1006 if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1007 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1011 #ifdef FLAC__HAS_OGG
1013 e->encoder.ogg.stream = OggFLAC__stream_encoder_new();
1014 if(0 == e->encoder.ogg.stream) {
1015 fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1016 EncoderSession_destroy(e);
1023 e->encoder.flac.stream = FLAC__stream_encoder_new();
1024 if(0 == e->encoder.flac.stream) {
1025 fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1026 EncoderSession_destroy(e);
1031 e->encoder.flac.file = FLAC__file_encoder_new();
1032 if(0 == e->encoder.flac.file) {
1033 fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1034 EncoderSession_destroy(e);
1042 void EncoderSession_destroy(EncoderSession *e)
1047 #ifdef FLAC__HAS_OGG
1049 if(0 != e->encoder.ogg.stream) {
1050 OggFLAC__stream_encoder_delete(e->encoder.ogg.stream);
1051 e->encoder.ogg.stream = 0;
1057 if(0 != e->encoder.flac.stream) {
1058 FLAC__stream_encoder_delete(e->encoder.flac.stream);
1059 e->encoder.flac.stream = 0;
1063 if(0 != e->encoder.flac.file) {
1064 FLAC__file_encoder_delete(e->encoder.flac.file);
1065 e->encoder.flac.file = 0;
1069 if(0 != e->seek_table_template) {
1070 FLAC__metadata_object_delete(e->seek_table_template);
1071 e->seek_table_template = 0;
1075 int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero)
1077 FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1080 #ifdef FLAC__HAS_OGG
1082 if(e->encoder.ogg.stream) {
1083 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1084 OggFLAC__stream_encoder_finish(e->encoder.ogg.stream);
1090 if(e->encoder.flac.stream) {
1091 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1092 FLAC__stream_encoder_finish(e->encoder.flac.stream);
1096 if(e->encoder.flac.file) {
1097 fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1098 FLAC__file_encoder_finish(e->encoder.flac.file);
1102 if(e->verbose && e->total_samples_to_encode > 0) {
1104 fprintf(stderr, "\n");
1107 if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) {
1108 print_verify_error(e);
1112 if(info_align_carry >= 0)
1113 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", e->inbasefilename, info_align_carry);
1114 if(info_align_zero >= 0)
1115 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", e->inbasefilename, info_align_zero);
1118 EncoderSession_destroy(e);
1123 int EncoderSession_finish_error(EncoderSession *e)
1125 FLAC__StreamEncoderState fse_state;
1127 if(e->verbose && e->total_samples_to_encode > 0)
1128 fprintf(stderr, "\n");
1130 #ifdef FLAC__HAS_OGG
1132 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1137 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1140 fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1143 if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1144 print_verify_error(e);
1146 unlink(e->outfilename);
1148 EncoderSession_destroy(e);
1153 FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate)
1155 unsigned num_metadata;
1156 FLAC__StreamMetadata padding;
1157 FLAC__StreamMetadata *metadata[2];
1160 options.do_mid_side = options.loose_mid_side = false;
1162 if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, e)) {
1163 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1168 if(e->seek_table_template->data.seek_table.num_points > 0) {
1169 e->seek_table_template->is_last = false; /* the encoder will set this for us */
1170 metadata[num_metadata++] = e->seek_table_template;
1172 if(options.padding > 0) {
1173 padding.is_last = false; /* the encoder will set this for us */
1174 padding.type = FLAC__METADATA_TYPE_PADDING;
1175 padding.length = (unsigned)options.padding;
1176 metadata[num_metadata++] = &padding;
1179 e->blocksize = options.blocksize;
1180 e->stats_mask = (options.do_exhaustive_model_search || options.do_qlp_coeff_prec_search)? 0x0f : 0x3f;
1182 #ifdef FLAC__HAS_OGG
1184 OggFLAC__stream_encoder_set_verify(e->encoder.ogg.stream, options.verify);
1185 OggFLAC__stream_encoder_set_streamable_subset(e->encoder.ogg.stream, !options.lax);
1186 OggFLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.ogg.stream, options.do_mid_side);
1187 OggFLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.ogg.stream, options.loose_mid_side);
1188 OggFLAC__stream_encoder_set_channels(e->encoder.ogg.stream, channels);
1189 OggFLAC__stream_encoder_set_bits_per_sample(e->encoder.ogg.stream, bps);
1190 OggFLAC__stream_encoder_set_sample_rate(e->encoder.ogg.stream, sample_rate);
1191 OggFLAC__stream_encoder_set_blocksize(e->encoder.ogg.stream, options.blocksize);
1192 OggFLAC__stream_encoder_set_max_lpc_order(e->encoder.ogg.stream, options.max_lpc_order);
1193 OggFLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.ogg.stream, options.qlp_coeff_precision);
1194 OggFLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg.stream, options.do_qlp_coeff_prec_search);
1195 OggFLAC__stream_encoder_set_do_escape_coding(e->encoder.ogg.stream, options.do_escape_coding);
1196 OggFLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.ogg.stream, options.do_exhaustive_model_search);
1197 OggFLAC__stream_encoder_set_min_residual_partition_order(e->encoder.ogg.stream, options.min_residual_partition_order);
1198 OggFLAC__stream_encoder_set_max_residual_partition_order(e->encoder.ogg.stream, options.max_residual_partition_order);
1199 OggFLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.ogg.stream, options.rice_parameter_search_dist);
1200 OggFLAC__stream_encoder_set_total_samples_estimate(e->encoder.ogg.stream, e->total_samples_to_encode);
1201 OggFLAC__stream_encoder_set_metadata(e->encoder.ogg.stream, (num_metadata > 0)? metadata : 0, num_metadata);
1202 OggFLAC__stream_encoder_set_write_callback(e->encoder.ogg.stream, ogg_stream_encoder_write_callback);
1203 OggFLAC__stream_encoder_set_client_data(e->encoder.ogg.stream, e);
1205 if(OggFLAC__stream_encoder_init(e->encoder.ogg.stream) != FLAC__STREAM_ENCODER_OK) {
1206 print_error_with_state(e, "ERROR initializing encoder");
1213 FLAC__stream_encoder_set_verify(e->encoder.flac.stream, options.verify);
1214 FLAC__stream_encoder_set_streamable_subset(e->encoder.flac.stream, !options.lax);
1215 FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.flac.stream, options.do_mid_side);
1216 FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.flac.stream, options.loose_mid_side);
1217 FLAC__stream_encoder_set_channels(e->encoder.flac.stream, channels);
1218 FLAC__stream_encoder_set_bits_per_sample(e->encoder.flac.stream, bps);
1219 FLAC__stream_encoder_set_sample_rate(e->encoder.flac.stream, sample_rate);
1220 FLAC__stream_encoder_set_blocksize(e->encoder.flac.stream, options.blocksize);
1221 FLAC__stream_encoder_set_max_lpc_order(e->encoder.flac.stream, options.max_lpc_order);
1222 FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.flac.stream, options.qlp_coeff_precision);
1223 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.stream, options.do_qlp_coeff_prec_search);
1224 FLAC__stream_encoder_set_do_escape_coding(e->encoder.flac.stream, options.do_escape_coding);
1225 FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.flac.stream, options.do_exhaustive_model_search);
1226 FLAC__stream_encoder_set_min_residual_partition_order(e->encoder.flac.stream, options.min_residual_partition_order);
1227 FLAC__stream_encoder_set_max_residual_partition_order(e->encoder.flac.stream, options.max_residual_partition_order);
1228 FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.flac.stream, options.rice_parameter_search_dist);
1229 FLAC__stream_encoder_set_total_samples_estimate(e->encoder.flac.stream, e->total_samples_to_encode);
1230 FLAC__stream_encoder_set_metadata(e->encoder.flac.stream, (num_metadata > 0)? metadata : 0, num_metadata);
1231 FLAC__stream_encoder_set_write_callback(e->encoder.flac.stream, flac_stream_encoder_write_callback);
1232 FLAC__stream_encoder_set_metadata_callback(e->encoder.flac.stream, flac_stream_encoder_metadata_callback);
1233 FLAC__stream_encoder_set_client_data(e->encoder.flac.stream, e);
1235 if(FLAC__stream_encoder_init(e->encoder.flac.stream) != FLAC__STREAM_ENCODER_OK) {
1236 print_error_with_state(e, "ERROR initializing encoder");
1241 FLAC__file_encoder_set_filename(e->encoder.flac.file, e->outfilename);
1242 FLAC__file_encoder_set_verify(e->encoder.flac.file, options.verify);
1243 FLAC__file_encoder_set_streamable_subset(e->encoder.flac.file, !options.lax);
1244 FLAC__file_encoder_set_do_mid_side_stereo(e->encoder.flac.file, options.do_mid_side);
1245 FLAC__file_encoder_set_loose_mid_side_stereo(e->encoder.flac.file, options.loose_mid_side);
1246 FLAC__file_encoder_set_channels(e->encoder.flac.file, channels);
1247 FLAC__file_encoder_set_bits_per_sample(e->encoder.flac.file, bps);
1248 FLAC__file_encoder_set_sample_rate(e->encoder.flac.file, sample_rate);
1249 FLAC__file_encoder_set_blocksize(e->encoder.flac.file, options.blocksize);
1250 FLAC__file_encoder_set_max_lpc_order(e->encoder.flac.file, options.max_lpc_order);
1251 FLAC__file_encoder_set_qlp_coeff_precision(e->encoder.flac.file, options.qlp_coeff_precision);
1252 FLAC__file_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.file, options.do_qlp_coeff_prec_search);
1253 FLAC__file_encoder_set_do_escape_coding(e->encoder.flac.file, options.do_escape_coding);
1254 FLAC__file_encoder_set_do_exhaustive_model_search(e->encoder.flac.file, options.do_exhaustive_model_search);
1255 FLAC__file_encoder_set_min_residual_partition_order(e->encoder.flac.file, options.min_residual_partition_order);
1256 FLAC__file_encoder_set_max_residual_partition_order(e->encoder.flac.file, options.max_residual_partition_order);
1257 FLAC__file_encoder_set_rice_parameter_search_dist(e->encoder.flac.file, options.rice_parameter_search_dist);
1258 FLAC__file_encoder_set_total_samples_estimate(e->encoder.flac.file, e->total_samples_to_encode);
1259 FLAC__file_encoder_set_metadata(e->encoder.flac.file, (num_metadata > 0)? metadata : 0, num_metadata);
1260 FLAC__file_encoder_set_progress_callback(e->encoder.flac.file, flac_file_encoder_progress_callback);
1261 FLAC__file_encoder_set_client_data(e->encoder.flac.file, e);
1263 if(FLAC__file_encoder_init(e->encoder.flac.file) != FLAC__FILE_ENCODER_OK) {
1264 print_error_with_state(e, "ERROR initializing encoder");
1272 FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples)
1274 #ifdef FLAC__HAS_OGG
1276 return OggFLAC__stream_encoder_process(e->encoder.ogg.stream, buffer, samples);
1281 return FLAC__stream_encoder_process(e->encoder.flac.stream, buffer, samples);
1284 return FLAC__file_encoder_process(e->encoder.flac.file, buffer, samples);
1288 FLAC__bool convert_to_seek_table_template(char *requested_seek_points, int num_requested_seek_points, EncoderSession *e)
1291 char *pt = requested_seek_points, *q;
1292 FLAC__bool only_placeholders = false;
1293 FLAC__bool needs_warning = false;
1295 if(num_requested_seek_points == 0)
1298 if(num_requested_seek_points < 0) {
1299 strcpy(requested_seek_points, "100x<");
1300 num_requested_seek_points = 1;
1304 only_placeholders = true;
1307 else if(e->is_ogg) {
1308 only_placeholders = true;
1312 for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
1313 q = strchr(pt, '<');
1314 FLAC__ASSERT(0 != q);
1317 if(0 == strcmp(pt, "X")) { /* -S X */
1318 if(!FLAC__metadata_object_seektable_template_append_placeholders(e->seek_table_template, 1))
1321 else if(!only_placeholders) {
1322 if(pt[strlen(pt)-1] == 'x') { /* -S #x */
1323 if(e->total_samples_to_encode > 0) { /* we can only do these if we know the number of samples to encode up front */
1324 if(!FLAC__metadata_object_seektable_template_append_spaced_points(e->seek_table_template, atoi(pt), e->total_samples_to_encode))
1329 FLAC__uint64 n = (unsigned)atoi(pt);
1330 if(!FLAC__metadata_object_seektable_template_append_point(e->seek_table_template, n))
1335 needs_warning = true;
1340 if(!FLAC__metadata_object_seektable_template_sort(e->seek_table_template, /*compact=*/true))
1345 fprintf(stderr, "%s: WARNING, cannot write back seektable when encoding to stdout\n", e->inbasefilename);
1348 else if(e->is_ogg) {
1349 fprintf(stderr, "%s: WARNING, cannot write back seektable when encoding to Ogg\n", e->inbasefilename);
1359 void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps)
1361 unsigned wide_sample, sample, channel, byte;
1364 if(is_unsigned_samples) {
1365 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1366 for(channel = 0; channel < channels; channel++, sample++)
1367 dest[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
1370 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1371 for(channel = 0; channel < channels; channel++, sample++)
1372 dest[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
1375 else if(bps == 16) {
1376 if(is_big_endian != is_big_endian_host_) {
1378 const unsigned bytes = wide_samples * channels * (bps >> 3);
1379 for(byte = 0; byte < bytes; byte += 2) {
1380 tmp = ucbuffer_[byte];
1381 ucbuffer_[byte] = ucbuffer_[byte+1];
1382 ucbuffer_[byte+1] = tmp;
1385 if(is_unsigned_samples) {
1386 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1387 for(channel = 0; channel < channels; channel++, sample++)
1388 dest[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
1391 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1392 for(channel = 0; channel < channels; channel++, sample++)
1393 dest[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
1396 else if(bps == 24) {
1397 if(!is_big_endian) {
1399 const unsigned bytes = wide_samples * channels * (bps >> 3);
1400 for(byte = 0; byte < bytes; byte += 3) {
1401 tmp = ucbuffer_[byte];
1402 ucbuffer_[byte] = ucbuffer_[byte+2];
1403 ucbuffer_[byte+2] = tmp;
1406 if(is_unsigned_samples) {
1407 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1408 for(channel = 0; channel < channels; channel++, sample++) {
1409 dest[channel][wide_sample] = ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1410 dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1411 dest[channel][wide_sample] |= ucbuffer_[byte++];
1412 dest[channel][wide_sample] -= 0x800000;
1416 for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1417 for(channel = 0; channel < channels; channel++, sample++) {
1418 dest[channel][wide_sample] = scbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1419 dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1420 dest[channel][wide_sample] |= ucbuffer_[byte++];
1429 #ifdef FLAC__HAS_OGG
1430 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)
1432 EncoderSession *encoder_session = (EncoderSession*)client_data;
1436 encoder_session->bytes_written += bytes;
1438 * With Ogg FLAC we don't get one write callback per frame and
1439 * we don't have good number for 'samples', so we estimate based
1440 * on the frame number and the knowledge that all blocks (except
1441 * the last) are the same size.
1444 encoder_session->samples_written = (current_frame+1) * encoder_session->blocksize;
1446 if(encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
1447 print_stats(encoder_session);
1449 if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
1450 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1452 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1456 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)
1458 EncoderSession *encoder_session = (EncoderSession*)client_data;
1462 encoder_session->bytes_written += bytes;
1463 encoder_session->samples_written += samples;
1465 if(samples && encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
1466 print_stats(encoder_session);
1468 if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
1469 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1471 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1474 void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
1477 * Nothing to do; if we get here, we're decoding to stdout, in
1478 * which case we can't seek backwards to write new metadata.
1480 (void)encoder, (void)metadata, (void)client_data;
1483 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)
1485 EncoderSession *encoder_session = (EncoderSession*)client_data;
1487 (void)encoder, (void)total_frames_estimate;
1489 encoder_session->bytes_written = bytes_written;
1490 encoder_session->samples_written = samples_written;
1492 if(encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !((frames_written-1) & encoder_session->stats_mask))
1493 print_stats(encoder_session);
1496 void print_stats(const EncoderSession *encoder_session)
1498 const FLAC__uint64 samples_written = min(encoder_session->total_samples_to_encode, encoder_session->samples_written);
1499 #if defined _MSC_VER || defined __MINGW32__
1500 /* with VC++ you have to spoon feed it the casting */
1501 const double progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)encoder_session->total_samples_to_encode;
1502 const double ratio = (double)(FLAC__int64)encoder_session->bytes_written / ((double)(FLAC__int64)encoder_session->unencoded_size * progress);
1504 const double progress = (double)samples_written / (double)encoder_session->total_samples_to_encode;
1505 const double ratio = (double)encoder_session->bytes_written / ((double)encoder_session->unencoded_size * progress);
1508 if(samples_written == encoder_session->total_samples_to_encode) {
1509 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1510 encoder_session->inbasefilename,
1511 encoder_session->verify? " Verify OK," : "",
1512 (unsigned)encoder_session->bytes_written,
1517 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_session->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1521 void print_error_with_state(const EncoderSession *e, const char *message)
1523 const int ilen = strlen(e->inbasefilename) + 1;
1525 fprintf(stderr, "\n%s: %s\n", e->inbasefilename, message);
1527 #ifdef FLAC__HAS_OGG
1529 const OggFLAC__StreamEncoderState ose_state = OggFLAC__stream_encoder_get_state(e->encoder.ogg.stream);
1530 if(ose_state != OggFLAC__STREAM_ENCODER_FLAC_STREAM_ENCODER_ERROR) {
1531 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ose_state, OggFLAC__StreamEncoderStateString[ose_state]);
1534 const FLAC__StreamEncoderState fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1535 if(fse_state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) {
1536 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fse_state, FLAC__StreamEncoderStateString[fse_state]);
1539 const FLAC__StreamDecoderState fsd_state = OggFLAC__stream_encoder_get_verify_decoder_state(e->encoder.ogg.stream);
1540 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1547 const FLAC__StreamEncoderState fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1548 if(fse_state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) {
1549 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fse_state, FLAC__StreamEncoderStateString[fse_state]);
1552 const FLAC__StreamDecoderState fsd_state = FLAC__stream_encoder_get_verify_decoder_state(e->encoder.flac.stream);
1553 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1557 const FLAC__FileEncoderState ffe_state = FLAC__file_encoder_get_state(e->encoder.flac.file);
1558 if(ffe_state != FLAC__FILE_ENCODER_SEEKABLE_STREAM_ENCODER_ERROR) {
1559 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ffe_state, FLAC__FileEncoderStateString[ffe_state]);
1562 const FLAC__SeekableStreamEncoderState fsse_state = FLAC__file_encoder_get_seekable_stream_encoder_state(e->encoder.flac.file);
1563 if(fsse_state != FLAC__SEEKABLE_STREAM_ENCODER_STREAM_ENCODER_ERROR) {
1564 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsse_state, FLAC__SeekableStreamEncoderStateString[fsse_state]);
1567 const FLAC__StreamEncoderState fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1568 if(fse_state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) {
1569 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fse_state, FLAC__StreamEncoderStateString[fse_state]);
1572 const FLAC__StreamDecoderState fsd_state = FLAC__file_encoder_get_verify_decoder_state(e->encoder.flac.file);
1573 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1580 void print_verify_error(EncoderSession *e)
1582 FLAC__uint64 absolute_sample;
1583 unsigned frame_number;
1586 FLAC__int32 expected;
1589 #ifdef FLAC__HAS_OGG
1591 OggFLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.ogg.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1596 FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.flac.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1599 FLAC__file_encoder_get_verify_decoder_error_stats(e->encoder.flac.file, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1602 fprintf(stderr, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
1603 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);
1604 fprintf(stderr, " Please submit a bug report to\n");
1605 fprintf(stderr, " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1606 fprintf(stderr, " Make sure to include an email contact in the comment and/or use the\n");
1607 fprintf(stderr, " \"Monitor\" feature to monitor the bug status.\n");
1608 fprintf(stderr, "Verify FAILED! Do not trust %s\n", e->outfilename);
1611 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1613 size_t bytes_read = fread(val, 1, 2, f);
1615 if(bytes_read == 0) {
1617 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1623 else if(bytes_read < 2) {
1624 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1628 if(is_big_endian_host_) {
1629 FLAC__byte tmp, *b = (FLAC__byte*)val;
1630 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1636 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1638 size_t bytes_read = fread(val, 1, 4, f);
1640 if(bytes_read == 0) {
1642 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1648 else if(bytes_read < 4) {
1649 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1653 if(is_big_endian_host_) {
1654 FLAC__byte tmp, *b = (FLAC__byte*)val;
1655 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1656 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1663 read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1665 unsigned char buf[4];
1666 size_t bytes_read= fread(buf, 1, 2, f);
1668 if(bytes_read==0U && eof_ok)
1670 else if(bytes_read<2U) {
1671 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1675 /* this is independent of host endianness */
1676 *val= (FLAC__uint16)(buf[0])<<8 | buf[1];
1682 read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1684 unsigned char buf[4];
1685 size_t bytes_read= fread(buf, 1, 4, f);
1687 if(bytes_read==0U && eof_ok)
1689 else if(bytes_read<4U) {
1690 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1694 /* this is independent of host endianness */
1695 *val= (FLAC__uint32)(buf[0])<<24 | (FLAC__uint32)(buf[1])<<16 |
1696 (FLAC__uint32)(buf[2])<<8 | buf[3];
1702 read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1703 /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
1704 * convert it into an integral value and store in 'val'. Return false if only
1705 * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f' and 'eof_ok' is
1706 * false, or if the value is negative, between zero and one, or too large to be
1707 * represented by 'val'; return true otherwise.
1711 unsigned char buf[10];
1712 size_t bytes_read= fread(buf, 1U, 10U, f);
1713 FLAC__int16 e= ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
1714 FLAC__int16 shift= 63-e;
1717 if(bytes_read==0U && eof_ok)
1719 else if(bytes_read<10U) {
1720 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1723 else if((buf[0]>>7)==1U || e<0 || e>63) {
1724 fprintf(stderr, "%s: ERROR: invalid floating-point value\n", fn);
1728 for(i= 0U; i<8U; ++i)
1729 p|= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
1730 *val= (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1));