1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002,2003 Josh Coalson
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 #if defined _WIN32 && !defined __CYGWIN__
24 /* where MSVC puts unlink() */
29 #include <math.h> /* for floor() */
30 #include <stdio.h> /* for FILE et al. */
31 #include <string.h> /* for strcmp() */
33 #include "share/grabbag.h"
34 #include "share/replaygain_synthesis.h"
38 #include "OggFLAC/stream_decoder.h"
47 FLAC__bool is_aiff_out;
48 FLAC__bool is_wave_out;
49 FLAC__bool continue_through_decode_errors;
52 replaygain_synthesis_spec_t spec;
54 DitherContext dither_context;
58 FLAC__bool analysis_mode;
59 analysis_options aopts;
60 utils__SkipUntilSpecification *skip_specification;
61 utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
63 const char *inbasefilename;
64 const char *outfilename;
66 FLAC__uint64 samples_processed;
67 unsigned frame_counter;
68 FLAC__bool abort_flag;
71 FLAC__bool needs_fixup;
72 unsigned riff_offset; /* or FORM offset for AIFF */
73 unsigned data_offset; /* or SSND offset for AIFF */
74 unsigned frames_offset; /* AIFF only */
75 } wave_chunk_size_fixup;
77 FLAC__bool is_big_endian;
78 FLAC__bool is_unsigned_samples;
79 FLAC__uint64 total_samples;
86 FLAC__FileDecoder *file;
90 OggFLAC__StreamDecoder *stream;
102 static FLAC__bool is_big_endian_host_;
108 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool verbose, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, const char *infilename, const char *outfilename);
109 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
110 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, decode_options_t decode_options, const char *infilename);
111 static FLAC__bool DecoderSession_process(DecoderSession *d);
112 static int DecoderSession_finish_ok(DecoderSession *d);
113 static int DecoderSession_finish_error(DecoderSession *d);
114 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
115 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
116 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
117 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
118 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
119 static FLAC__bool write_sane_extended(FILE *f, unsigned val);
120 static FLAC__bool fixup_wave_chunk_size(const char *outfilename, FLAC__bool is_wave_out, unsigned riff_offset, unsigned data_offset, unsigned frames_offset, FLAC__uint32 total_samples, unsigned channels, unsigned bps);
122 static FLAC__StreamDecoderReadStatus read_callback(const OggFLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
125 * We use 'void *' so that we can use the same callbacks for the
126 * FLAC__StreamDecoder and FLAC__FileDecoder. The 'decoder' argument is
127 * actually never used in the callbacks.
129 static FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
130 static void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
131 static void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
132 static void print_error_with_state(const DecoderSession *d, const char *message);
133 static void print_stats(const DecoderSession *decoder_session);
139 int flac__decode_aiff(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
141 DecoderSession decoder_session;
144 DecoderSession_construct(
147 options.common.is_ogg,
151 options.common.verbose,
152 /*is_aiff_out=*/true,
153 /*is_wave_out=*/false,
154 options.common.continue_through_decode_errors,
155 options.common.replaygain_synthesis_spec,
158 &options.common.skip_specification,
159 &options.common.until_specification,
166 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
167 return DecoderSession_finish_error(&decoder_session);
169 if(!DecoderSession_process(&decoder_session))
170 return DecoderSession_finish_error(&decoder_session);
172 return DecoderSession_finish_ok(&decoder_session);
175 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
177 DecoderSession decoder_session;
180 DecoderSession_construct(
183 options.common.is_ogg,
187 options.common.verbose,
188 /*is_aiff_out=*/false,
189 /*is_wave_out=*/true,
190 options.common.continue_through_decode_errors,
191 options.common.replaygain_synthesis_spec,
194 &options.common.skip_specification,
195 &options.common.until_specification,
202 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
203 return DecoderSession_finish_error(&decoder_session);
205 if(!DecoderSession_process(&decoder_session))
206 return DecoderSession_finish_error(&decoder_session);
208 return DecoderSession_finish_ok(&decoder_session);
211 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
213 DecoderSession decoder_session;
215 decoder_session.is_big_endian = options.is_big_endian;
216 decoder_session.is_unsigned_samples = options.is_unsigned_samples;
219 DecoderSession_construct(
222 options.common.is_ogg,
226 options.common.verbose,
227 /*is_aiff_out=*/false,
228 /*is_wave_out=*/false,
229 options.common.continue_through_decode_errors,
230 options.common.replaygain_synthesis_spec,
233 &options.common.skip_specification,
234 &options.common.until_specification,
241 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
242 return DecoderSession_finish_error(&decoder_session);
244 if(!DecoderSession_process(&decoder_session))
245 return DecoderSession_finish_error(&decoder_session);
247 return DecoderSession_finish_ok(&decoder_session);
250 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool verbose, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, const char *infilename, const char *outfilename)
258 d->verbose = verbose;
259 d->is_aiff_out = is_aiff_out;
260 d->is_wave_out = is_wave_out;
261 d->continue_through_decode_errors = continue_through_decode_errors;
262 d->replaygain.spec = replaygain_synthesis_spec;
263 d->replaygain.scale = 0.0;
264 /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
265 d->test_only = (0 == outfilename);
266 d->analysis_mode = analysis_mode;
268 d->skip_specification = skip_specification;
269 d->until_specification = until_specification;
271 d->inbasefilename = grabbag__file_get_basename(infilename);
272 d->outfilename = outfilename;
274 d->samples_processed = 0;
275 d->frame_counter = 0;
276 d->abort_flag = false;
278 d->wave_chunk_size_fixup.needs_fixup = false;
280 d->decoder.flac.file = 0;
282 d->decoder.ogg.stream = 0;
288 d->fout = 0; /* initialized with an open file later if necessary */
290 FLAC__ASSERT(!(d->test_only && d->analysis_mode));
293 if(0 == strcmp(outfilename, "-")) {
294 d->fout = grabbag__file_get_binary_stdout();
297 if(0 == (d->fout = fopen(outfilename, "wb"))) {
298 fprintf(stderr, "%s: ERROR: can't open output file %s\n", d->inbasefilename, outfilename);
299 DecoderSession_destroy(d, /*error_occurred=*/true);
307 if (0 == strcmp(infilename, "-")) {
308 d->fin = grabbag__file_get_binary_stdin();
310 if (0 == (d->fin = fopen(infilename, "rb"))) {
311 fprintf(stderr, "%s: ERROR: can't open input file %s\n", d->inbasefilename, infilename);
312 DecoderSession_destroy(d, /*error_occurred=*/true);
320 flac__analyze_init(aopts);
325 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
327 if(0 != d->fout && d->fout != stdout) {
330 unlink(d->outfilename);
333 if(0 != d->fin && d->fin != stdin)
338 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, decode_options_t decode_options, const char *infilename)
340 FLAC__uint32 test = 1;
342 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
345 if(decoder_session->is_ogg) {
346 decoder_session->decoder.ogg.stream = OggFLAC__stream_decoder_new();
348 if(0 == decoder_session->decoder.ogg.stream) {
349 fprintf(stderr, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
353 if(!decode_options.use_first_serial_number)
354 OggFLAC__stream_decoder_set_serial_number(decoder_session->decoder.ogg.stream, decode_options.serial_number);
355 if (decoder_session->replaygain.spec.apply)
356 OggFLAC__stream_decoder_set_metadata_respond(decoder_session->decoder.ogg.stream, FLAC__METADATA_TYPE_VORBIS_COMMENT);
358 OggFLAC__stream_decoder_set_read_callback(decoder_session->decoder.ogg.stream, read_callback);
360 * The three ugly casts here are to 'downcast' the 'void *' argument of
361 * the callback down to 'FLAC__StreamDecoder *'. In C++ this would be
362 * unnecessary but here the cast makes the C compiler happy.
364 OggFLAC__stream_decoder_set_write_callback(decoder_session->decoder.ogg.stream, (FLAC__StreamDecoderWriteStatus (*)(const OggFLAC__StreamDecoder *, const FLAC__Frame *, const FLAC__int32 * const [], void *))write_callback);
365 OggFLAC__stream_decoder_set_metadata_callback(decoder_session->decoder.ogg.stream, (void (*)(const OggFLAC__StreamDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
366 OggFLAC__stream_decoder_set_error_callback(decoder_session->decoder.ogg.stream, (void (*)(const OggFLAC__StreamDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
367 OggFLAC__stream_decoder_set_client_data(decoder_session->decoder.ogg.stream, decoder_session);
369 if(OggFLAC__stream_decoder_init(decoder_session->decoder.ogg.stream) != OggFLAC__STREAM_DECODER_OK) {
370 print_error_with_state(decoder_session, "ERROR initializing decoder");
376 (void)decode_options;
379 decoder_session->decoder.flac.file = FLAC__file_decoder_new();
381 if(0 == decoder_session->decoder.flac.file) {
382 fprintf(stderr, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
386 FLAC__file_decoder_set_md5_checking(decoder_session->decoder.flac.file, true);
387 FLAC__file_decoder_set_filename(decoder_session->decoder.flac.file, infilename);
388 if (decoder_session->replaygain.spec.apply)
389 FLAC__file_decoder_set_metadata_respond(decoder_session->decoder.flac.file, FLAC__METADATA_TYPE_VORBIS_COMMENT);
391 * The three ugly casts here are to 'downcast' the 'void *' argument of
392 * the callback down to 'FLAC__FileDecoder *'.
394 FLAC__file_decoder_set_write_callback(decoder_session->decoder.flac.file, (FLAC__StreamDecoderWriteStatus (*)(const FLAC__FileDecoder *, const FLAC__Frame *, const FLAC__int32 * const [], void *))write_callback);
395 FLAC__file_decoder_set_metadata_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
396 FLAC__file_decoder_set_error_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
397 FLAC__file_decoder_set_client_data(decoder_session->decoder.flac.file, decoder_session);
399 if(FLAC__file_decoder_init(decoder_session->decoder.flac.file) != FLAC__FILE_DECODER_OK) {
400 print_error_with_state(decoder_session, "ERROR initializing decoder");
408 FLAC__bool DecoderSession_process(DecoderSession *d)
412 if(!OggFLAC__stream_decoder_process_until_end_of_metadata(d->decoder.ogg.stream)) {
413 if(d->verbose) fprintf(stderr, "\n");
414 print_error_with_state(d, "ERROR while decoding metadata");
417 if(OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream) != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC && OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream) != FLAC__STREAM_DECODER_END_OF_STREAM) {
418 if(d->verbose) fprintf(stderr, "\n");
419 print_error_with_state(d, "ERROR during metadata decoding");
426 if(!FLAC__file_decoder_process_until_end_of_metadata(d->decoder.flac.file)) {
427 if(d->verbose) fprintf(stderr, "\n");
428 print_error_with_state(d, "ERROR while decoding metadata");
431 if(FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_END_OF_FILE) {
432 if(d->verbose) fprintf(stderr, "\n");
433 print_error_with_state(d, "ERROR during metadata decoding");
440 if(d->skip_specification->value.samples > 0) {
441 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
444 if(d->is_ogg) { /*@@@ (move this check into main.c) */
445 fprintf(stderr, "%s: ERROR, can't skip when decoding Ogg-FLAC yet; convert to native-FLAC first\n", d->inbasefilename);
449 if(!FLAC__file_decoder_seek_absolute(d->decoder.flac.file, skip)) {
450 print_error_with_state(d, "ERROR seeking while skipping bytes");
453 if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file)) {
454 if(d->verbose) fprintf(stderr, "\n");
455 print_error_with_state(d, "ERROR while decoding frames");
458 if(FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_END_OF_FILE) {
459 if(d->verbose) fprintf(stderr, "\n");
460 print_error_with_state(d, "ERROR during decoding");
467 if(!OggFLAC__stream_decoder_process_until_end_of_stream(d->decoder.ogg.stream)) {
468 if(d->verbose) fprintf(stderr, "\n");
469 print_error_with_state(d, "ERROR while decoding data");
472 if(OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA && OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream) != FLAC__STREAM_DECODER_END_OF_STREAM) {
473 if(d->verbose) fprintf(stderr, "\n");
474 print_error_with_state(d, "ERROR during decoding");
481 if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file)) {
482 if(d->verbose) fprintf(stderr, "\n");
483 print_error_with_state(d, "ERROR while decoding data");
486 if(FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_END_OF_FILE) {
487 if(d->verbose) fprintf(stderr, "\n");
488 print_error_with_state(d, "ERROR during decoding");
494 if(d->is_aiff_out && ((d->total_samples * d->channels * ((d->bps+7)/8)) & 1)) {
495 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
496 print_error_with_state(d, "ERROR writing pad byte to AIFF SSND chunk");
504 int DecoderSession_finish_ok(DecoderSession *d)
506 FLAC__bool md5_failure = false;
510 if(d->decoder.ogg.stream) {
511 OggFLAC__stream_decoder_finish(d->decoder.ogg.stream);
514 OggFLAC__stream_decoder_delete(d->decoder.ogg.stream);
520 if(d->decoder.flac.file) {
521 md5_failure = !FLAC__file_decoder_finish(d->decoder.flac.file);
523 FLAC__file_decoder_delete(d->decoder.flac.file);
527 flac__analyze_finish(d->aopts);
529 fprintf(stderr, "\r%s: WARNING, MD5 signature mismatch\n", d->inbasefilename);
533 fprintf(stderr, "\r%s: %s \n", d->inbasefilename, d->test_only? "ok ":d->analysis_mode?"done ":"done");
535 DecoderSession_destroy(d, /*error_occurred=*/false);
536 if((d->is_wave_out || d->is_aiff_out) && d->wave_chunk_size_fixup.needs_fixup)
537 if(!fixup_wave_chunk_size(d->outfilename, d->is_wave_out, d->wave_chunk_size_fixup.riff_offset, d->wave_chunk_size_fixup.data_offset, d->wave_chunk_size_fixup.frames_offset, (FLAC__uint32)d->samples_processed, d->channels, d->bps))
542 int DecoderSession_finish_error(DecoderSession *d)
546 if(d->decoder.ogg.stream) {
547 OggFLAC__stream_decoder_finish(d->decoder.ogg.stream);
548 OggFLAC__stream_decoder_delete(d->decoder.ogg.stream);
554 if(d->decoder.flac.file) {
555 FLAC__file_decoder_finish(d->decoder.flac.file);
556 FLAC__file_decoder_delete(d->decoder.flac.file);
560 flac__analyze_finish(d->aopts);
561 DecoderSession_destroy(d, /*error_occurred=*/true);
565 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
567 /* convert from mm:ss.sss to sample number if necessary */
568 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
570 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
571 if(spec->is_relative && spec->value.samples == 0) {
572 spec->is_relative = false;
576 /* in any other case the total samples in the input must be known */
577 if(total_samples_in_input == 0) {
578 fprintf(stderr, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
582 FLAC__ASSERT(spec->value_is_samples);
584 /* convert relative specifications to absolute */
585 if(spec->is_relative) {
586 if(spec->value.samples <= 0)
587 spec->value.samples += (FLAC__int64)total_samples_in_input;
589 spec->value.samples += skip;
590 spec->is_relative = false;
594 if(spec->value.samples < 0) {
595 fprintf(stderr, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
598 if((FLAC__uint64)spec->value.samples <= skip) {
599 fprintf(stderr, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
602 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
603 fprintf(stderr, "%s: ERROR, --until value is after end of input\n", inbasefilename);
610 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
612 FLAC__byte *b = (FLAC__byte*)(&val);
613 if(is_big_endian_host_) {
615 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
617 return flac__utils_fwrite(b, 1, 2, f) == 2;
620 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
622 FLAC__byte *b = (FLAC__byte*)(&val);
623 if(is_big_endian_host_) {
625 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
626 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
628 return flac__utils_fwrite(b, 1, 4, f) == 4;
631 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
633 FLAC__byte *b = (FLAC__byte*)(&val);
634 if(!is_big_endian_host_) {
636 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
638 return flac__utils_fwrite(b, 1, 2, f) == 2;
641 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
643 FLAC__byte *b = (FLAC__byte*)(&val);
644 if(!is_big_endian_host_) {
646 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
647 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
649 return flac__utils_fwrite(b, 1, 4, f) == 4;
652 FLAC__bool write_sane_extended(FILE *f, unsigned val)
653 /* Write to 'f' a SANE extended representation of 'val'. Return false if
654 * the write succeeds; return true otherwise.
656 * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
657 * of exponent, and 64 bits of significand (mantissa). Unlike most IEEE-754
658 * representations, it does not imply a 1 above the MSB of the significand.
664 unsigned int shift, exponent;
666 FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
668 for(shift= 0U; (val>>(31-shift))==0U; ++shift)
671 exponent= 63U-(shift+32U); /* add 32 for unused second word */
673 if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
675 if(!write_big_endian_uint32(f, val))
677 if(!write_big_endian_uint32(f, 0)) /* unused second word */
683 FLAC__bool fixup_wave_chunk_size(const char *outfilename, FLAC__bool is_wave_out, unsigned riff_offset, unsigned data_offset, unsigned frames_offset, FLAC__uint32 total_samples, unsigned channels, unsigned bps)
685 const char *fmt_desc = (is_wave_out? "WAVE" : "AIFF");
686 FLAC__bool (*write_it)(FILE *, FLAC__uint32) = (is_wave_out? write_little_endian_uint32 : write_big_endian_uint32);
687 FILE *f = fopen(outfilename, "r+b");
688 FLAC__uint32 data_size, aligned_data_size;
691 fprintf(stderr, "ERROR, couldn't open file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
695 data_size = aligned_data_size = total_samples * channels * ((bps+7)/8);
696 if(!is_wave_out && (aligned_data_size & 1))
699 if(fseek(f, riff_offset, SEEK_SET) < 0) {
700 fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
704 if(!write_it(f, aligned_data_size + (is_wave_out? 36 : 46))) {
705 fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
710 if(fseek(f, frames_offset, SEEK_SET) < 0) {
711 fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
715 if(!write_it(f, total_samples)) {
716 fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
721 if(fseek(f, data_offset, SEEK_SET) < 0) {
722 fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
726 if(!write_it(f, data_size + (is_wave_out? 0 : 8))) {
727 fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
736 FLAC__StreamDecoderReadStatus read_callback(const OggFLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
738 DecoderSession *decoder_session = (DecoderSession*)client_data;
739 FILE *fin = decoder_session->fin;
742 (void)decoder; /* avoid compiler warning */
744 if (decoder_session->abort_flag)
745 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
748 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
750 bytes_read = fread(buffer, 1, *bytes, fin);
753 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
755 *bytes = (unsigned)bytes_read;
757 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
761 FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
763 DecoderSession *decoder_session = (DecoderSession*)client_data;
764 FILE *fout = decoder_session->fout;
765 const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
766 FLAC__bool is_big_endian = (decoder_session->is_aiff_out? true : (decoder_session->is_wave_out? false : decoder_session->is_big_endian));
767 FLAC__bool is_unsigned_samples = (decoder_session->is_aiff_out? false : (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples));
768 unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
769 static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
770 FLAC__uint8 *u8buffer = (FLAC__uint8 *)s8buffer;
771 FLAC__int16 *s16buffer = (FLAC__int16 *)s8buffer;
772 FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
773 FLAC__int32 *s32buffer = (FLAC__int32 *)s8buffer;
774 FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
778 if(decoder_session->abort_flag)
779 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
781 if(bps != decoder_session->bps) {
782 fprintf(stderr, "%s: ERROR, bits-per-sample is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, bps, decoder_session->bps);
783 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
785 if(channels != decoder_session->channels) {
786 fprintf(stderr, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
787 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
789 if(frame->header.sample_rate != decoder_session->sample_rate) {
790 fprintf(stderr, "%s: ERROR, sample rate is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
791 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
795 * limit the number of samples to accept based on --until
797 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
798 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
799 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
800 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
801 if(decoder_session->until_specification->value.samples > 0) {
802 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
803 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
804 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
805 FLAC__ASSERT(until >= input_samples_passed);
806 if(input_samples_passed + wide_samples > until)
807 wide_samples = (unsigned)(until - input_samples_passed);
810 if(wide_samples > 0) {
811 decoder_session->samples_processed += wide_samples;
812 decoder_session->frame_counter++;
814 if(decoder_session->verbose && !(decoder_session->frame_counter & 0x3f))
815 print_stats(decoder_session);
817 if(decoder_session->analysis_mode) {
818 flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->aopts, fout);
820 else if(!decoder_session->test_only) {
821 if (decoder_session->replaygain.spec.apply) {
822 const size_t n = FLAC__replaygain_synthesis__apply_gain(
829 bps, /* source_bps */
830 bps, /* target_bps */
831 decoder_session->replaygain.scale,
832 decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
833 decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
834 &decoder_session->replaygain.dither_context
836 if(flac__utils_fwrite(u8buffer, 1, n, fout) != n)
837 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
840 if(is_unsigned_samples) {
841 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
842 for(channel = 0; channel < channels; channel++, sample++)
843 u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
846 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
847 for(channel = 0; channel < channels; channel++, sample++)
848 s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
850 if(flac__utils_fwrite(u8buffer, 1, sample, fout) != sample)
851 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
854 if(is_unsigned_samples) {
855 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
856 for(channel = 0; channel < channels; channel++, sample++)
857 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
860 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
861 for(channel = 0; channel < channels; channel++, sample++)
862 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
864 if(is_big_endian != is_big_endian_host_) {
866 const unsigned bytes = sample * 2;
867 for(byte = 0; byte < bytes; byte += 2) {
868 tmp = u8buffer[byte];
869 u8buffer[byte] = u8buffer[byte+1];
870 u8buffer[byte+1] = tmp;
873 if(flac__utils_fwrite(u16buffer, 2, sample, fout) != sample)
874 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
877 if(is_unsigned_samples) {
878 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
879 for(channel = 0; channel < channels; channel++, sample++)
880 u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
883 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
884 for(channel = 0; channel < channels; channel++, sample++)
885 s32buffer[sample] = buffer[channel][wide_sample];
887 if(is_big_endian != is_big_endian_host_) {
889 const unsigned bytes = sample * 4;
890 for(byte = 0; byte < bytes; byte += 4) {
891 tmp = u8buffer[byte];
892 u8buffer[byte] = u8buffer[byte+3];
893 u8buffer[byte+3] = tmp;
894 tmp = u8buffer[byte+1];
895 u8buffer[byte+1] = u8buffer[byte+2];
896 u8buffer[byte+2] = tmp;
901 const unsigned bytes = sample * 4;
902 for(lbyte = byte = 0; byte < bytes; ) {
904 u8buffer[lbyte++] = u8buffer[byte++];
905 u8buffer[lbyte++] = u8buffer[byte++];
906 u8buffer[lbyte++] = u8buffer[byte++];
911 const unsigned bytes = sample * 4;
912 for(lbyte = byte = 0; byte < bytes; ) {
913 u8buffer[lbyte++] = u8buffer[byte++];
914 u8buffer[lbyte++] = u8buffer[byte++];
915 u8buffer[lbyte++] = u8buffer[byte++];
919 if(flac__utils_fwrite(u8buffer, 3, sample, fout) != sample)
920 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
927 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
930 void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
932 DecoderSession *decoder_session = (DecoderSession*)client_data;
934 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
935 FLAC__uint64 skip, until;
936 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
937 decoder_session->channels = metadata->data.stream_info.channels;
938 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
940 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
941 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
942 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
944 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
945 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
946 fprintf(stderr, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
947 decoder_session->abort_flag = true;
950 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
951 fprintf(stderr, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
952 decoder_session->abort_flag = true;
955 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
957 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
958 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
959 decoder_session->abort_flag = true;
962 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
963 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
966 decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
968 if(decoder_session->bps != 8 && decoder_session->bps != 16 && decoder_session->bps != 24) {
969 fprintf(stderr, "%s: ERROR: bits per sample is not 8/16/24\n", decoder_session->inbasefilename);
970 decoder_session->abort_flag = true;
974 /* write the WAVE/AIFF headers if necessary */
975 if(!decoder_session->analysis_mode && !decoder_session->test_only && (decoder_session->is_wave_out || decoder_session->is_aiff_out)) {
976 const char *fmt_desc = decoder_session->is_wave_out? "WAVE" : "AIFF";
977 FLAC__uint64 data_size = decoder_session->total_samples * decoder_session->channels * ((decoder_session->bps+7)/8);
978 if(decoder_session->total_samples == 0) {
979 if(decoder_session->fout == stdout) {
980 fprintf(stderr, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
981 fprintf(stderr, " Generated %s file will have a data chunk size of 0. Try\n", fmt_desc);
982 fprintf(stderr, " decoding directly to a file instead.\n");
985 decoder_session->wave_chunk_size_fixup.needs_fixup = true;
988 if(data_size >= 0xFFFFFFDC) {
989 fprintf(stderr, "%s: ERROR: stream is too big to fit in a single %s file chunk\n", decoder_session->inbasefilename, fmt_desc);
990 decoder_session->abort_flag = true;
993 if(decoder_session->is_wave_out) {
994 if(flac__utils_fwrite("RIFF", 1, 4, decoder_session->fout) != 4)
995 decoder_session->abort_flag = true;
997 if(decoder_session->wave_chunk_size_fixup.needs_fixup)
998 decoder_session->wave_chunk_size_fixup.riff_offset = ftell(decoder_session->fout);
1000 if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)(data_size+36))) /* filesize-8 */
1001 decoder_session->abort_flag = true;
1003 if(flac__utils_fwrite("WAVEfmt ", 1, 8, decoder_session->fout) != 8)
1004 decoder_session->abort_flag = true;
1006 if(flac__utils_fwrite("\020\000\000\000", 1, 4, decoder_session->fout) != 4) /* chunk size = 16 */
1007 decoder_session->abort_flag = true;
1009 if(flac__utils_fwrite("\001\000", 1, 2, decoder_session->fout) != 2) /* compression code == 1 */
1010 decoder_session->abort_flag = true;
1012 if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels)))
1013 decoder_session->abort_flag = true;
1015 if(!write_little_endian_uint32(decoder_session->fout, decoder_session->sample_rate))
1016 decoder_session->abort_flag = true;
1018 if(!write_little_endian_uint32(decoder_session->fout, decoder_session->sample_rate * decoder_session->channels * ((decoder_session->bps+7) / 8))) /* @@@ or is it (sample_rate*channels*bps) / 8 ??? */
1019 decoder_session->abort_flag = true;
1021 if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels * ((decoder_session->bps+7) / 8)))) /* block align */
1022 decoder_session->abort_flag = true;
1024 if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->bps))) /* bits per sample */
1025 decoder_session->abort_flag = true;
1027 if(flac__utils_fwrite("data", 1, 4, decoder_session->fout) != 4)
1028 decoder_session->abort_flag = true;
1030 if(decoder_session->wave_chunk_size_fixup.needs_fixup)
1031 decoder_session->wave_chunk_size_fixup.data_offset = ftell(decoder_session->fout);
1033 if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)data_size)) /* data size */
1034 decoder_session->abort_flag = true;
1037 const FLAC__uint32 aligned_data_size = (FLAC__uint32)((data_size+1) & (~1U));
1039 if(flac__utils_fwrite("FORM", 1, 4, decoder_session->fout) != 4)
1040 decoder_session->abort_flag = true;
1042 if(decoder_session->wave_chunk_size_fixup.needs_fixup)
1043 decoder_session->wave_chunk_size_fixup.riff_offset = ftell(decoder_session->fout);
1045 if(!write_big_endian_uint32(decoder_session->fout, (FLAC__uint32)(aligned_data_size+46))) /* filesize-8 */
1046 decoder_session->abort_flag = true;
1048 if(flac__utils_fwrite("AIFFCOMM", 1, 8, decoder_session->fout) != 8)
1049 decoder_session->abort_flag = true;
1051 if(flac__utils_fwrite("\000\000\000\022", 1, 4, decoder_session->fout) != 4) /* chunk size = 18 */
1052 decoder_session->abort_flag = true;
1054 if(!write_big_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels)))
1055 decoder_session->abort_flag = true;
1057 if(decoder_session->wave_chunk_size_fixup.needs_fixup)
1058 decoder_session->wave_chunk_size_fixup.frames_offset = ftell(decoder_session->fout);
1060 if(!write_big_endian_uint32(decoder_session->fout, (FLAC__uint32)decoder_session->total_samples))
1061 decoder_session->abort_flag = true;
1063 if(!write_big_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->bps)))
1064 decoder_session->abort_flag = true;
1066 if(!write_sane_extended(decoder_session->fout, decoder_session->sample_rate))
1067 decoder_session->abort_flag = true;
1069 if(flac__utils_fwrite("SSND", 1, 4, decoder_session->fout) != 4)
1070 decoder_session->abort_flag = true;
1072 if(decoder_session->wave_chunk_size_fixup.needs_fixup)
1073 decoder_session->wave_chunk_size_fixup.data_offset = ftell(decoder_session->fout);
1075 if(!write_big_endian_uint32(decoder_session->fout, (FLAC__uint32)data_size+8)) /* data size */
1076 decoder_session->abort_flag = true;
1078 if(!write_big_endian_uint32(decoder_session->fout, 0/*offset*/))
1079 decoder_session->abort_flag = true;
1081 if(!write_big_endian_uint32(decoder_session->fout, 0/*block_size*/))
1082 decoder_session->abort_flag = true;
1086 else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1087 if (decoder_session->replaygain.spec.apply) {
1089 if (!(decoder_session->replaygain.spec.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, &gain, &peak))) {
1090 fprintf(stderr, "%s: WARNING: can't get %s ReplayGain tag\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track");
1093 const char *ls[] = { "no", "peak", "hard" };
1094 const char *ns[] = { "no", "low", "medium", "high" };
1095 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1096 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1097 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1098 fprintf(stderr, "%s: INFO: applying %s ReplayGain (gain=%0.2fdB+preamp=%0.1fdB, %s noise shaping, %s limiting) to output\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", gain, decoder_session->replaygain.spec.preamp, ns[decoder_session->replaygain.spec.noise_shaping], ls[decoder_session->replaygain.spec.limiter]);
1099 fprintf(stderr, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1105 void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1107 DecoderSession *decoder_session = (DecoderSession*)client_data;
1109 fprintf(stderr, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1110 if(!decoder_session->continue_through_decode_errors)
1111 decoder_session->abort_flag = true;
1114 void print_error_with_state(const DecoderSession *d, const char *message)
1116 const int ilen = strlen(d->inbasefilename) + 1;
1118 fprintf(stderr, "\n%s: %s\n", d->inbasefilename, message);
1120 #ifdef FLAC__HAS_OGG
1122 const OggFLAC__StreamDecoderState osd_state = OggFLAC__stream_decoder_get_state(d->decoder.ogg.stream);
1123 if(osd_state != OggFLAC__STREAM_DECODER_FLAC_STREAM_DECODER_ERROR) {
1124 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)osd_state, OggFLAC__StreamDecoderStateString[osd_state]);
1127 const FLAC__StreamDecoderState fsd_state = OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream);
1128 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1134 const FLAC__FileDecoderState ffd_state = FLAC__file_decoder_get_state(d->decoder.flac.file);
1135 if(ffd_state != FLAC__FILE_DECODER_SEEKABLE_STREAM_DECODER_ERROR) {
1136 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ffd_state, FLAC__FileDecoderStateString[ffd_state]);
1139 const FLAC__SeekableStreamDecoderState fssd_state = FLAC__file_decoder_get_seekable_stream_decoder_state(d->decoder.flac.file);
1140 if(fssd_state != FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR) {
1141 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fssd_state, FLAC__SeekableStreamDecoderStateString[fssd_state]);
1144 const FLAC__StreamDecoderState fsd_state = FLAC__file_decoder_get_stream_decoder_state(d->decoder.flac.file);
1145 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1151 void print_stats(const DecoderSession *decoder_session)
1153 if(decoder_session->verbose) {
1154 #if defined _MSC_VER || defined __MINGW32__
1155 /* with VC++ you have to spoon feed it the casting */
1156 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1158 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1160 if(decoder_session->total_samples > 0) {
1161 fprintf(stderr, "\r%s: %s%u%% complete",
1162 decoder_session->inbasefilename,
1163 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1164 (unsigned)floor(progress + 0.5)
1168 fprintf(stderr, "\r%s: %s %u samples",
1169 decoder_session->inbasefilename,
1170 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1171 (unsigned)decoder_session->samples_processed