1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006 Josh Coalson
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 #if defined _WIN32 && !defined __CYGWIN__
24 /* where MSVC puts unlink() */
29 #if defined _MSC_VER || defined __MINGW32__
30 #include <sys/types.h> /* for off_t */
31 //@@@ [2G limit] hacks for MSVC6
36 #include <math.h> /* for floor() */
37 #include <stdio.h> /* for FILE etc. */
38 #include <string.h> /* for strcmp(), strerror() */
40 #include "share/grabbag.h"
41 #include "share/replaygain_synthesis.h"
45 #include "OggFLAC/stream_decoder.h"
53 FLAC__bool is_aiff_out;
54 FLAC__bool is_wave_out;
55 FLAC__bool continue_through_decode_errors;
58 replaygain_synthesis_spec_t spec;
59 FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */
61 DitherContext dither_context;
65 FLAC__bool analysis_mode;
66 analysis_options aopts;
67 utils__SkipUntilSpecification *skip_specification;
68 utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
69 utils__CueSpecification *cue_specification;
71 const char *inbasefilename;
72 const char *outfilename;
74 FLAC__uint64 samples_processed;
75 unsigned frame_counter;
76 FLAC__bool abort_flag;
77 FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
78 FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */
80 FLAC__bool iff_headers_need_fixup;
82 FLAC__bool is_big_endian;
83 FLAC__bool is_unsigned_samples;
84 FLAC__bool got_stream_info;
85 FLAC__uint64 total_samples;
91 FLAC__StreamDecoder *flac;
93 OggFLAC__StreamDecoder *ogg;
101 static FLAC__bool is_big_endian_host_;
107 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, 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, utils__CueSpecification *cue_specification, const char *infilename, const char *outfilename);
108 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
109 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, decode_options_t decode_options, const char *infilename);
110 static FLAC__bool DecoderSession_process(DecoderSession *d);
111 static int DecoderSession_finish_ok(DecoderSession *d);
112 static int DecoderSession_finish_error(DecoderSession *d);
113 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
114 static FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples);
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_iff_headers(DecoderSession *d);
121 static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
122 static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
123 static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
124 static void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status);
125 static void print_error_with_state(const DecoderSession *d, const char *message);
126 static void print_stats(const DecoderSession *decoder_session);
132 int flac__decode_aiff(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
134 DecoderSession decoder_session;
137 DecoderSession_construct(
140 options.common.is_ogg,
144 /*is_aiff_out=*/true,
145 /*is_wave_out=*/false,
146 options.common.continue_through_decode_errors,
147 options.common.replaygain_synthesis_spec,
150 &options.common.skip_specification,
151 &options.common.until_specification,
152 options.common.has_cue_specification? &options.common.cue_specification : 0,
159 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
160 return DecoderSession_finish_error(&decoder_session);
162 if(!DecoderSession_process(&decoder_session))
163 return DecoderSession_finish_error(&decoder_session);
165 return DecoderSession_finish_ok(&decoder_session);
168 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
170 DecoderSession decoder_session;
173 DecoderSession_construct(
176 options.common.is_ogg,
180 /*is_aiff_out=*/false,
181 /*is_wave_out=*/true,
182 options.common.continue_through_decode_errors,
183 options.common.replaygain_synthesis_spec,
186 &options.common.skip_specification,
187 &options.common.until_specification,
188 options.common.has_cue_specification? &options.common.cue_specification : 0,
195 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
196 return DecoderSession_finish_error(&decoder_session);
198 if(!DecoderSession_process(&decoder_session))
199 return DecoderSession_finish_error(&decoder_session);
201 return DecoderSession_finish_ok(&decoder_session);
204 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
206 DecoderSession decoder_session;
208 decoder_session.is_big_endian = options.is_big_endian;
209 decoder_session.is_unsigned_samples = options.is_unsigned_samples;
212 DecoderSession_construct(
215 options.common.is_ogg,
219 /*is_aiff_out=*/false,
220 /*is_wave_out=*/false,
221 options.common.continue_through_decode_errors,
222 options.common.replaygain_synthesis_spec,
225 &options.common.skip_specification,
226 &options.common.until_specification,
227 options.common.has_cue_specification? &options.common.cue_specification : 0,
234 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
235 return DecoderSession_finish_error(&decoder_session);
237 if(!DecoderSession_process(&decoder_session))
238 return DecoderSession_finish_error(&decoder_session);
240 return DecoderSession_finish_ok(&decoder_session);
243 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, 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, utils__CueSpecification *cue_specification, const char *infilename, const char *outfilename)
251 d->is_aiff_out = is_aiff_out;
252 d->is_wave_out = is_wave_out;
253 d->continue_through_decode_errors = continue_through_decode_errors;
254 d->replaygain.spec = replaygain_synthesis_spec;
255 d->replaygain.apply = false;
256 d->replaygain.scale = 0.0;
257 /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
258 d->test_only = (0 == outfilename);
259 d->analysis_mode = analysis_mode;
261 d->skip_specification = skip_specification;
262 d->until_specification = until_specification;
263 d->cue_specification = cue_specification;
265 d->inbasefilename = grabbag__file_get_basename(infilename);
266 d->outfilename = outfilename;
268 d->samples_processed = 0;
269 d->frame_counter = 0;
270 d->abort_flag = false;
271 d->aborting_due_to_until = false;
272 d->aborting_due_to_unparseable = false;
274 d->iff_headers_need_fixup = false;
276 d->total_samples = 0;
277 d->got_stream_info = false;
287 d->fout = 0; /* initialized with an open file later if necessary */
289 FLAC__ASSERT(!(d->test_only && d->analysis_mode));
292 if(0 == strcmp(outfilename, "-")) {
293 d->fout = grabbag__file_get_binary_stdout();
296 if(0 == (d->fout = fopen(outfilename, "wb"))) {
297 flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
298 DecoderSession_destroy(d, /*error_occurred=*/true);
305 flac__analyze_init(aopts);
310 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
312 if(0 != d->fout && d->fout != stdout) {
315 unlink(d->outfilename);
319 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, decode_options_t decode_options, const char *infilename)
321 FLAC__StreamDecoderInitStatus init_status;
322 FLAC__uint32 test = 1;
324 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
327 if(decoder_session->is_ogg) {
328 decoder_session->decoder.ogg = OggFLAC__stream_decoder_new();
330 if(0 == decoder_session->decoder.ogg) {
331 flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
335 OggFLAC__stream_decoder_set_md5_checking(decoder_session->decoder.ogg, true);
336 if(!decode_options.use_first_serial_number)
337 OggFLAC__stream_decoder_set_serial_number(decoder_session->decoder.ogg, decode_options.serial_number);
338 if (0 != decoder_session->cue_specification)
339 OggFLAC__stream_decoder_set_metadata_respond(decoder_session->decoder.ogg, FLAC__METADATA_TYPE_CUESHEET);
340 if (decoder_session->replaygain.spec.apply)
341 OggFLAC__stream_decoder_set_metadata_respond(decoder_session->decoder.ogg, FLAC__METADATA_TYPE_VORBIS_COMMENT);
343 init_status = OggFLAC__stream_decoder_init_file(decoder_session->decoder.ogg, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
344 if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
345 print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
351 (void)decode_options;
354 decoder_session->decoder.flac = FLAC__stream_decoder_new();
356 if(0 == decoder_session->decoder.flac) {
357 flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
361 FLAC__stream_decoder_set_md5_checking(decoder_session->decoder.flac, true);
362 if (0 != decoder_session->cue_specification)
363 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder.flac, FLAC__METADATA_TYPE_CUESHEET);
364 if (decoder_session->replaygain.spec.apply)
365 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder.flac, FLAC__METADATA_TYPE_VORBIS_COMMENT);
367 init_status = FLAC__stream_decoder_init_file(decoder_session->decoder.flac, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
368 if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
369 print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
377 FLAC__bool DecoderSession_process(DecoderSession *d)
381 if(!OggFLAC__stream_decoder_process_until_end_of_metadata(d->decoder.ogg)) {
382 flac__utils_printf(stderr, 2, "\n");
383 print_error_with_state(d, "ERROR while decoding metadata");
386 if(OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_OK && OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_END_OF_STREAM) {
387 flac__utils_printf(stderr, 2, "\n");
388 print_error_with_state(d, "ERROR during metadata decoding");
389 if(!d->continue_through_decode_errors)
396 if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder.flac)) {
397 flac__utils_printf(stderr, 2, "\n");
398 print_error_with_state(d, "ERROR while decoding metadata");
401 if(FLAC__stream_decoder_get_state(d->decoder.flac) > FLAC__STREAM_DECODER_END_OF_STREAM) {
402 flac__utils_printf(stderr, 2, "\n");
403 print_error_with_state(d, "ERROR during metadata decoding");
404 if(!d->continue_through_decode_errors)
411 /* write the WAVE/AIFF headers if necessary */
412 if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out)) {
413 if(!write_iff_headers(d->fout, d, d->total_samples)) {
414 d->abort_flag = true;
419 if(d->skip_specification->value.samples > 0) {
420 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
424 if(!OggFLAC__stream_decoder_seek_absolute(d->decoder.ogg, skip)) {
425 print_error_with_state(d, "ERROR seeking while skipping bytes");
428 if(!OggFLAC__stream_decoder_process_until_end_of_stream(d->decoder.ogg) && !d->aborting_due_to_until) {
429 flac__utils_printf(stderr, 2, "\n");
430 print_error_with_state(d, "ERROR while decoding frames");
433 if(OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_OK && OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until) {
434 flac__utils_printf(stderr, 2, "\n");
435 print_error_with_state(d, "ERROR during decoding");
442 if(!FLAC__stream_decoder_seek_absolute(d->decoder.flac, skip)) {
443 print_error_with_state(d, "ERROR seeking while skipping bytes");
446 if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder.flac) && !d->aborting_due_to_until) {
447 flac__utils_printf(stderr, 2, "\n");
448 print_error_with_state(d, "ERROR while decoding frames");
451 if(FLAC__stream_decoder_get_state(d->decoder.flac) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until) {
452 flac__utils_printf(stderr, 2, "\n");
453 print_error_with_state(d, "ERROR during decoding");
461 if(!OggFLAC__stream_decoder_process_until_end_of_stream(d->decoder.ogg) && !d->aborting_due_to_until) {
462 flac__utils_printf(stderr, 2, "\n");
463 print_error_with_state(d, "ERROR while decoding data");
466 if(OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_OK && OggFLAC__stream_decoder_get_state(d->decoder.ogg) != OggFLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until) {
467 flac__utils_printf(stderr, 2, "\n");
468 print_error_with_state(d, "ERROR during decoding");
475 if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder.flac) && !d->aborting_due_to_until) {
476 flac__utils_printf(stderr, 2, "\n");
477 print_error_with_state(d, "ERROR while decoding data");
480 if(FLAC__stream_decoder_get_state(d->decoder.flac) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until) {
481 flac__utils_printf(stderr, 2, "\n");
482 print_error_with_state(d, "ERROR during decoding");
488 if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out) && ((d->total_samples * d->channels * ((d->bps+7)/8)) & 1)) {
489 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
490 print_error_with_state(d, d->is_wave_out?
491 "ERROR writing pad byte to WAVE data chunk" :
492 "ERROR writing pad byte to AIFF SSND chunk"
501 int DecoderSession_finish_ok(DecoderSession *d)
503 FLAC__bool ok = true, md5_failure = false;
508 md5_failure = !OggFLAC__stream_decoder_finish(d->decoder.ogg) && !d->aborting_due_to_until;
510 OggFLAC__stream_decoder_delete(d->decoder.ogg);
516 if(d->decoder.flac) {
517 md5_failure = !FLAC__stream_decoder_finish(d->decoder.flac) && !d->aborting_due_to_until;
519 FLAC__stream_decoder_delete(d->decoder.flac);
523 flac__analyze_finish(d->aopts);
525 flac__utils_printf(stderr, 1, "\r%s: ERROR, MD5 signature mismatch\n", d->inbasefilename);
526 ok = d->continue_through_decode_errors;
528 else if(!d->got_stream_info) {
529 flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since there was no STREAMINFO\n", d->inbasefilename);
532 flac__utils_printf(stderr, 2, "\r%s: %s \n", d->inbasefilename, d->test_only? "ok ":d->analysis_mode?"done ":"done");
534 DecoderSession_destroy(d, /*error_occurred=*/!ok);
535 if((d->is_wave_out || d->is_aiff_out) && (d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))))
536 if(!fixup_iff_headers(d))
541 int DecoderSession_finish_error(DecoderSession *d)
546 OggFLAC__stream_decoder_finish(d->decoder.ogg);
547 OggFLAC__stream_decoder_delete(d->decoder.ogg);
553 if(d->decoder.flac) {
554 FLAC__stream_decoder_finish(d->decoder.flac);
555 FLAC__stream_decoder_delete(d->decoder.flac);
559 flac__analyze_finish(d->aopts);
560 DecoderSession_destroy(d, /*error_occurred=*/true);
564 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
566 /* convert from mm:ss.sss to sample number if necessary */
567 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
569 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
570 if(spec->is_relative && spec->value.samples == 0) {
571 spec->is_relative = false;
575 /* in any other case the total samples in the input must be known */
576 if(total_samples_in_input == 0) {
577 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
581 FLAC__ASSERT(spec->value_is_samples);
583 /* convert relative specifications to absolute */
584 if(spec->is_relative) {
585 if(spec->value.samples <= 0)
586 spec->value.samples += (FLAC__int64)total_samples_in_input;
588 spec->value.samples += skip;
589 spec->is_relative = false;
593 if(spec->value.samples < 0) {
594 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
597 if((FLAC__uint64)spec->value.samples <= skip) {
598 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
601 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
602 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
609 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
611 const char *fmt_desc = decoder_session->is_wave_out? "WAVE" : "AIFF";
612 FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
613 const FLAC__uint32 aligned_data_size = (FLAC__uint32)((data_size+1) & (~1U)); /* we'll check for overflow later */
616 flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
617 flac__utils_printf(stderr, 1, " Generated %s file will have a data chunk size of 0. Try\n", fmt_desc);
618 flac__utils_printf(stderr, 1, " decoding directly to a file instead.\n");
621 decoder_session->iff_headers_need_fixup = true;
624 if(data_size >= 0xFFFFFFDC) {
625 flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file chunk\n", decoder_session->inbasefilename, fmt_desc);
628 if(decoder_session->is_wave_out) {
629 if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
632 if(!write_little_endian_uint32(f, aligned_data_size+36)) /* filesize-8 */
635 if(flac__utils_fwrite("WAVEfmt ", 1, 8, f) != 8)
638 if(flac__utils_fwrite("\020\000\000\000", 1, 4, f) != 4) /* chunk size = 16 */
641 if(flac__utils_fwrite("\001\000", 1, 2, f) != 2) /* compression code == 1 */
644 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
647 if(!write_little_endian_uint32(f, decoder_session->sample_rate))
650 if(!write_little_endian_uint32(f, decoder_session->sample_rate * decoder_session->channels * ((decoder_session->bps+7) / 8))) /* @@@ or is it (sample_rate*channels*bps) / 8 ??? */
653 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels * ((decoder_session->bps+7) / 8)))) /* block align */
656 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->bps))) /* bits per sample */
659 if(flac__utils_fwrite("data", 1, 4, f) != 4)
662 if(!write_little_endian_uint32(f, (FLAC__uint32)data_size)) /* data size */
666 if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
669 if(!write_big_endian_uint32(f, aligned_data_size+46)) /* filesize-8 */
672 if(flac__utils_fwrite("AIFFCOMM", 1, 8, f) != 8)
675 if(flac__utils_fwrite("\000\000\000\022", 1, 4, f) != 4) /* chunk size = 18 */
678 if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
681 if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
684 if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->bps)))
687 if(!write_sane_extended(f, decoder_session->sample_rate))
690 if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
693 if(!write_big_endian_uint32(f, (FLAC__uint32)data_size+8)) /* data size */
696 if(!write_big_endian_uint32(f, 0/*offset*/))
699 if(!write_big_endian_uint32(f, 0/*block_size*/))
706 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
708 FLAC__byte *b = (FLAC__byte*)(&val);
709 if(is_big_endian_host_) {
711 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
713 return flac__utils_fwrite(b, 1, 2, f) == 2;
716 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
718 FLAC__byte *b = (FLAC__byte*)(&val);
719 if(is_big_endian_host_) {
721 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
722 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
724 return flac__utils_fwrite(b, 1, 4, f) == 4;
727 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
729 FLAC__byte *b = (FLAC__byte*)(&val);
730 if(!is_big_endian_host_) {
732 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
734 return flac__utils_fwrite(b, 1, 2, f) == 2;
737 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
739 FLAC__byte *b = (FLAC__byte*)(&val);
740 if(!is_big_endian_host_) {
742 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
743 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
745 return flac__utils_fwrite(b, 1, 4, f) == 4;
748 FLAC__bool write_sane_extended(FILE *f, unsigned val)
749 /* Write to 'f' a SANE extended representation of 'val'. Return false if
750 * the write succeeds; return true otherwise.
752 * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
753 * of exponent, and 64 bits of significand (mantissa). Unlike most IEEE-754
754 * representations, it does not imply a 1 above the MSB of the significand.
760 unsigned int shift, exponent;
762 FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
764 for(shift= 0U; (val>>(31-shift))==0U; ++shift)
767 exponent= 63U-(shift+32U); /* add 32 for unused second word */
769 if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
771 if(!write_big_endian_uint32(f, val))
773 if(!write_big_endian_uint32(f, 0)) /* unused second word */
779 FLAC__bool fixup_iff_headers(DecoderSession *d)
781 const char *fmt_desc = (d->is_wave_out? "WAVE" : "AIFF");
782 FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
785 flac__utils_printf(stderr, 1, "ERROR, couldn't open file %s while fixing up %s chunk size: %s\n", d->outfilename, fmt_desc, strerror(errno));
789 if(!write_iff_headers(f, d, d->samples_processed)) {
798 FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
800 DecoderSession *decoder_session = (DecoderSession*)client_data;
801 FILE *fout = decoder_session->fout;
802 const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
803 FLAC__bool is_big_endian = (decoder_session->is_aiff_out? true : (decoder_session->is_wave_out? false : decoder_session->is_big_endian));
804 FLAC__bool is_unsigned_samples = (decoder_session->is_aiff_out? false : (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples));
805 unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
806 static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
807 FLAC__uint8 *u8buffer = (FLAC__uint8 *)s8buffer;
808 FLAC__int16 *s16buffer = (FLAC__int16 *)s8buffer;
809 FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
810 FLAC__int32 *s32buffer = (FLAC__int32 *)s8buffer;
811 FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
812 size_t bytes_to_write = 0;
816 if(decoder_session->abort_flag)
817 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
819 /* sanity-check the bits-per-sample */
820 if(decoder_session->bps) {
821 if(bps != decoder_session->bps) {
822 if(decoder_session->got_stream_info)
823 flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, bps, decoder_session->bps);
825 flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, bps, decoder_session->bps);
826 if(!decoder_session->continue_through_decode_errors)
827 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
831 /* must not have gotten STREAMINFO, save the bps from the frame header */
832 FLAC__ASSERT(!decoder_session->got_stream_info);
833 decoder_session->bps = bps;
836 /* sanity-check the #channels */
837 if(decoder_session->channels) {
838 if(channels != decoder_session->channels) {
839 if(decoder_session->got_stream_info)
840 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
842 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, channels, decoder_session->channels);
843 if(!decoder_session->continue_through_decode_errors)
844 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
848 /* must not have gotten STREAMINFO, save the #channels from the frame header */
849 FLAC__ASSERT(!decoder_session->got_stream_info);
850 decoder_session->channels = channels;
853 /* sanity-check the sample rate */
854 if(decoder_session->sample_rate) {
855 if(frame->header.sample_rate != decoder_session->sample_rate) {
856 if(decoder_session->got_stream_info)
857 flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
859 flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
860 if(!decoder_session->continue_through_decode_errors)
861 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
865 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
866 FLAC__ASSERT(!decoder_session->got_stream_info);
867 decoder_session->sample_rate = frame->header.sample_rate;
871 * limit the number of samples to accept based on --until
873 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
874 /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
875 if(decoder_session->skip_specification->is_relative) {
876 if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
877 decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
879 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --skip because the total sample count was not found in the metadata\n", decoder_session->inbasefilename);
880 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
883 if(decoder_session->until_specification->is_relative) {
884 if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
885 decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
887 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until because the total sample count was not found in the metadata\n", decoder_session->inbasefilename);
888 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
891 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
892 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
893 if(decoder_session->until_specification->value.samples > 0) {
894 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
895 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
896 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
897 FLAC__ASSERT(until >= input_samples_passed);
898 if(input_samples_passed + wide_samples > until)
899 wide_samples = (unsigned)(until - input_samples_passed);
900 if (wide_samples == 0) {
901 decoder_session->abort_flag = true;
902 decoder_session->aborting_due_to_until = true;
903 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
907 if(wide_samples > 0) {
908 decoder_session->samples_processed += wide_samples;
909 decoder_session->frame_counter++;
911 if(!(decoder_session->frame_counter & 0x3f))
912 print_stats(decoder_session);
914 if(decoder_session->analysis_mode) {
915 flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->aopts, fout);
917 else if(!decoder_session->test_only) {
918 if (decoder_session->replaygain.apply) {
919 bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
926 bps, /* source_bps */
927 bps, /* target_bps */
928 decoder_session->replaygain.scale,
929 decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
930 decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
931 &decoder_session->replaygain.dither_context
935 if(is_unsigned_samples) {
936 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
937 for(channel = 0; channel < channels; channel++, sample++)
938 u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
941 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
942 for(channel = 0; channel < channels; channel++, sample++)
943 s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
945 bytes_to_write = sample;
948 if(is_unsigned_samples) {
949 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
950 for(channel = 0; channel < channels; channel++, sample++)
951 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
954 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
955 for(channel = 0; channel < channels; channel++, sample++)
956 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
958 if(is_big_endian != is_big_endian_host_) {
960 const unsigned bytes = sample * 2;
961 for(byte = 0; byte < bytes; byte += 2) {
962 tmp = u8buffer[byte];
963 u8buffer[byte] = u8buffer[byte+1];
964 u8buffer[byte+1] = tmp;
967 bytes_to_write = 2 * sample;
970 if(is_unsigned_samples) {
971 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
972 for(channel = 0; channel < channels; channel++, sample++)
973 u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
976 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
977 for(channel = 0; channel < channels; channel++, sample++)
978 s32buffer[sample] = buffer[channel][wide_sample];
980 if(is_big_endian != is_big_endian_host_) {
982 const unsigned bytes = sample * 4;
983 for(byte = 0; byte < bytes; byte += 4) {
984 tmp = u8buffer[byte];
985 u8buffer[byte] = u8buffer[byte+3];
986 u8buffer[byte+3] = tmp;
987 tmp = u8buffer[byte+1];
988 u8buffer[byte+1] = u8buffer[byte+2];
989 u8buffer[byte+2] = tmp;
994 const unsigned bytes = sample * 4;
995 for(lbyte = byte = 0; byte < bytes; ) {
997 u8buffer[lbyte++] = u8buffer[byte++];
998 u8buffer[lbyte++] = u8buffer[byte++];
999 u8buffer[lbyte++] = u8buffer[byte++];
1004 const unsigned bytes = sample * 4;
1005 for(lbyte = byte = 0; byte < bytes; ) {
1006 u8buffer[lbyte++] = u8buffer[byte++];
1007 u8buffer[lbyte++] = u8buffer[byte++];
1008 u8buffer[lbyte++] = u8buffer[byte++];
1012 bytes_to_write = 3 * sample;
1019 if(bytes_to_write > 0) {
1020 if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
1021 /* if a pipe closed when writing to stdout, we let it go without an error message */
1022 if(errno == EPIPE && decoder_session->fout == stdout)
1023 decoder_session->aborting_due_to_until = true;
1024 decoder_session->abort_flag = true;
1025 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1028 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1031 void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1033 DecoderSession *decoder_session = (DecoderSession*)client_data;
1035 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
1036 FLAC__uint64 skip, until;
1037 decoder_session->got_stream_info = true;
1038 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1039 decoder_session->channels = metadata->data.stream_info.channels;
1040 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1042 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
1043 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1044 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1046 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1047 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1048 flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1049 decoder_session->abort_flag = true;
1052 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1053 flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1054 decoder_session->abort_flag = true;
1057 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1058 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1060 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1061 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1062 decoder_session->abort_flag = true;
1065 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1066 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1069 FLAC__ASSERT(decoder_session->total_samples != 0);
1070 FLAC__ASSERT(0 == decoder_session->cue_specification);
1071 decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1074 if(decoder_session->bps != 8 && decoder_session->bps != 16 && decoder_session->bps != 24) {
1075 flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is not 8/16/24\n", decoder_session->inbasefilename);
1076 decoder_session->abort_flag = true;
1080 else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1081 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1082 if(decoder_session->total_samples == 0) {
1083 flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1084 decoder_session->abort_flag = true;
1088 flac__utils_canonicalize_cue_specification(decoder_session->cue_specification, &metadata->data.cue_sheet, decoder_session->total_samples, decoder_session->skip_specification, decoder_session->until_specification);
1090 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1091 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1093 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1094 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1096 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1097 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1098 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1099 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1101 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1103 else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1104 if (decoder_session->replaygain.spec.apply) {
1105 double reference, gain, peak;
1106 if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
1107 flac__utils_printf(stderr, 1, "%s: WARNING: can't get %s (or even %s) ReplayGain tags\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", decoder_session->replaygain.spec.use_album_gain? "track":"album");
1110 const char *ls[] = { "no", "peak", "hard" };
1111 const char *ns[] = { "no", "low", "medium", "high" };
1112 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1113 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1114 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1115 flac__utils_printf(stderr, 1, "%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]);
1116 flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1122 void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1124 DecoderSession *decoder_session = (DecoderSession*)client_data;
1126 flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1127 if(!decoder_session->continue_through_decode_errors) {
1128 decoder_session->abort_flag = true;
1129 if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1130 decoder_session->aborting_due_to_unparseable = true;
1134 void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
1136 const int ilen = strlen(d->inbasefilename) + 1;
1138 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1140 flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
1142 /* print out some more info for some errors: */
1143 if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
1144 flac__utils_printf(stderr, 1,
1146 "An error occurred opening the input file; it is likely that it does not exist\n"
1147 "or is not readable.\n"
1152 void print_error_with_state(const DecoderSession *d, const char *message)
1154 const int ilen = strlen(d->inbasefilename) + 1;
1155 const char *state_string;
1157 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1159 #ifdef FLAC__HAS_OGG
1161 state_string = OggFLAC__stream_decoder_get_resolved_state_string(d->decoder.ogg);
1166 state_string = FLAC__stream_decoder_get_resolved_state_string(d->decoder.flac);
1169 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
1171 /* print out some more info for some errors: */
1172 if (d->aborting_due_to_unparseable) {
1173 flac__utils_printf(stderr, 1,
1175 "The FLAC stream may have been created by a more advanced encoder. Try\n"
1176 " metaflac --show-vendor-tag %s\n"
1177 "If the version number is greater than %s, this decoder is probably\n"
1178 "not able to decode the file. If the version number is not, the file\n"
1179 "may be corrupted, or you may have found a bug. In this case please\n"
1180 "submit a bug report to\n"
1181 " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
1182 "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1183 d->inbasefilename, FLAC__VERSION_STRING
1188 void print_stats(const DecoderSession *decoder_session)
1190 if(flac__utils_verbosity_ >= 2) {
1191 #if defined _MSC_VER || defined __MINGW32__
1192 /* with MSVC you have to spoon feed it the casting */
1193 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1195 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1197 if(decoder_session->total_samples > 0) {
1198 fprintf(stderr, "\r%s: %s%u%% complete",
1199 decoder_session->inbasefilename,
1200 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1201 (unsigned)floor(progress + 0.5)
1205 fprintf(stderr, "\r%s: %s %u samples",
1206 decoder_session->inbasefilename,
1207 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1208 (unsigned)decoder_session->samples_processed