1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008 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 #if _MSC_VER <= 1600 /* @@@ [2G limit] */
37 #include <math.h> /* for floor() */
38 #include <stdio.h> /* for FILE etc. */
39 #include <string.h> /* for strcmp(), strerror() */
41 #include "share/grabbag.h"
42 #include "share/replaygain_synthesis.h"
48 FLAC__bool use_first_serial_number;
53 FLAC__bool treat_warnings_as_errors;
54 FLAC__bool continue_through_decode_errors;
55 FLAC__bool channel_map_none;
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 *infilename;
73 const char *outfilename;
75 FLAC__uint64 samples_processed;
76 unsigned frame_counter;
77 FLAC__bool abort_flag;
78 FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
79 FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */
81 FLAC__bool iff_headers_need_fixup;
83 FLAC__bool is_big_endian;
84 FLAC__bool is_unsigned_samples;
85 FLAC__bool got_stream_info;
86 FLAC__bool has_md5sum;
87 FLAC__uint64 total_samples;
91 FLAC__uint32 channel_mask;
93 /* these are used only in analyze mode */
94 FLAC__uint64 decode_position;
96 FLAC__StreamDecoder *decoder;
100 foreign_metadata_t *foreign_metadata; /* NULL unless --keep-foreign-metadata requested */
101 off_t fm_offset1, fm_offset2, fm_offset3;
105 static FLAC__bool is_big_endian_host_;
111 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool use_first_serial_number, long serial_number, FileFormat format, FLAC__bool treat_warnings_as_errors, FLAC__bool continue_through_decode_errors, FLAC__bool channel_map_none, 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, foreign_metadata_t *foreign_metadata, const char *infilename, const char *outfilename);
112 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
113 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, const char *infilename);
114 static FLAC__bool DecoderSession_process(DecoderSession *d);
115 static int DecoderSession_finish_ok(DecoderSession *d);
116 static int DecoderSession_finish_error(DecoderSession *d);
117 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
118 static FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples);
119 static FLAC__bool write_riff_wave_fmt_chunk(FILE *f, FLAC__bool is_waveformatextensible, unsigned bps, unsigned channels, unsigned sample_rate, FLAC__uint32 channel_mask);
120 static FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate);
121 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
122 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
123 static FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val);
124 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
125 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
126 static FLAC__bool write_sane_extended(FILE *f, unsigned val);
127 static FLAC__bool fixup_iff_headers(DecoderSession *d);
128 static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
129 static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
130 static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
131 static void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status);
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_file(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, decode_options_t options)
141 DecoderSession decoder_session;
144 options.format == FORMAT_WAVE ||
145 options.format == FORMAT_RF64 ||
146 options.format == FORMAT_AIFF ||
147 options.format == FORMAT_AIFF_C ||
148 options.format == FORMAT_RAW
151 if(options.format == FORMAT_RAW) {
152 decoder_session.is_big_endian = options.format_options.raw.is_big_endian;
153 decoder_session.is_unsigned_samples = options.format_options.raw.is_unsigned_samples;
157 DecoderSession_construct(
161 options.use_first_serial_number,
162 options.serial_number,
165 /*use_first_serial_number=*/false,
169 options.treat_warnings_as_errors,
170 options.continue_through_decode_errors,
171 options.channel_map_none,
172 options.replaygain_synthesis_spec,
175 &options.skip_specification,
176 &options.until_specification,
177 options.has_cue_specification? &options.cue_specification : 0,
178 options.format == FORMAT_RAW? NULL : options.format_options.iff.foreign_metadata,
185 if(!DecoderSession_init_decoder(&decoder_session, infilename))
186 return DecoderSession_finish_error(&decoder_session);
188 if(!DecoderSession_process(&decoder_session))
189 return DecoderSession_finish_error(&decoder_session);
191 return DecoderSession_finish_ok(&decoder_session);
194 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool use_first_serial_number, long serial_number, FileFormat format, FLAC__bool treat_warnings_as_errors, FLAC__bool continue_through_decode_errors, FLAC__bool channel_map_none, 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, foreign_metadata_t *foreign_metadata, const char *infilename, const char *outfilename)
198 d->use_first_serial_number = use_first_serial_number;
199 d->serial_number = serial_number;
202 (void)use_first_serial_number;
207 d->treat_warnings_as_errors = treat_warnings_as_errors;
208 d->continue_through_decode_errors = continue_through_decode_errors;
209 d->channel_map_none = channel_map_none;
210 d->replaygain.spec = replaygain_synthesis_spec;
211 d->replaygain.apply = false;
212 d->replaygain.scale = 0.0;
213 /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
214 d->test_only = (0 == outfilename);
215 d->analysis_mode = analysis_mode;
217 d->skip_specification = skip_specification;
218 d->until_specification = until_specification;
219 d->cue_specification = cue_specification;
221 d->inbasefilename = grabbag__file_get_basename(infilename);
222 d->infilename = infilename;
223 d->outfilename = outfilename;
225 d->samples_processed = 0;
226 d->frame_counter = 0;
227 d->abort_flag = false;
228 d->aborting_due_to_until = false;
229 d->aborting_due_to_unparseable = false;
231 d->iff_headers_need_fixup = false;
233 d->total_samples = 0;
234 d->got_stream_info = false;
235 d->has_md5sum = false;
241 d->decode_position = 0;
245 d->fout = 0; /* initialized with an open file later if necessary */
247 d->foreign_metadata = foreign_metadata;
249 FLAC__ASSERT(!(d->test_only && d->analysis_mode));
252 if(0 == strcmp(outfilename, "-")) {
253 d->fout = grabbag__file_get_binary_stdout();
256 if(0 == (d->fout = fopen(outfilename, "wb"))) {
257 flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
258 DecoderSession_destroy(d, /*error_occurred=*/true);
265 flac__analyze_init(aopts);
270 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
272 if(0 != d->fout && d->fout != stdout) {
275 unlink(d->outfilename);
279 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, const char *infilename)
281 FLAC__StreamDecoderInitStatus init_status;
282 FLAC__uint32 test = 1;
284 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
286 if(!decoder_session->analysis_mode && !decoder_session->test_only && decoder_session->foreign_metadata) {
288 if(!flac__foreign_metadata_read_from_flac(decoder_session->foreign_metadata, infilename, &error)) {
289 flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", decoder_session->inbasefilename, error);
294 decoder_session->decoder = FLAC__stream_decoder_new();
296 if(0 == decoder_session->decoder) {
297 flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
301 FLAC__stream_decoder_set_md5_checking(decoder_session->decoder, true);
302 if (0 != decoder_session->cue_specification)
303 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_CUESHEET);
304 if (decoder_session->replaygain.spec.apply)
305 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
308 if(decoder_session->is_ogg) {
309 if(!decoder_session->use_first_serial_number)
310 FLAC__stream_decoder_set_ogg_serial_number(decoder_session->decoder, decoder_session->serial_number);
311 init_status = FLAC__stream_decoder_init_ogg_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
316 init_status = FLAC__stream_decoder_init_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
319 if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
320 print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
327 FLAC__bool DecoderSession_process(DecoderSession *d)
329 if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder)) {
330 flac__utils_printf(stderr, 2, "\n");
331 print_error_with_state(d, "ERROR while decoding metadata");
334 if(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM) {
335 flac__utils_printf(stderr, 2, "\n");
336 print_error_with_state(d, "ERROR during metadata decoding");
337 if(!d->continue_through_decode_errors)
344 /* set channel mapping */
345 if(!d->channel_map_none) {
346 /* currently FLAC order matches SMPTE/WAVEFORMATEXTENSIBLE order, so no reordering is necessary; see encode.c */
347 /* only the channel mask must be set if it was not already picked up from the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag */
348 if(d->channels == 1) {
349 if(d->channel_mask == 0)
350 d->channel_mask = 0x0001;
352 else if(d->channels == 2) {
353 if(d->channel_mask == 0)
354 d->channel_mask = 0x0003;
356 else if(d->channels == 3) {
357 if(d->channel_mask == 0)
358 d->channel_mask = 0x0007;
360 else if(d->channels == 4) {
361 if(d->channel_mask == 0)
362 d->channel_mask = 0x0033;
364 else if(d->channels == 5) {
365 if(d->channel_mask == 0)
366 d->channel_mask = 0x0607;
368 else if(d->channels == 6) {
369 if(d->channel_mask == 0)
370 d->channel_mask = 0x060f;
374 /* write the WAVE/AIFF headers if necessary */
375 if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
376 if(!write_iff_headers(d->fout, d, d->total_samples)) {
377 d->abort_flag = true;
382 if(d->skip_specification->value.samples > 0) {
383 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
385 if(!FLAC__stream_decoder_seek_absolute(d->decoder, skip)) {
386 print_error_with_state(d, "ERROR seeking while skipping bytes");
390 if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder) && !d->aborting_due_to_until) {
391 flac__utils_printf(stderr, 2, "\n");
392 print_error_with_state(d, "ERROR while decoding data");
393 if(!d->continue_through_decode_errors)
397 (d->abort_flag && !(d->aborting_due_to_until || d->continue_through_decode_errors)) ||
398 (FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until)
400 flac__utils_printf(stderr, 2, "\n");
401 print_error_with_state(d, "ERROR during decoding");
405 if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW && ((d->total_samples * d->channels * ((d->bps+7)/8)) & 1)) {
406 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
407 print_error_with_state(d, d->format == FORMAT_WAVE || d->format == FORMAT_RF64?
408 "ERROR writing pad byte to WAVE data chunk" :
409 "ERROR writing pad byte to AIFF SSND chunk"
418 int DecoderSession_finish_ok(DecoderSession *d)
420 FLAC__bool ok = true, md5_failure = false;
423 md5_failure = !FLAC__stream_decoder_finish(d->decoder) && !d->aborting_due_to_until;
425 FLAC__stream_decoder_delete(d->decoder);
428 flac__analyze_finish(d->aopts);
430 flac__utils_printf(stderr, 1, "\r%s: ERROR, MD5 signature mismatch\n", d->inbasefilename);
431 ok = d->continue_through_decode_errors;
434 if(!d->got_stream_info) {
435 flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since there was no STREAMINFO\n", d->inbasefilename);
436 ok = !d->treat_warnings_as_errors;
438 else if(!d->has_md5sum) {
439 flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since it was unset in the STREAMINFO\n", d->inbasefilename);
440 ok = !d->treat_warnings_as_errors;
442 flac__utils_printf(stderr, 2, "\r%s: %s \n", d->inbasefilename, d->test_only? "ok ":d->analysis_mode?"done ":"done");
444 DecoderSession_destroy(d, /*error_occurred=*/!ok);
445 if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
446 if(d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))) {
447 if(!fixup_iff_headers(d))
450 if(d->foreign_metadata) {
452 if(!flac__foreign_metadata_write_to_iff(d->foreign_metadata, d->infilename, d->outfilename, d->fm_offset1, d->fm_offset2, d->fm_offset3, &error)) {
453 flac__utils_printf(stderr, 1, "ERROR updating foreign metadata from %s to %s: %s\n", d->infilename, d->outfilename, error);
461 int DecoderSession_finish_error(DecoderSession *d)
464 (void)FLAC__stream_decoder_finish(d->decoder);
465 FLAC__stream_decoder_delete(d->decoder);
468 flac__analyze_finish(d->aopts);
469 DecoderSession_destroy(d, /*error_occurred=*/true);
473 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
475 /* convert from mm:ss.sss to sample number if necessary */
476 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
478 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
479 if(spec->is_relative && spec->value.samples == 0) {
480 spec->is_relative = false;
484 /* in any other case the total samples in the input must be known */
485 if(total_samples_in_input == 0) {
486 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
490 FLAC__ASSERT(spec->value_is_samples);
492 /* convert relative specifications to absolute */
493 if(spec->is_relative) {
494 if(spec->value.samples <= 0)
495 spec->value.samples += (FLAC__int64)total_samples_in_input;
497 spec->value.samples += skip;
498 spec->is_relative = false;
502 if(spec->value.samples < 0) {
503 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
506 if((FLAC__uint64)spec->value.samples <= skip) {
507 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
510 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
511 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
518 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
520 const FileFormat format = decoder_session->format;
521 const char *fmt_desc = format==FORMAT_WAVE? "WAVE" : format==FORMAT_RF64? "RF64" : "AIFF";
522 const FLAC__bool is_wavish = format == FORMAT_WAVE || format == FORMAT_RF64;
523 const FLAC__bool is_waveformatextensible = is_wavish && (decoder_session->channel_mask == 2 || decoder_session->channel_mask > 3 || decoder_session->bps%8 || decoder_session->channels > 2);
524 const FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
525 const FLAC__uint64 aligned_data_size = data_size & 1? (data_size+1) : data_size;
527 FLAC__uint64 iff_size;
528 unsigned foreign_metadata_size = 0; /* size of all non-audio non-fmt/COMM foreign metadata chunks */
529 foreign_metadata_t *fm = decoder_session->foreign_metadata;
532 FLAC__ASSERT(flac__utils_format_is_iff(format));
536 flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
537 flac__utils_printf(stderr, 1, " Generated %s file will have a data chunk size of 0. Try\n", fmt_desc);
538 flac__utils_printf(stderr, 1, " decoding directly to a file instead.\n");
539 if(decoder_session->treat_warnings_as_errors)
543 decoder_session->iff_headers_need_fixup = true;
548 FLAC__ASSERT(fm->format_block);
549 FLAC__ASSERT(fm->audio_block);
550 FLAC__ASSERT(fm->format_block < fm->audio_block);
551 /* calc foreign metadata size; for RIFF/AIFF we always skip the first chunk, ds64 chunk, format chunk, and sound chunk since we write our own */
552 for(i = format==FORMAT_RF64?2:1; i < fm->num_blocks; i++) {
553 if(i != fm->format_block && i != fm->audio_block)
554 foreign_metadata_size += fm->blocks[i].size;
561 iff_size = (is_waveformatextensible?60:36) + (format==FORMAT_RF64?36:0) + foreign_metadata_size + aligned_data_size;
563 /* @@@@@@ can ssnd_offset_size be odd and hence screw up our alignment logic? */
564 iff_size = 46 + foreign_metadata_size + aligned_data_size + (fm? fm->ssnd_offset_size : 0);
566 if(format != FORMAT_RF64 && iff_size >= 0xFFFFFFF4) {
567 flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file\n", decoder_session->inbasefilename, fmt_desc);
572 if(format == FORMAT_RF64) {
573 if(flac__utils_fwrite("RF64", 1, 4, f) != 4)
576 if(!write_little_endian_uint32(f, 0xffffffff))
580 if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
583 if(!write_little_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
587 if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
590 if(format == FORMAT_RF64) {
591 if(flac__utils_fwrite("ds64", 1, 4, f) != 4)
594 if(!write_little_endian_uint32(f, 28)) /* chunk size */
597 if(!write_little_endian_uint64(f, iff_size))
600 if(!write_little_endian_uint64(f, data_size))
603 if(!write_little_endian_uint64(f, samples)) /*@@@@@@ correct? */
606 if(!write_little_endian_uint32(f, 0)) /* table size */
610 decoder_session->fm_offset1 = ftello(f);
613 /* seek forward to {allocate} or {skip over already-written chunks} before "fmt " */
614 for(i = format==FORMAT_RF64?2:1; i < fm->format_block; i++) {
615 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
616 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"fmt \"\n", decoder_session->inbasefilename);
622 if(!write_riff_wave_fmt_chunk(f, is_waveformatextensible, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate, decoder_session->channel_mask))
625 decoder_session->fm_offset2 = ftello(f);
628 /* seek forward to {allocate} or {skip over already-written chunks} after "fmt " but before "data" */
629 for(i = fm->format_block+1; i < fm->audio_block; i++) {
630 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
631 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"fmt \"\n", decoder_session->inbasefilename);
637 if(flac__utils_fwrite("data", 1, 4, f) != 4)
640 if(!write_little_endian_uint32(f, format==FORMAT_RF64? 0xffffffff : (FLAC__uint32)data_size))
643 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
646 FLAC__uint32 ssnd_offset_size = (fm? fm->ssnd_offset_size : 0);
648 if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
651 if(!write_big_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
654 if(flac__utils_fwrite("AIFF", 1, 4, f) != 4)
657 decoder_session->fm_offset1 = ftello(f);
660 /* seek forward to {allocate} or {skip over already-written chunks} before "COMM" */
661 for(i = 1; i < fm->format_block; i++) {
662 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
663 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"COMM\"\n", decoder_session->inbasefilename);
669 if(!write_aiff_form_comm_chunk(f, samples, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate))
672 decoder_session->fm_offset2 = ftello(f);
675 /* seek forward to {allocate} or {skip over already-written chunks} after "COMM" but before "SSND" */
676 for(i = fm->format_block+1; i < fm->audio_block; i++) {
677 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
678 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"COMM\"\n", decoder_session->inbasefilename);
684 if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
687 if(!write_big_endian_uint32(f, (FLAC__uint32)data_size + 8 + ssnd_offset_size)) /* data size */
690 if(!write_big_endian_uint32(f, ssnd_offset_size))
693 if(!write_big_endian_uint32(f, 0/*block_size*/))
696 if(ssnd_offset_size) {
697 /* seek forward to {allocate} or {skip over already-written} SSND offset */
698 if(fseeko(f, ssnd_offset_size, SEEK_CUR) < 0) {
699 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping \"SSND\" offset\n", decoder_session->inbasefilename);
704 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
710 FLAC__bool write_riff_wave_fmt_chunk(FILE *f, FLAC__bool is_waveformatextensible, unsigned bps, unsigned channels, unsigned sample_rate, FLAC__uint32 channel_mask)
712 if(flac__utils_fwrite("fmt ", 1, 4, f) != 4)
715 if(!write_little_endian_uint32(f, is_waveformatextensible? 40 : 16)) /* chunk size */
718 if(!write_little_endian_uint16(f, (FLAC__uint16)(is_waveformatextensible? 65534 : 1))) /* compression code */
721 if(!write_little_endian_uint16(f, (FLAC__uint16)channels))
724 if(!write_little_endian_uint32(f, sample_rate))
727 if(!write_little_endian_uint32(f, sample_rate * channels * ((bps+7) / 8)))
730 if(!write_little_endian_uint16(f, (FLAC__uint16)(channels * ((bps+7) / 8)))) /* block align */
733 if(!write_little_endian_uint16(f, (FLAC__uint16)(((bps+7)/8)*8))) /* bits per sample */
736 if(is_waveformatextensible) {
737 if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */
740 if(!write_little_endian_uint16(f, (FLAC__uint16)bps)) /* validBitsPerSample */
743 if(!write_little_endian_uint32(f, channel_mask))
746 /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */
747 if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16)
754 FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate)
756 FLAC__ASSERT(samples <= 0xffffffff);
758 if(flac__utils_fwrite("COMM", 1, 4, f) != 4)
761 if(!write_big_endian_uint32(f, 18)) /* chunk size = 18 */
764 if(!write_big_endian_uint16(f, (FLAC__uint16)channels))
767 if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
770 if(!write_big_endian_uint16(f, (FLAC__uint16)bps))
773 if(!write_sane_extended(f, sample_rate))
779 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
781 FLAC__byte *b = (FLAC__byte*)(&val);
782 if(is_big_endian_host_) {
784 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
786 return flac__utils_fwrite(b, 1, 2, f) == 2;
789 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
791 FLAC__byte *b = (FLAC__byte*)(&val);
792 if(is_big_endian_host_) {
794 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
795 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
797 return flac__utils_fwrite(b, 1, 4, f) == 4;
800 FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val)
802 FLAC__byte *b = (FLAC__byte*)(&val);
803 if(is_big_endian_host_) {
805 tmp = b[7]; b[7] = b[0]; b[0] = tmp;
806 tmp = b[6]; b[6] = b[1]; b[1] = tmp;
807 tmp = b[5]; b[5] = b[2]; b[2] = tmp;
808 tmp = b[4]; b[4] = b[3]; b[3] = tmp;
810 return flac__utils_fwrite(b, 1, 8, f) == 8;
813 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
815 FLAC__byte *b = (FLAC__byte*)(&val);
816 if(!is_big_endian_host_) {
818 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
820 return flac__utils_fwrite(b, 1, 2, f) == 2;
823 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
825 FLAC__byte *b = (FLAC__byte*)(&val);
826 if(!is_big_endian_host_) {
828 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
829 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
831 return flac__utils_fwrite(b, 1, 4, f) == 4;
834 FLAC__bool write_sane_extended(FILE *f, unsigned val)
835 /* Write to 'f' a SANE extended representation of 'val'. Return false if
836 * the write succeeds; return true otherwise.
838 * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
839 * of exponent, and 64 bits of significand (mantissa). Unlike most IEEE-754
840 * representations, it does not imply a 1 above the MSB of the significand.
846 unsigned int shift, exponent;
848 FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
850 for(shift= 0U; (val>>(31-shift))==0U; ++shift)
853 exponent= 63U-(shift+32U); /* add 32 for unused second word */
855 if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
857 if(!write_big_endian_uint32(f, val))
859 if(!write_big_endian_uint32(f, 0)) /* unused second word */
865 FLAC__bool fixup_iff_headers(DecoderSession *d)
867 const char *fmt_desc = d->format==FORMAT_WAVE? "WAVE" : d->format==FORMAT_RF64? "RF64" : "AIFF";
868 FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
871 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));
875 if(!write_iff_headers(f, d, d->samples_processed)) {
884 FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
886 DecoderSession *decoder_session = (DecoderSession*)client_data;
887 FILE *fout = decoder_session->fout;
888 const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
889 const unsigned shift = (decoder_session->format != FORMAT_RAW && (bps%8)? 8-(bps%8): 0);
890 FLAC__bool is_big_endian = (
891 decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? true : (
892 decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_RF64 ? false :
893 decoder_session->is_big_endian
895 FLAC__bool is_unsigned_samples = (
896 decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? false : (
897 decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_RF64 ? bps<=8 :
898 decoder_session->is_unsigned_samples
900 unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
901 unsigned frame_bytes = 0;
902 static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
903 FLAC__uint8 *u8buffer = (FLAC__uint8 *)s8buffer;
904 FLAC__int16 *s16buffer = (FLAC__int16 *)s8buffer;
905 FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
906 FLAC__int32 *s32buffer = (FLAC__int32 *)s8buffer;
907 FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
908 size_t bytes_to_write = 0;
912 if(decoder_session->abort_flag)
913 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
915 /* sanity-check the bits-per-sample */
916 if(decoder_session->bps) {
917 if(bps != decoder_session->bps) {
918 if(decoder_session->got_stream_info)
919 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);
921 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);
922 if(!decoder_session->continue_through_decode_errors)
923 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
927 /* must not have gotten STREAMINFO, save the bps from the frame header */
928 FLAC__ASSERT(!decoder_session->got_stream_info);
929 decoder_session->bps = bps;
932 /* sanity-check the #channels */
933 if(decoder_session->channels) {
934 if(channels != decoder_session->channels) {
935 if(decoder_session->got_stream_info)
936 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
938 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);
939 if(!decoder_session->continue_through_decode_errors)
940 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
944 /* must not have gotten STREAMINFO, save the #channels from the frame header */
945 FLAC__ASSERT(!decoder_session->got_stream_info);
946 decoder_session->channels = channels;
949 /* sanity-check the sample rate */
950 if(decoder_session->sample_rate) {
951 if(frame->header.sample_rate != decoder_session->sample_rate) {
952 if(decoder_session->got_stream_info)
953 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);
955 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);
956 if(!decoder_session->continue_through_decode_errors)
957 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
961 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
962 FLAC__ASSERT(!decoder_session->got_stream_info);
963 decoder_session->sample_rate = frame->header.sample_rate;
967 * limit the number of samples to accept based on --until
969 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
970 /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
971 if(decoder_session->skip_specification->is_relative) {
972 if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
973 decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
975 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);
976 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
979 if(decoder_session->until_specification->is_relative) {
980 if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
981 decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
983 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);
984 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
987 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
988 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
989 if(decoder_session->until_specification->value.samples > 0) {
990 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
991 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
992 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
993 FLAC__ASSERT(until >= input_samples_passed);
994 if(input_samples_passed + wide_samples > until)
995 wide_samples = (unsigned)(until - input_samples_passed);
996 if (wide_samples == 0) {
997 decoder_session->abort_flag = true;
998 decoder_session->aborting_due_to_until = true;
999 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1003 if(decoder_session->analysis_mode) {
1005 FLAC__stream_decoder_get_decode_position(decoder_session->decoder, &dpos);
1006 frame_bytes = (unsigned)(dpos-decoder_session->decode_position);
1007 decoder_session->decode_position = dpos;
1010 if(wide_samples > 0) {
1011 decoder_session->samples_processed += wide_samples;
1012 decoder_session->frame_counter++;
1014 if(!(decoder_session->frame_counter & 0x3f))
1015 print_stats(decoder_session);
1017 if(decoder_session->analysis_mode) {
1018 flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->decode_position-frame_bytes, frame_bytes, decoder_session->aopts, fout);
1020 else if(!decoder_session->test_only) {
1021 if(shift && !decoder_session->replaygain.apply) {
1022 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1023 for(channel = 0; channel < channels; channel++)
1024 ((FLAC__int32**)buffer)[channel][wide_sample] <<= shift;/*@@@@@@un-const'ing the buffer is hacky but safe*/
1026 if(decoder_session->replaygain.apply) {
1027 bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
1030 is_unsigned_samples,
1034 bps, /* source_bps */
1035 bps+shift, /* target_bps */
1036 decoder_session->replaygain.scale,
1037 decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
1038 decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
1039 &decoder_session->replaygain.dither_context
1042 /* first some special code for common cases */
1043 else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 2 && bps+shift == 16) {
1044 FLAC__int16 *buf1_ = s16buffer + 1;
1046 memcpy(s16buffer, ((FLAC__byte*)(buffer[0]))+2, sizeof(FLAC__int32) * wide_samples - 2);
1048 memcpy(s16buffer, buffer[0], sizeof(FLAC__int32) * wide_samples);
1049 for(sample = 0; sample < wide_samples; sample++, buf1_+=2)
1050 *buf1_ = (FLAC__int16)buffer[1][sample];
1051 bytes_to_write = 4 * sample;
1053 else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 1 && bps+shift == 16) {
1054 FLAC__int16 *buf1_ = s16buffer;
1055 for(sample = 0; sample < wide_samples; sample++)
1056 *buf1_++ = (FLAC__int16)buffer[0][sample];
1057 bytes_to_write = 2 * sample;
1059 /* generic code for the rest */
1060 else if(bps+shift == 16) {
1061 if(is_unsigned_samples) {
1063 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1064 u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1065 u16buffer[sample++] = (FLAC__uint16)(buffer[1][wide_sample] + 0x8000);
1068 else if(channels == 1) {
1069 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1070 u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1072 else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1073 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1074 for(channel = 0; channel < channels; channel++, sample++)
1075 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
1080 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1081 s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1082 s16buffer[sample++] = (FLAC__int16)(buffer[1][wide_sample]);
1085 else if(channels == 1) {
1086 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1087 s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1089 else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1090 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1091 for(channel = 0; channel < channels; channel++, sample++)
1092 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
1095 if(is_big_endian != is_big_endian_host_) {
1097 const unsigned bytes = sample * 2;
1098 for(byte = 0; byte < bytes; byte += 2) {
1099 tmp = u8buffer[byte];
1100 u8buffer[byte] = u8buffer[byte+1];
1101 u8buffer[byte+1] = tmp;
1104 bytes_to_write = 2 * sample;
1106 else if(bps+shift == 24) {
1107 if(is_unsigned_samples) {
1108 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1109 for(channel = 0; channel < channels; channel++, sample++)
1110 u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
1113 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1114 for(channel = 0; channel < channels; channel++, sample++)
1115 s32buffer[sample] = buffer[channel][wide_sample];
1117 if(is_big_endian != is_big_endian_host_) {
1119 const unsigned bytes = sample * 4;
1120 for(byte = 0; byte < bytes; byte += 4) {
1121 tmp = u8buffer[byte];
1122 u8buffer[byte] = u8buffer[byte+3];
1123 u8buffer[byte+3] = tmp;
1124 tmp = u8buffer[byte+1];
1125 u8buffer[byte+1] = u8buffer[byte+2];
1126 u8buffer[byte+2] = tmp;
1131 const unsigned bytes = sample * 4;
1132 for(lbyte = byte = 0; byte < bytes; ) {
1134 u8buffer[lbyte++] = u8buffer[byte++];
1135 u8buffer[lbyte++] = u8buffer[byte++];
1136 u8buffer[lbyte++] = u8buffer[byte++];
1141 const unsigned bytes = sample * 4;
1142 for(lbyte = byte = 0; byte < bytes; ) {
1143 u8buffer[lbyte++] = u8buffer[byte++];
1144 u8buffer[lbyte++] = u8buffer[byte++];
1145 u8buffer[lbyte++] = u8buffer[byte++];
1149 bytes_to_write = 3 * sample;
1151 else if(bps+shift == 8) {
1152 if(is_unsigned_samples) {
1153 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1154 for(channel = 0; channel < channels; channel++, sample++)
1155 u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
1158 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1159 for(channel = 0; channel < channels; channel++, sample++)
1160 s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
1162 bytes_to_write = sample;
1166 /* double protection */
1167 decoder_session->abort_flag = true;
1168 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1172 if(bytes_to_write > 0) {
1173 if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
1174 /* if a pipe closed when writing to stdout, we let it go without an error message */
1175 if(errno == EPIPE && decoder_session->fout == stdout)
1176 decoder_session->aborting_due_to_until = true;
1177 decoder_session->abort_flag = true;
1178 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1181 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1184 void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1186 DecoderSession *decoder_session = (DecoderSession*)client_data;
1188 if(decoder_session->analysis_mode)
1189 FLAC__stream_decoder_get_decode_position(decoder, &decoder_session->decode_position);
1191 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
1192 FLAC__uint64 skip, until;
1193 decoder_session->got_stream_info = true;
1194 decoder_session->has_md5sum = memcmp(metadata->data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16);
1195 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1196 decoder_session->channels = metadata->data.stream_info.channels;
1197 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1199 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
1200 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1201 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1203 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1204 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1205 flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1206 decoder_session->abort_flag = true;
1209 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1210 flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1211 decoder_session->abort_flag = true;
1214 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1215 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1217 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1218 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1219 decoder_session->abort_flag = true;
1222 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1223 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1226 FLAC__ASSERT(decoder_session->total_samples != 0);
1227 FLAC__ASSERT(0 == decoder_session->cue_specification);
1228 decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1231 if(decoder_session->bps < 4 || decoder_session->bps > 24) {
1232 flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 4-24\n", decoder_session->inbasefilename, decoder_session->bps);
1233 decoder_session->abort_flag = true;
1237 else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1238 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1239 if(decoder_session->total_samples == 0) {
1240 flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1241 decoder_session->abort_flag = true;
1245 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);
1247 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1248 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1250 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1251 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1253 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1254 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1255 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1256 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1258 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1260 else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1261 if (decoder_session->replaygain.spec.apply) {
1262 double reference, gain, peak;
1263 if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
1264 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");
1265 if(decoder_session->treat_warnings_as_errors) {
1266 decoder_session->abort_flag = true;
1271 const char *ls[] = { "no", "peak", "hard" };
1272 const char *ns[] = { "no", "low", "medium", "high" };
1273 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1274 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1275 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1276 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]);
1277 flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1278 /* don't check if(decoder_session->treat_warnings_as_errors) because the user explicitly asked for it */
1281 (void)flac__utils_get_channel_mask_tag(metadata, &decoder_session->channel_mask);
1285 void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1287 DecoderSession *decoder_session = (DecoderSession*)client_data;
1289 flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1290 if(!decoder_session->continue_through_decode_errors) {
1291 decoder_session->abort_flag = true;
1292 if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1293 decoder_session->aborting_due_to_unparseable = true;
1297 void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
1299 const int ilen = strlen(d->inbasefilename) + 1;
1301 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1303 flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
1305 /* print out some more info for some errors: */
1306 if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
1307 flac__utils_printf(stderr, 1,
1309 "An error occurred opening the input file; it is likely that it does not exist\n"
1310 "or is not readable.\n"
1315 void print_error_with_state(const DecoderSession *d, const char *message)
1317 const int ilen = strlen(d->inbasefilename) + 1;
1319 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1320 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", FLAC__stream_decoder_get_resolved_state_string(d->decoder));
1322 /* print out some more info for some errors: */
1323 if (d->aborting_due_to_unparseable) {
1324 flac__utils_printf(stderr, 1,
1326 "The FLAC stream may have been created by a more advanced encoder. Try\n"
1327 " metaflac --show-vendor-tag %s\n"
1328 "If the version number is greater than %s, this decoder is probably\n"
1329 "not able to decode the file. If the version number is not, the file\n"
1330 "may be corrupted, or you may have found a bug. In this case please\n"
1331 "submit a bug report to\n"
1332 " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
1333 "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1334 d->inbasefilename, FLAC__VERSION_STRING
1339 void print_stats(const DecoderSession *decoder_session)
1341 if(flac__utils_verbosity_ >= 2) {
1342 #if defined _MSC_VER || defined __MINGW32__
1343 /* with MSVC you have to spoon feed it the casting */
1344 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1346 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1348 if(decoder_session->total_samples > 0) {
1349 fprintf(stderr, "\r%s: %s%u%% complete",
1350 decoder_session->inbasefilename,
1351 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1352 (unsigned)floor(progress + 0.5)
1356 fprintf(stderr, "\r%s: %s %u samples",
1357 decoder_session->inbasefilename,
1358 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1359 (unsigned)decoder_session->samples_processed