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;
53 FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */
55 DitherContext dither_context;
59 FLAC__bool analysis_mode;
60 analysis_options aopts;
61 utils__SkipUntilSpecification *skip_specification;
62 utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
64 const char *inbasefilename;
65 const char *outfilename;
67 FLAC__uint64 samples_processed;
68 unsigned frame_counter;
69 FLAC__bool abort_flag;
72 FLAC__bool needs_fixup;
73 unsigned riff_offset; /* or FORM offset for AIFF */
74 unsigned data_offset; /* or SSND offset for AIFF */
75 unsigned frames_offset; /* AIFF only */
76 } wave_chunk_size_fixup;
78 FLAC__bool is_big_endian;
79 FLAC__bool is_unsigned_samples;
80 FLAC__uint64 total_samples;
87 FLAC__FileDecoder *file;
91 OggFLAC__StreamDecoder *stream;
103 static FLAC__bool is_big_endian_host_;
109 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);
110 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
111 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, decode_options_t decode_options, const char *infilename);
112 static FLAC__bool DecoderSession_process(DecoderSession *d);
113 static int DecoderSession_finish_ok(DecoderSession *d);
114 static int DecoderSession_finish_error(DecoderSession *d);
115 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
116 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
117 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
118 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
119 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
120 static FLAC__bool write_sane_extended(FILE *f, unsigned val);
121 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);
123 static FLAC__StreamDecoderReadStatus read_callback(const OggFLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
126 * We use 'void *' so that we can use the same callbacks for the
127 * FLAC__StreamDecoder and FLAC__FileDecoder. The 'decoder' argument is
128 * actually never used in the callbacks.
130 static FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
131 static void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
132 static void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
133 static void print_error_with_state(const DecoderSession *d, const char *message);
134 static void print_stats(const DecoderSession *decoder_session);
140 int flac__decode_aiff(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
142 DecoderSession decoder_session;
145 DecoderSession_construct(
148 options.common.is_ogg,
152 options.common.verbose,
153 /*is_aiff_out=*/true,
154 /*is_wave_out=*/false,
155 options.common.continue_through_decode_errors,
156 options.common.replaygain_synthesis_spec,
159 &options.common.skip_specification,
160 &options.common.until_specification,
167 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
168 return DecoderSession_finish_error(&decoder_session);
170 if(!DecoderSession_process(&decoder_session))
171 return DecoderSession_finish_error(&decoder_session);
173 return DecoderSession_finish_ok(&decoder_session);
176 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
178 DecoderSession decoder_session;
181 DecoderSession_construct(
184 options.common.is_ogg,
188 options.common.verbose,
189 /*is_aiff_out=*/false,
190 /*is_wave_out=*/true,
191 options.common.continue_through_decode_errors,
192 options.common.replaygain_synthesis_spec,
195 &options.common.skip_specification,
196 &options.common.until_specification,
203 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
204 return DecoderSession_finish_error(&decoder_session);
206 if(!DecoderSession_process(&decoder_session))
207 return DecoderSession_finish_error(&decoder_session);
209 return DecoderSession_finish_ok(&decoder_session);
212 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
214 DecoderSession decoder_session;
216 decoder_session.is_big_endian = options.is_big_endian;
217 decoder_session.is_unsigned_samples = options.is_unsigned_samples;
220 DecoderSession_construct(
223 options.common.is_ogg,
227 options.common.verbose,
228 /*is_aiff_out=*/false,
229 /*is_wave_out=*/false,
230 options.common.continue_through_decode_errors,
231 options.common.replaygain_synthesis_spec,
234 &options.common.skip_specification,
235 &options.common.until_specification,
242 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
243 return DecoderSession_finish_error(&decoder_session);
245 if(!DecoderSession_process(&decoder_session))
246 return DecoderSession_finish_error(&decoder_session);
248 return DecoderSession_finish_ok(&decoder_session);
251 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)
259 d->verbose = verbose;
260 d->is_aiff_out = is_aiff_out;
261 d->is_wave_out = is_wave_out;
262 d->continue_through_decode_errors = continue_through_decode_errors;
263 d->replaygain.spec = replaygain_synthesis_spec;
264 d->replaygain.apply = false;
265 d->replaygain.scale = 0.0;
266 /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
267 d->test_only = (0 == outfilename);
268 d->analysis_mode = analysis_mode;
270 d->skip_specification = skip_specification;
271 d->until_specification = until_specification;
273 d->inbasefilename = grabbag__file_get_basename(infilename);
274 d->outfilename = outfilename;
276 d->samples_processed = 0;
277 d->frame_counter = 0;
278 d->abort_flag = false;
280 d->wave_chunk_size_fixup.needs_fixup = false;
282 d->decoder.flac.file = 0;
284 d->decoder.ogg.stream = 0;
290 d->fout = 0; /* initialized with an open file later if necessary */
292 FLAC__ASSERT(!(d->test_only && d->analysis_mode));
295 if(0 == strcmp(outfilename, "-")) {
296 d->fout = grabbag__file_get_binary_stdout();
299 if(0 == (d->fout = fopen(outfilename, "wb"))) {
300 fprintf(stderr, "%s: ERROR: can't open output file %s\n", d->inbasefilename, outfilename);
301 DecoderSession_destroy(d, /*error_occurred=*/true);
309 if (0 == strcmp(infilename, "-")) {
310 d->fin = grabbag__file_get_binary_stdin();
312 if (0 == (d->fin = fopen(infilename, "rb"))) {
313 fprintf(stderr, "%s: ERROR: can't open input file %s\n", d->inbasefilename, infilename);
314 DecoderSession_destroy(d, /*error_occurred=*/true);
322 flac__analyze_init(aopts);
327 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
329 if(0 != d->fout && d->fout != stdout) {
332 unlink(d->outfilename);
335 if(0 != d->fin && d->fin != stdin)
340 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, decode_options_t decode_options, const char *infilename)
342 FLAC__uint32 test = 1;
344 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
347 if(decoder_session->is_ogg) {
348 decoder_session->decoder.ogg.stream = OggFLAC__stream_decoder_new();
350 if(0 == decoder_session->decoder.ogg.stream) {
351 fprintf(stderr, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
355 if(!decode_options.use_first_serial_number)
356 OggFLAC__stream_decoder_set_serial_number(decoder_session->decoder.ogg.stream, decode_options.serial_number);
357 if (decoder_session->replaygain.spec.apply)
358 OggFLAC__stream_decoder_set_metadata_respond(decoder_session->decoder.ogg.stream, FLAC__METADATA_TYPE_VORBIS_COMMENT);
360 OggFLAC__stream_decoder_set_read_callback(decoder_session->decoder.ogg.stream, read_callback);
362 * The three ugly casts here are to 'downcast' the 'void *' argument of
363 * the callback down to 'FLAC__StreamDecoder *'. In C++ this would be
364 * unnecessary but here the cast makes the C compiler happy.
366 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);
367 OggFLAC__stream_decoder_set_metadata_callback(decoder_session->decoder.ogg.stream, (void (*)(const OggFLAC__StreamDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
368 OggFLAC__stream_decoder_set_error_callback(decoder_session->decoder.ogg.stream, (void (*)(const OggFLAC__StreamDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
369 OggFLAC__stream_decoder_set_client_data(decoder_session->decoder.ogg.stream, decoder_session);
371 if(OggFLAC__stream_decoder_init(decoder_session->decoder.ogg.stream) != OggFLAC__STREAM_DECODER_OK) {
372 print_error_with_state(decoder_session, "ERROR initializing decoder");
378 (void)decode_options;
381 decoder_session->decoder.flac.file = FLAC__file_decoder_new();
383 if(0 == decoder_session->decoder.flac.file) {
384 fprintf(stderr, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
388 FLAC__file_decoder_set_md5_checking(decoder_session->decoder.flac.file, true);
389 FLAC__file_decoder_set_filename(decoder_session->decoder.flac.file, infilename);
390 if (decoder_session->replaygain.spec.apply)
391 FLAC__file_decoder_set_metadata_respond(decoder_session->decoder.flac.file, FLAC__METADATA_TYPE_VORBIS_COMMENT);
393 * The three ugly casts here are to 'downcast' the 'void *' argument of
394 * the callback down to 'FLAC__FileDecoder *'.
396 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);
397 FLAC__file_decoder_set_metadata_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
398 FLAC__file_decoder_set_error_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
399 FLAC__file_decoder_set_client_data(decoder_session->decoder.flac.file, decoder_session);
401 if(FLAC__file_decoder_init(decoder_session->decoder.flac.file) != FLAC__FILE_DECODER_OK) {
402 print_error_with_state(decoder_session, "ERROR initializing decoder");
410 FLAC__bool DecoderSession_process(DecoderSession *d)
414 if(!OggFLAC__stream_decoder_process_until_end_of_metadata(d->decoder.ogg.stream)) {
415 if(d->verbose) fprintf(stderr, "\n");
416 print_error_with_state(d, "ERROR while decoding metadata");
419 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) {
420 if(d->verbose) fprintf(stderr, "\n");
421 print_error_with_state(d, "ERROR during metadata decoding");
428 if(!FLAC__file_decoder_process_until_end_of_metadata(d->decoder.flac.file)) {
429 if(d->verbose) fprintf(stderr, "\n");
430 print_error_with_state(d, "ERROR while decoding metadata");
433 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) {
434 if(d->verbose) fprintf(stderr, "\n");
435 print_error_with_state(d, "ERROR during metadata decoding");
442 if(d->skip_specification->value.samples > 0) {
443 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
446 if(d->is_ogg) { /*@@@ (move this check into main.c) */
447 fprintf(stderr, "%s: ERROR, can't skip when decoding Ogg-FLAC yet; convert to native-FLAC first\n", d->inbasefilename);
451 if(!FLAC__file_decoder_seek_absolute(d->decoder.flac.file, skip)) {
452 print_error_with_state(d, "ERROR seeking while skipping bytes");
455 if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file)) {
456 if(d->verbose) fprintf(stderr, "\n");
457 print_error_with_state(d, "ERROR while decoding frames");
460 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) {
461 if(d->verbose) fprintf(stderr, "\n");
462 print_error_with_state(d, "ERROR during decoding");
469 if(!OggFLAC__stream_decoder_process_until_end_of_stream(d->decoder.ogg.stream)) {
470 if(d->verbose) fprintf(stderr, "\n");
471 print_error_with_state(d, "ERROR while decoding data");
474 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) {
475 if(d->verbose) fprintf(stderr, "\n");
476 print_error_with_state(d, "ERROR during decoding");
483 if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file)) {
484 if(d->verbose) fprintf(stderr, "\n");
485 print_error_with_state(d, "ERROR while decoding data");
488 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) {
489 if(d->verbose) fprintf(stderr, "\n");
490 print_error_with_state(d, "ERROR during decoding");
496 if(d->is_aiff_out && ((d->total_samples * d->channels * ((d->bps+7)/8)) & 1)) {
497 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
498 print_error_with_state(d, "ERROR writing pad byte to AIFF SSND chunk");
506 int DecoderSession_finish_ok(DecoderSession *d)
508 FLAC__bool md5_failure = false;
512 if(d->decoder.ogg.stream) {
513 OggFLAC__stream_decoder_finish(d->decoder.ogg.stream);
516 OggFLAC__stream_decoder_delete(d->decoder.ogg.stream);
522 if(d->decoder.flac.file) {
523 md5_failure = !FLAC__file_decoder_finish(d->decoder.flac.file);
525 FLAC__file_decoder_delete(d->decoder.flac.file);
529 flac__analyze_finish(d->aopts);
531 fprintf(stderr, "\r%s: WARNING, MD5 signature mismatch\n", d->inbasefilename);
535 fprintf(stderr, "\r%s: %s \n", d->inbasefilename, d->test_only? "ok ":d->analysis_mode?"done ":"done");
537 DecoderSession_destroy(d, /*error_occurred=*/false);
538 if((d->is_wave_out || d->is_aiff_out) && d->wave_chunk_size_fixup.needs_fixup)
539 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))
544 int DecoderSession_finish_error(DecoderSession *d)
548 if(d->decoder.ogg.stream) {
549 OggFLAC__stream_decoder_finish(d->decoder.ogg.stream);
550 OggFLAC__stream_decoder_delete(d->decoder.ogg.stream);
556 if(d->decoder.flac.file) {
557 FLAC__file_decoder_finish(d->decoder.flac.file);
558 FLAC__file_decoder_delete(d->decoder.flac.file);
562 flac__analyze_finish(d->aopts);
563 DecoderSession_destroy(d, /*error_occurred=*/true);
567 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
569 /* convert from mm:ss.sss to sample number if necessary */
570 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
572 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
573 if(spec->is_relative && spec->value.samples == 0) {
574 spec->is_relative = false;
578 /* in any other case the total samples in the input must be known */
579 if(total_samples_in_input == 0) {
580 fprintf(stderr, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
584 FLAC__ASSERT(spec->value_is_samples);
586 /* convert relative specifications to absolute */
587 if(spec->is_relative) {
588 if(spec->value.samples <= 0)
589 spec->value.samples += (FLAC__int64)total_samples_in_input;
591 spec->value.samples += skip;
592 spec->is_relative = false;
596 if(spec->value.samples < 0) {
597 fprintf(stderr, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
600 if((FLAC__uint64)spec->value.samples <= skip) {
601 fprintf(stderr, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
604 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
605 fprintf(stderr, "%s: ERROR, --until value is after end of input\n", inbasefilename);
612 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
614 FLAC__byte *b = (FLAC__byte*)(&val);
615 if(is_big_endian_host_) {
617 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
619 return flac__utils_fwrite(b, 1, 2, f) == 2;
622 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
624 FLAC__byte *b = (FLAC__byte*)(&val);
625 if(is_big_endian_host_) {
627 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
628 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
630 return flac__utils_fwrite(b, 1, 4, f) == 4;
633 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
635 FLAC__byte *b = (FLAC__byte*)(&val);
636 if(!is_big_endian_host_) {
638 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
640 return flac__utils_fwrite(b, 1, 2, f) == 2;
643 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
645 FLAC__byte *b = (FLAC__byte*)(&val);
646 if(!is_big_endian_host_) {
648 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
649 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
651 return flac__utils_fwrite(b, 1, 4, f) == 4;
654 FLAC__bool write_sane_extended(FILE *f, unsigned val)
655 /* Write to 'f' a SANE extended representation of 'val'. Return false if
656 * the write succeeds; return true otherwise.
658 * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
659 * of exponent, and 64 bits of significand (mantissa). Unlike most IEEE-754
660 * representations, it does not imply a 1 above the MSB of the significand.
666 unsigned int shift, exponent;
668 FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
670 for(shift= 0U; (val>>(31-shift))==0U; ++shift)
673 exponent= 63U-(shift+32U); /* add 32 for unused second word */
675 if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
677 if(!write_big_endian_uint32(f, val))
679 if(!write_big_endian_uint32(f, 0)) /* unused second word */
685 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)
687 const char *fmt_desc = (is_wave_out? "WAVE" : "AIFF");
688 FLAC__bool (*write_it)(FILE *, FLAC__uint32) = (is_wave_out? write_little_endian_uint32 : write_big_endian_uint32);
689 FILE *f = fopen(outfilename, "r+b");
690 FLAC__uint32 data_size, aligned_data_size;
693 fprintf(stderr, "ERROR, couldn't open file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
697 data_size = aligned_data_size = total_samples * channels * ((bps+7)/8);
698 if(!is_wave_out && (aligned_data_size & 1))
701 if(fseek(f, riff_offset, SEEK_SET) < 0) {
702 fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
706 if(!write_it(f, aligned_data_size + (is_wave_out? 36 : 46))) {
707 fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
712 if(fseek(f, frames_offset, SEEK_SET) < 0) {
713 fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
717 if(!write_it(f, total_samples)) {
718 fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
723 if(fseek(f, data_offset, SEEK_SET) < 0) {
724 fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
728 if(!write_it(f, data_size + (is_wave_out? 0 : 8))) {
729 fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
738 FLAC__StreamDecoderReadStatus read_callback(const OggFLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
740 DecoderSession *decoder_session = (DecoderSession*)client_data;
741 FILE *fin = decoder_session->fin;
744 (void)decoder; /* avoid compiler warning */
746 if (decoder_session->abort_flag)
747 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
750 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
752 bytes_read = fread(buffer, 1, *bytes, fin);
755 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
757 *bytes = (unsigned)bytes_read;
759 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
763 FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
765 DecoderSession *decoder_session = (DecoderSession*)client_data;
766 FILE *fout = decoder_session->fout;
767 const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
768 FLAC__bool is_big_endian = (decoder_session->is_aiff_out? true : (decoder_session->is_wave_out? false : decoder_session->is_big_endian));
769 FLAC__bool is_unsigned_samples = (decoder_session->is_aiff_out? false : (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples));
770 unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
771 static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
772 FLAC__uint8 *u8buffer = (FLAC__uint8 *)s8buffer;
773 FLAC__int16 *s16buffer = (FLAC__int16 *)s8buffer;
774 FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
775 FLAC__int32 *s32buffer = (FLAC__int32 *)s8buffer;
776 FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
780 if(decoder_session->abort_flag)
781 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
783 if(bps != decoder_session->bps) {
784 fprintf(stderr, "%s: ERROR, bits-per-sample is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, bps, decoder_session->bps);
785 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
787 if(channels != decoder_session->channels) {
788 fprintf(stderr, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
789 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
791 if(frame->header.sample_rate != decoder_session->sample_rate) {
792 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);
793 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
797 * limit the number of samples to accept based on --until
799 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
800 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
801 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
802 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
803 if(decoder_session->until_specification->value.samples > 0) {
804 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
805 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
806 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
807 FLAC__ASSERT(until >= input_samples_passed);
808 if(input_samples_passed + wide_samples > until)
809 wide_samples = (unsigned)(until - input_samples_passed);
812 if(wide_samples > 0) {
813 decoder_session->samples_processed += wide_samples;
814 decoder_session->frame_counter++;
816 if(decoder_session->verbose && !(decoder_session->frame_counter & 0x3f))
817 print_stats(decoder_session);
819 if(decoder_session->analysis_mode) {
820 flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->aopts, fout);
822 else if(!decoder_session->test_only) {
823 if (decoder_session->replaygain.apply) {
824 const size_t n = FLAC__replaygain_synthesis__apply_gain(
831 bps, /* source_bps */
832 bps, /* target_bps */
833 decoder_session->replaygain.scale,
834 decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
835 decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
836 &decoder_session->replaygain.dither_context
838 if(flac__utils_fwrite(u8buffer, 1, n, fout) != n)
839 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
842 if(is_unsigned_samples) {
843 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
844 for(channel = 0; channel < channels; channel++, sample++)
845 u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
848 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
849 for(channel = 0; channel < channels; channel++, sample++)
850 s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
852 if(flac__utils_fwrite(u8buffer, 1, sample, fout) != sample)
853 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
856 if(is_unsigned_samples) {
857 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
858 for(channel = 0; channel < channels; channel++, sample++)
859 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
862 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
863 for(channel = 0; channel < channels; channel++, sample++)
864 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
866 if(is_big_endian != is_big_endian_host_) {
868 const unsigned bytes = sample * 2;
869 for(byte = 0; byte < bytes; byte += 2) {
870 tmp = u8buffer[byte];
871 u8buffer[byte] = u8buffer[byte+1];
872 u8buffer[byte+1] = tmp;
875 if(flac__utils_fwrite(u16buffer, 2, sample, fout) != sample)
876 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
879 if(is_unsigned_samples) {
880 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
881 for(channel = 0; channel < channels; channel++, sample++)
882 u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
885 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
886 for(channel = 0; channel < channels; channel++, sample++)
887 s32buffer[sample] = buffer[channel][wide_sample];
889 if(is_big_endian != is_big_endian_host_) {
891 const unsigned bytes = sample * 4;
892 for(byte = 0; byte < bytes; byte += 4) {
893 tmp = u8buffer[byte];
894 u8buffer[byte] = u8buffer[byte+3];
895 u8buffer[byte+3] = tmp;
896 tmp = u8buffer[byte+1];
897 u8buffer[byte+1] = u8buffer[byte+2];
898 u8buffer[byte+2] = tmp;
903 const unsigned bytes = sample * 4;
904 for(lbyte = byte = 0; byte < bytes; ) {
906 u8buffer[lbyte++] = u8buffer[byte++];
907 u8buffer[lbyte++] = u8buffer[byte++];
908 u8buffer[lbyte++] = u8buffer[byte++];
913 const unsigned bytes = sample * 4;
914 for(lbyte = byte = 0; byte < bytes; ) {
915 u8buffer[lbyte++] = u8buffer[byte++];
916 u8buffer[lbyte++] = u8buffer[byte++];
917 u8buffer[lbyte++] = u8buffer[byte++];
921 if(flac__utils_fwrite(u8buffer, 3, sample, fout) != sample)
922 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
929 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
932 void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
934 DecoderSession *decoder_session = (DecoderSession*)client_data;
936 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
937 FLAC__uint64 skip, until;
938 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
939 decoder_session->channels = metadata->data.stream_info.channels;
940 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
942 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
943 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
944 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
946 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
947 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
948 fprintf(stderr, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
949 decoder_session->abort_flag = true;
952 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
953 fprintf(stderr, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
954 decoder_session->abort_flag = true;
957 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
959 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
960 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
961 decoder_session->abort_flag = true;
964 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
965 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
968 decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
970 if(decoder_session->bps != 8 && decoder_session->bps != 16 && decoder_session->bps != 24) {
971 fprintf(stderr, "%s: ERROR: bits per sample is not 8/16/24\n", decoder_session->inbasefilename);
972 decoder_session->abort_flag = true;
976 /* write the WAVE/AIFF headers if necessary */
977 if(!decoder_session->analysis_mode && !decoder_session->test_only && (decoder_session->is_wave_out || decoder_session->is_aiff_out)) {
978 const char *fmt_desc = decoder_session->is_wave_out? "WAVE" : "AIFF";
979 FLAC__uint64 data_size = decoder_session->total_samples * decoder_session->channels * ((decoder_session->bps+7)/8);
980 if(decoder_session->total_samples == 0) {
981 if(decoder_session->fout == stdout) {
982 fprintf(stderr, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
983 fprintf(stderr, " Generated %s file will have a data chunk size of 0. Try\n", fmt_desc);
984 fprintf(stderr, " decoding directly to a file instead.\n");
987 decoder_session->wave_chunk_size_fixup.needs_fixup = true;
990 if(data_size >= 0xFFFFFFDC) {
991 fprintf(stderr, "%s: ERROR: stream is too big to fit in a single %s file chunk\n", decoder_session->inbasefilename, fmt_desc);
992 decoder_session->abort_flag = true;
995 if(decoder_session->is_wave_out) {
996 if(flac__utils_fwrite("RIFF", 1, 4, decoder_session->fout) != 4)
997 decoder_session->abort_flag = true;
999 if(decoder_session->wave_chunk_size_fixup.needs_fixup)
1000 decoder_session->wave_chunk_size_fixup.riff_offset = ftell(decoder_session->fout);
1002 if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)(data_size+36))) /* filesize-8 */
1003 decoder_session->abort_flag = true;
1005 if(flac__utils_fwrite("WAVEfmt ", 1, 8, decoder_session->fout) != 8)
1006 decoder_session->abort_flag = true;
1008 if(flac__utils_fwrite("\020\000\000\000", 1, 4, decoder_session->fout) != 4) /* chunk size = 16 */
1009 decoder_session->abort_flag = true;
1011 if(flac__utils_fwrite("\001\000", 1, 2, decoder_session->fout) != 2) /* compression code == 1 */
1012 decoder_session->abort_flag = true;
1014 if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels)))
1015 decoder_session->abort_flag = true;
1017 if(!write_little_endian_uint32(decoder_session->fout, decoder_session->sample_rate))
1018 decoder_session->abort_flag = true;
1020 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 ??? */
1021 decoder_session->abort_flag = true;
1023 if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels * ((decoder_session->bps+7) / 8)))) /* block align */
1024 decoder_session->abort_flag = true;
1026 if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->bps))) /* bits per sample */
1027 decoder_session->abort_flag = true;
1029 if(flac__utils_fwrite("data", 1, 4, decoder_session->fout) != 4)
1030 decoder_session->abort_flag = true;
1032 if(decoder_session->wave_chunk_size_fixup.needs_fixup)
1033 decoder_session->wave_chunk_size_fixup.data_offset = ftell(decoder_session->fout);
1035 if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)data_size)) /* data size */
1036 decoder_session->abort_flag = true;
1039 const FLAC__uint32 aligned_data_size = (FLAC__uint32)((data_size+1) & (~1U));
1041 if(flac__utils_fwrite("FORM", 1, 4, decoder_session->fout) != 4)
1042 decoder_session->abort_flag = true;
1044 if(decoder_session->wave_chunk_size_fixup.needs_fixup)
1045 decoder_session->wave_chunk_size_fixup.riff_offset = ftell(decoder_session->fout);
1047 if(!write_big_endian_uint32(decoder_session->fout, (FLAC__uint32)(aligned_data_size+46))) /* filesize-8 */
1048 decoder_session->abort_flag = true;
1050 if(flac__utils_fwrite("AIFFCOMM", 1, 8, decoder_session->fout) != 8)
1051 decoder_session->abort_flag = true;
1053 if(flac__utils_fwrite("\000\000\000\022", 1, 4, decoder_session->fout) != 4) /* chunk size = 18 */
1054 decoder_session->abort_flag = true;
1056 if(!write_big_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels)))
1057 decoder_session->abort_flag = true;
1059 if(decoder_session->wave_chunk_size_fixup.needs_fixup)
1060 decoder_session->wave_chunk_size_fixup.frames_offset = ftell(decoder_session->fout);
1062 if(!write_big_endian_uint32(decoder_session->fout, (FLAC__uint32)decoder_session->total_samples))
1063 decoder_session->abort_flag = true;
1065 if(!write_big_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->bps)))
1066 decoder_session->abort_flag = true;
1068 if(!write_sane_extended(decoder_session->fout, decoder_session->sample_rate))
1069 decoder_session->abort_flag = true;
1071 if(flac__utils_fwrite("SSND", 1, 4, decoder_session->fout) != 4)
1072 decoder_session->abort_flag = true;
1074 if(decoder_session->wave_chunk_size_fixup.needs_fixup)
1075 decoder_session->wave_chunk_size_fixup.data_offset = ftell(decoder_session->fout);
1077 if(!write_big_endian_uint32(decoder_session->fout, (FLAC__uint32)data_size+8)) /* data size */
1078 decoder_session->abort_flag = true;
1080 if(!write_big_endian_uint32(decoder_session->fout, 0/*offset*/))
1081 decoder_session->abort_flag = true;
1083 if(!write_big_endian_uint32(decoder_session->fout, 0/*block_size*/))
1084 decoder_session->abort_flag = true;
1088 else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1089 if (decoder_session->replaygain.spec.apply) {
1091 if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, &gain, &peak))) {
1092 fprintf(stderr, "%s: WARNING: can't get %s ReplayGain tag\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track");
1095 const char *ls[] = { "no", "peak", "hard" };
1096 const char *ns[] = { "no", "low", "medium", "high" };
1097 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1098 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1099 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1100 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]);
1101 fprintf(stderr, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1107 void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1109 DecoderSession *decoder_session = (DecoderSession*)client_data;
1111 fprintf(stderr, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1112 if(!decoder_session->continue_through_decode_errors)
1113 decoder_session->abort_flag = true;
1116 void print_error_with_state(const DecoderSession *d, const char *message)
1118 const int ilen = strlen(d->inbasefilename) + 1;
1120 fprintf(stderr, "\n%s: %s\n", d->inbasefilename, message);
1122 #ifdef FLAC__HAS_OGG
1124 const OggFLAC__StreamDecoderState osd_state = OggFLAC__stream_decoder_get_state(d->decoder.ogg.stream);
1125 if(osd_state != OggFLAC__STREAM_DECODER_FLAC_STREAM_DECODER_ERROR) {
1126 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)osd_state, OggFLAC__StreamDecoderStateString[osd_state]);
1129 const FLAC__StreamDecoderState fsd_state = OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream);
1130 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1136 const FLAC__FileDecoderState ffd_state = FLAC__file_decoder_get_state(d->decoder.flac.file);
1137 if(ffd_state != FLAC__FILE_DECODER_SEEKABLE_STREAM_DECODER_ERROR) {
1138 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ffd_state, FLAC__FileDecoderStateString[ffd_state]);
1141 const FLAC__SeekableStreamDecoderState fssd_state = FLAC__file_decoder_get_seekable_stream_decoder_state(d->decoder.flac.file);
1142 if(fssd_state != FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR) {
1143 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fssd_state, FLAC__SeekableStreamDecoderStateString[fssd_state]);
1146 const FLAC__StreamDecoderState fsd_state = FLAC__file_decoder_get_stream_decoder_state(d->decoder.flac.file);
1147 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1153 void print_stats(const DecoderSession *decoder_session)
1155 if(decoder_session->verbose) {
1156 #if defined _MSC_VER || defined __MINGW32__
1157 /* with VC++ you have to spoon feed it the casting */
1158 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1160 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1162 if(decoder_session->total_samples > 0) {
1163 fprintf(stderr, "\r%s: %s%u%% complete",
1164 decoder_session->inbasefilename,
1165 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1166 (unsigned)floor(progress + 0.5)
1170 fprintf(stderr, "\r%s: %s %u samples",
1171 decoder_session->inbasefilename,
1172 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1173 (unsigned)decoder_session->samples_processed