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_body(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_WAVE64 ||
146 options.format == FORMAT_RF64 ||
147 options.format == FORMAT_AIFF ||
148 options.format == FORMAT_AIFF_C ||
149 options.format == FORMAT_RAW
152 if(options.format == FORMAT_RAW) {
153 decoder_session.is_big_endian = options.format_options.raw.is_big_endian;
154 decoder_session.is_unsigned_samples = options.format_options.raw.is_unsigned_samples;
158 DecoderSession_construct(
162 options.use_first_serial_number,
163 options.serial_number,
166 /*use_first_serial_number=*/false,
170 options.treat_warnings_as_errors,
171 options.continue_through_decode_errors,
172 options.channel_map_none,
173 options.replaygain_synthesis_spec,
176 &options.skip_specification,
177 &options.until_specification,
178 options.has_cue_specification? &options.cue_specification : 0,
179 options.format == FORMAT_RAW? NULL : options.format_options.iff.foreign_metadata,
186 if(!DecoderSession_init_decoder(&decoder_session, infilename))
187 return DecoderSession_finish_error(&decoder_session);
189 if(!DecoderSession_process(&decoder_session))
190 return DecoderSession_finish_error(&decoder_session);
192 return DecoderSession_finish_ok(&decoder_session);
195 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)
199 d->use_first_serial_number = use_first_serial_number;
200 d->serial_number = serial_number;
203 (void)use_first_serial_number;
208 d->treat_warnings_as_errors = treat_warnings_as_errors;
209 d->continue_through_decode_errors = continue_through_decode_errors;
210 d->channel_map_none = channel_map_none;
211 d->replaygain.spec = replaygain_synthesis_spec;
212 d->replaygain.apply = false;
213 d->replaygain.scale = 0.0;
214 /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
215 d->test_only = (0 == outfilename);
216 d->analysis_mode = analysis_mode;
218 d->skip_specification = skip_specification;
219 d->until_specification = until_specification;
220 d->cue_specification = cue_specification;
222 d->inbasefilename = grabbag__file_get_basename(infilename);
223 d->infilename = infilename;
224 d->outfilename = outfilename;
226 d->samples_processed = 0;
227 d->frame_counter = 0;
228 d->abort_flag = false;
229 d->aborting_due_to_until = false;
230 d->aborting_due_to_unparseable = false;
232 d->iff_headers_need_fixup = false;
234 d->total_samples = 0;
235 d->got_stream_info = false;
236 d->has_md5sum = false;
242 d->decode_position = 0;
246 d->fout = 0; /* initialized with an open file later if necessary */
248 d->foreign_metadata = foreign_metadata;
250 FLAC__ASSERT(!(d->test_only && d->analysis_mode));
253 if(0 == strcmp(outfilename, "-")) {
254 d->fout = grabbag__file_get_binary_stdout();
257 if(0 == (d->fout = fopen(outfilename, "wb"))) {
258 flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
259 DecoderSession_destroy(d, /*error_occurred=*/true);
266 flac__analyze_init(aopts);
271 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
273 if(0 != d->fout && d->fout != stdout) {
276 unlink(d->outfilename);
280 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, const char *infilename)
282 FLAC__StreamDecoderInitStatus init_status;
283 FLAC__uint32 test = 1;
285 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
287 if(!decoder_session->analysis_mode && !decoder_session->test_only && decoder_session->foreign_metadata) {
289 if(!flac__foreign_metadata_read_from_flac(decoder_session->foreign_metadata, infilename, &error)) {
290 flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", decoder_session->inbasefilename, error);
295 decoder_session->decoder = FLAC__stream_decoder_new();
297 if(0 == decoder_session->decoder) {
298 flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
302 FLAC__stream_decoder_set_md5_checking(decoder_session->decoder, true);
303 if (0 != decoder_session->cue_specification)
304 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_CUESHEET);
305 if (decoder_session->replaygain.spec.apply)
306 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
309 if(decoder_session->is_ogg) {
310 if(!decoder_session->use_first_serial_number)
311 FLAC__stream_decoder_set_ogg_serial_number(decoder_session->decoder, decoder_session->serial_number);
312 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);
317 init_status = FLAC__stream_decoder_init_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
320 if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
321 print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
328 FLAC__bool DecoderSession_process(DecoderSession *d)
330 if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder)) {
331 flac__utils_printf(stderr, 2, "\n");
332 print_error_with_state(d, "ERROR while decoding metadata");
335 if(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM) {
336 flac__utils_printf(stderr, 2, "\n");
337 print_error_with_state(d, "ERROR during metadata decoding");
338 if(!d->continue_through_decode_errors)
345 /* set channel mapping */
346 if(!d->channel_map_none) {
347 /* currently FLAC order matches SMPTE/WAVEFORMATEXTENSIBLE order, so no reordering is necessary; see encode.c */
348 /* only the channel mask must be set if it was not already picked up from the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag */
349 if(d->channels == 1) {
350 if(d->channel_mask == 0)
351 d->channel_mask = 0x0001;
353 else if(d->channels == 2) {
354 if(d->channel_mask == 0)
355 d->channel_mask = 0x0003;
357 else if(d->channels == 3) {
358 if(d->channel_mask == 0)
359 d->channel_mask = 0x0007;
361 else if(d->channels == 4) {
362 if(d->channel_mask == 0)
363 d->channel_mask = 0x0033;
365 else if(d->channels == 5) {
366 if(d->channel_mask == 0)
367 d->channel_mask = 0x0607;
369 else if(d->channels == 6) {
370 if(d->channel_mask == 0)
371 d->channel_mask = 0x060f;
375 /* write the WAVE/AIFF headers if necessary */
376 if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
377 if(!write_iff_headers(d->fout, d, d->total_samples)) {
378 d->abort_flag = true;
383 if(d->skip_specification->value.samples > 0) {
384 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
386 if(!FLAC__stream_decoder_seek_absolute(d->decoder, skip)) {
387 print_error_with_state(d, "ERROR seeking while skipping bytes");
391 if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder) && !d->aborting_due_to_until) {
392 flac__utils_printf(stderr, 2, "\n");
393 print_error_with_state(d, "ERROR while decoding data");
394 if(!d->continue_through_decode_errors)
398 (d->abort_flag && !(d->aborting_due_to_until || d->continue_through_decode_errors)) ||
399 (FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until)
401 flac__utils_printf(stderr, 2, "\n");
402 print_error_with_state(d, "ERROR during decoding");
406 /* write padding bytes for alignment if necessary */
407 if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
408 const FLAC__uint64 data_size = d->total_samples * d->channels * ((d->bps+7)/8);
410 if(d->format != FORMAT_WAVE64) {
411 padding = (unsigned)(data_size & 1);
414 /* 8-byte alignment for Wave64 */
415 padding = (8 - (unsigned)(data_size & 7)) & 7;
417 for( ; padding > 0; --padding) {
418 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
419 print_error_with_state(
421 d->format == FORMAT_WAVE? "ERROR writing pad byte to WAVE data chunk" :
422 d->format == FORMAT_WAVE64? "ERROR writing pad bytes to WAVE64 data chunk" :
423 d->format == FORMAT_RF64? "ERROR writing pad byte to RF64 data chunk" :
424 "ERROR writing pad byte to AIFF SSND chunk"
434 int DecoderSession_finish_ok(DecoderSession *d)
436 FLAC__bool ok = true, md5_failure = false;
439 md5_failure = !FLAC__stream_decoder_finish(d->decoder) && !d->aborting_due_to_until;
441 FLAC__stream_decoder_delete(d->decoder);
444 flac__analyze_finish(d->aopts);
446 flac__utils_printf(stderr, 1, "\r%s: ERROR, MD5 signature mismatch\n", d->inbasefilename);
447 ok = d->continue_through_decode_errors;
450 if(!d->got_stream_info) {
451 flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since there was no STREAMINFO\n", d->inbasefilename);
452 ok = !d->treat_warnings_as_errors;
454 else if(!d->has_md5sum) {
455 flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since it was unset in the STREAMINFO\n", d->inbasefilename);
456 ok = !d->treat_warnings_as_errors;
458 flac__utils_printf(stderr, 2, "\r%s: %s \n", d->inbasefilename, d->test_only? "ok ":d->analysis_mode?"done ":"done");
460 DecoderSession_destroy(d, /*error_occurred=*/!ok);
461 if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
462 if(d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))) {
463 if(!fixup_iff_headers(d))
466 if(d->foreign_metadata) {
468 if(!flac__foreign_metadata_write_to_iff(d->foreign_metadata, d->infilename, d->outfilename, d->fm_offset1, d->fm_offset2, d->fm_offset3, &error)) {
469 flac__utils_printf(stderr, 1, "ERROR updating foreign metadata from %s to %s: %s\n", d->infilename, d->outfilename, error);
477 int DecoderSession_finish_error(DecoderSession *d)
480 (void)FLAC__stream_decoder_finish(d->decoder);
481 FLAC__stream_decoder_delete(d->decoder);
484 flac__analyze_finish(d->aopts);
485 DecoderSession_destroy(d, /*error_occurred=*/true);
489 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
491 /* convert from mm:ss.sss to sample number if necessary */
492 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
494 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
495 if(spec->is_relative && spec->value.samples == 0) {
496 spec->is_relative = false;
500 /* in any other case the total samples in the input must be known */
501 if(total_samples_in_input == 0) {
502 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
506 FLAC__ASSERT(spec->value_is_samples);
508 /* convert relative specifications to absolute */
509 if(spec->is_relative) {
510 if(spec->value.samples <= 0)
511 spec->value.samples += (FLAC__int64)total_samples_in_input;
513 spec->value.samples += skip;
514 spec->is_relative = false;
518 if(spec->value.samples < 0) {
519 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
522 if((FLAC__uint64)spec->value.samples <= skip) {
523 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
526 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
527 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
534 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
536 const FileFormat format = decoder_session->format;
537 const char *fmt_desc =
538 format==FORMAT_WAVE? "WAVE" :
539 format==FORMAT_WAVE64? "Wave64" :
540 format==FORMAT_RF64? "RF64" :
542 const FLAC__bool is_waveformatextensible =
543 (format == FORMAT_WAVE || format == FORMAT_WAVE64 || format == FORMAT_RF64) &&
545 decoder_session->channel_mask == 2 ||
546 decoder_session->channel_mask > 3 ||
547 decoder_session->bps%8 ||
548 decoder_session->channels > 2
550 const FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
551 const FLAC__uint64 aligned_data_size =
552 format == FORMAT_WAVE64?
553 (data_size+7) & (~(FLAC__uint64)7) :
554 (data_size+1) & (~(FLAC__uint64)1);
556 FLAC__uint64 iff_size;
557 unsigned foreign_metadata_size = 0; /* size of all non-audio non-fmt/COMM foreign metadata chunks */
558 foreign_metadata_t *fm = decoder_session->foreign_metadata;
562 format == FORMAT_WAVE ||
563 format == FORMAT_WAVE64 ||
564 format == FORMAT_RF64 ||
565 format == FORMAT_AIFF ||
566 format == FORMAT_AIFF_C
571 flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
572 flac__utils_printf(stderr, 1, " Generated %s file will have a data chunk size of 0. Try\n", fmt_desc);
573 flac__utils_printf(stderr, 1, " decoding directly to a file instead.\n");
574 if(decoder_session->treat_warnings_as_errors)
578 decoder_session->iff_headers_need_fixup = true;
583 FLAC__ASSERT(fm->format_block);
584 FLAC__ASSERT(fm->audio_block);
585 FLAC__ASSERT(fm->format_block < fm->audio_block);
586 /* calc foreign metadata size; we always skip the first chunk, ds64 chunk, format chunk, and sound chunk since we write our own */
587 for(i = format==FORMAT_RF64?2:1; i < fm->num_blocks; i++) {
588 if(i != fm->format_block && i != fm->audio_block)
589 foreign_metadata_size += fm->blocks[i].size;
595 else if(format == FORMAT_WAVE || format == FORMAT_RF64)
596 /* 4 for WAVE form bytes */
597 /* +{36,0} for ds64 chunk */
598 /* +8+{40,16} for fmt chunk header and body */
599 /* +8 for data chunk header */
600 iff_size = 4 + (format==FORMAT_RF64?36:0) + 8+(is_waveformatextensible?40:16) + 8 + foreign_metadata_size + aligned_data_size;
601 else if(format == FORMAT_WAVE64)
602 /* 16+8 for RIFF GUID and size field */
603 /* +16 for WAVE GUID */
604 /* +16+8+{40,16} for fmt chunk header (GUID and size field) and body */
605 /* +16+8 for data chunk header (GUID and size field) */
606 iff_size = 16+8 + 16 + 16+8+(is_waveformatextensible?40:16) + 16+8 + foreign_metadata_size + aligned_data_size;
608 iff_size = 46 + foreign_metadata_size + aligned_data_size;
610 if(format != FORMAT_WAVE64 && format != FORMAT_RF64 && iff_size >= 0xFFFFFFF4) {
611 flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file\n", decoder_session->inbasefilename, fmt_desc);
615 if(format == FORMAT_WAVE || format == FORMAT_WAVE64 || format == FORMAT_RF64) {
619 if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
621 if(!write_little_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
623 if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
627 /* RIFF GUID 66666972-912E-11CF-A5D6-28DB04C10000 */
628 if(flac__utils_fwrite("\x72\x69\x66\x66\x2E\x91\xCF\x11\xD6\xA5\x28\xDB\x04\xC1\x00\x00", 1, 16, f) != 16)
630 if(!write_little_endian_uint64(f, iff_size))
632 /* WAVE GUID 65766177-ACF3-11D3-8CD1-00C04F8EDB8A */
633 if(flac__utils_fwrite("\x77\x61\x76\x65\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
637 if(flac__utils_fwrite("RF64", 1, 4, f) != 4)
639 if(!write_little_endian_uint32(f, 0xffffffff))
641 if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
648 /* ds64 chunk for RF64 */
649 if(format == FORMAT_RF64) {
650 if(flac__utils_fwrite("ds64", 1, 4, f) != 4)
653 if(!write_little_endian_uint32(f, 28)) /* chunk size */
656 if(!write_little_endian_uint64(f, iff_size))
659 if(!write_little_endian_uint64(f, data_size))
662 if(!write_little_endian_uint64(f, samples)) /*@@@@@@ correct? */
665 if(!write_little_endian_uint32(f, 0)) /* table size */
669 decoder_session->fm_offset1 = ftello(f);
672 /* seek forward to {allocate} or {skip over already-written chunks} before "fmt " */
673 for(i = format==FORMAT_RF64?2:1; i < fm->format_block; i++) {
674 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
675 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"fmt \"\n", decoder_session->inbasefilename);
681 if(format != FORMAT_WAVE64) {
682 if(flac__utils_fwrite("fmt ", 1, 4, f) != 4)
684 if(!write_little_endian_uint32(f, is_waveformatextensible? 40 : 16)) /* chunk size */
688 /* fmt GUID 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A */
689 if(flac__utils_fwrite("\x66\x6D\x74\x20\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
691 /* chunk size (+16+8 for GUID and size fields) */
692 if(!write_little_endian_uint64(f, 16+8+(is_waveformatextensible?40:16)))
696 if(!write_riff_wave_fmt_chunk_body(f, is_waveformatextensible, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate, decoder_session->channel_mask))
699 decoder_session->fm_offset2 = ftello(f);
702 /* seek forward to {allocate} or {skip over already-written chunks} after "fmt " but before "data" */
703 for(i = fm->format_block+1; i < fm->audio_block; i++) {
704 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
705 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"fmt \"\n", decoder_session->inbasefilename);
711 if(format != FORMAT_WAVE64) {
712 if(flac__utils_fwrite("data", 1, 4, f) != 4)
714 if(!write_little_endian_uint32(f, format==FORMAT_RF64? 0xffffffff : (FLAC__uint32)data_size))
718 /* data GUID 61746164-ACF3-11D3-8CD1-00C04F8EDB8A */
719 if(flac__utils_fwrite("\x64\x61\x74\x61\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
721 /* +16+8 for GUID and size fields */
722 if(!write_little_endian_uint64(f, 16+8 + data_size))
726 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
729 if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
732 if(!write_big_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
735 if(flac__utils_fwrite("AIFF", 1, 4, f) != 4)
738 decoder_session->fm_offset1 = ftello(f);
741 /* seek forward to {allocate} or {skip over already-written chunks} before "COMM" */
742 for(i = 1; i < fm->format_block; i++) {
743 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
744 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"COMM\"\n", decoder_session->inbasefilename);
750 if(!write_aiff_form_comm_chunk(f, samples, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate))
753 decoder_session->fm_offset2 = ftello(f);
756 /* seek forward to {allocate} or {skip over already-written chunks} after "COMM" but before "SSND" */
757 for(i = fm->format_block+1; i < fm->audio_block; i++) {
758 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
759 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"COMM\"\n", decoder_session->inbasefilename);
765 if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
768 if(!write_big_endian_uint32(f, (FLAC__uint32)data_size + 8)) /* data size */
771 if(!write_big_endian_uint32(f, 0/*offset_size*/))
774 if(!write_big_endian_uint32(f, 0/*block_size*/))
777 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
783 FLAC__bool write_riff_wave_fmt_chunk_body(FILE *f, FLAC__bool is_waveformatextensible, unsigned bps, unsigned channels, unsigned sample_rate, FLAC__uint32 channel_mask)
785 if(!write_little_endian_uint16(f, (FLAC__uint16)(is_waveformatextensible? 65534 : 1))) /* compression code */
788 if(!write_little_endian_uint16(f, (FLAC__uint16)channels))
791 if(!write_little_endian_uint32(f, sample_rate))
794 if(!write_little_endian_uint32(f, sample_rate * channels * ((bps+7) / 8)))
797 if(!write_little_endian_uint16(f, (FLAC__uint16)(channels * ((bps+7) / 8)))) /* block align */
800 if(!write_little_endian_uint16(f, (FLAC__uint16)(((bps+7)/8)*8))) /* bits per sample */
803 if(is_waveformatextensible) {
804 if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */
807 if(!write_little_endian_uint16(f, (FLAC__uint16)bps)) /* validBitsPerSample */
810 if(!write_little_endian_uint32(f, channel_mask))
813 /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */
814 if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16)
821 FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate)
823 FLAC__ASSERT(samples <= 0xffffffff);
825 if(flac__utils_fwrite("COMM", 1, 4, f) != 4)
828 if(!write_big_endian_uint32(f, 18)) /* chunk size = 18 */
831 if(!write_big_endian_uint16(f, (FLAC__uint16)channels))
834 if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
837 if(!write_big_endian_uint16(f, (FLAC__uint16)bps))
840 if(!write_sane_extended(f, sample_rate))
846 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
848 FLAC__byte *b = (FLAC__byte*)(&val);
849 if(is_big_endian_host_) {
851 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
853 return flac__utils_fwrite(b, 1, 2, f) == 2;
856 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
858 FLAC__byte *b = (FLAC__byte*)(&val);
859 if(is_big_endian_host_) {
861 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
862 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
864 return flac__utils_fwrite(b, 1, 4, f) == 4;
867 FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val)
869 FLAC__byte *b = (FLAC__byte*)(&val);
870 if(is_big_endian_host_) {
872 tmp = b[7]; b[7] = b[0]; b[0] = tmp;
873 tmp = b[6]; b[6] = b[1]; b[1] = tmp;
874 tmp = b[5]; b[5] = b[2]; b[2] = tmp;
875 tmp = b[4]; b[4] = b[3]; b[3] = tmp;
877 return flac__utils_fwrite(b, 1, 8, f) == 8;
880 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
882 FLAC__byte *b = (FLAC__byte*)(&val);
883 if(!is_big_endian_host_) {
885 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
887 return flac__utils_fwrite(b, 1, 2, f) == 2;
890 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
892 FLAC__byte *b = (FLAC__byte*)(&val);
893 if(!is_big_endian_host_) {
895 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
896 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
898 return flac__utils_fwrite(b, 1, 4, f) == 4;
901 FLAC__bool write_sane_extended(FILE *f, unsigned val)
902 /* Write to 'f' a SANE extended representation of 'val'. Return false if
903 * the write succeeds; return true otherwise.
905 * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
906 * of exponent, and 64 bits of significand (mantissa). Unlike most IEEE-754
907 * representations, it does not imply a 1 above the MSB of the significand.
913 unsigned int shift, exponent;
915 FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
917 for(shift= 0U; (val>>(31-shift))==0U; ++shift)
920 exponent= 63U-(shift+32U); /* add 32 for unused second word */
922 if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
924 if(!write_big_endian_uint32(f, val))
926 if(!write_big_endian_uint32(f, 0)) /* unused second word */
932 FLAC__bool fixup_iff_headers(DecoderSession *d)
934 const char *fmt_desc =
935 d->format==FORMAT_WAVE? "WAVE" :
936 d->format==FORMAT_WAVE64? "Wave64" :
937 d->format==FORMAT_RF64? "RF64" :
939 FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
942 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));
946 if(!write_iff_headers(f, d, d->samples_processed)) {
955 FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
957 DecoderSession *decoder_session = (DecoderSession*)client_data;
958 FILE *fout = decoder_session->fout;
959 const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
960 const unsigned shift = (decoder_session->format != FORMAT_RAW && (bps%8))? 8-(bps%8): 0;
961 FLAC__bool is_big_endian = (
962 decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? true : (
963 decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 ? false :
964 decoder_session->is_big_endian
966 FLAC__bool is_unsigned_samples = (
967 decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? false : (
968 decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 ? bps<=8 :
969 decoder_session->is_unsigned_samples
971 unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
972 unsigned frame_bytes = 0;
973 static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
974 FLAC__uint8 *u8buffer = (FLAC__uint8 *)s8buffer;
975 FLAC__int16 *s16buffer = (FLAC__int16 *)s8buffer;
976 FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
977 FLAC__int32 *s32buffer = (FLAC__int32 *)s8buffer;
978 FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
979 size_t bytes_to_write = 0;
983 if(decoder_session->abort_flag)
984 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
986 /* sanity-check the bits-per-sample */
987 if(decoder_session->bps) {
988 if(bps != decoder_session->bps) {
989 if(decoder_session->got_stream_info)
990 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);
992 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);
993 if(!decoder_session->continue_through_decode_errors)
994 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
998 /* must not have gotten STREAMINFO, save the bps from the frame header */
999 FLAC__ASSERT(!decoder_session->got_stream_info);
1000 decoder_session->bps = bps;
1003 /* sanity-check the #channels */
1004 if(decoder_session->channels) {
1005 if(channels != decoder_session->channels) {
1006 if(decoder_session->got_stream_info)
1007 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
1009 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);
1010 if(!decoder_session->continue_through_decode_errors)
1011 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1015 /* must not have gotten STREAMINFO, save the #channels from the frame header */
1016 FLAC__ASSERT(!decoder_session->got_stream_info);
1017 decoder_session->channels = channels;
1020 /* sanity-check the sample rate */
1021 if(decoder_session->sample_rate) {
1022 if(frame->header.sample_rate != decoder_session->sample_rate) {
1023 if(decoder_session->got_stream_info)
1024 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);
1026 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);
1027 if(!decoder_session->continue_through_decode_errors)
1028 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1032 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
1033 FLAC__ASSERT(!decoder_session->got_stream_info);
1034 decoder_session->sample_rate = frame->header.sample_rate;
1038 * limit the number of samples to accept based on --until
1040 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1041 /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
1042 if(decoder_session->skip_specification->is_relative) {
1043 if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
1044 decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
1046 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);
1047 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1050 if(decoder_session->until_specification->is_relative) {
1051 if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
1052 decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
1054 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);
1055 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1058 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1059 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1060 if(decoder_session->until_specification->value.samples > 0) {
1061 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1062 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1063 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
1064 FLAC__ASSERT(until >= input_samples_passed);
1065 if(input_samples_passed + wide_samples > until)
1066 wide_samples = (unsigned)(until - input_samples_passed);
1067 if (wide_samples == 0) {
1068 decoder_session->abort_flag = true;
1069 decoder_session->aborting_due_to_until = true;
1070 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1074 if(decoder_session->analysis_mode) {
1076 FLAC__stream_decoder_get_decode_position(decoder_session->decoder, &dpos);
1077 frame_bytes = (unsigned)(dpos-decoder_session->decode_position);
1078 decoder_session->decode_position = dpos;
1081 if(wide_samples > 0) {
1082 decoder_session->samples_processed += wide_samples;
1083 decoder_session->frame_counter++;
1085 if(!(decoder_session->frame_counter & 0x3f))
1086 print_stats(decoder_session);
1088 if(decoder_session->analysis_mode) {
1089 flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->decode_position-frame_bytes, frame_bytes, decoder_session->aopts, fout);
1091 else if(!decoder_session->test_only) {
1092 if(shift && !decoder_session->replaygain.apply) {
1093 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1094 for(channel = 0; channel < channels; channel++)
1095 ((FLAC__int32**)buffer)[channel][wide_sample] <<= shift;/*@@@@@@un-const'ing the buffer is hacky but safe*/
1097 if(decoder_session->replaygain.apply) {
1098 bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
1101 is_unsigned_samples,
1105 bps, /* source_bps */
1106 bps+shift, /* target_bps */
1107 decoder_session->replaygain.scale,
1108 decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
1109 decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
1110 &decoder_session->replaygain.dither_context
1113 /* first some special code for common cases */
1114 else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 2 && bps+shift == 16) {
1115 FLAC__int16 *buf1_ = s16buffer + 1;
1117 memcpy(s16buffer, ((FLAC__byte*)(buffer[0]))+2, sizeof(FLAC__int32) * wide_samples - 2);
1119 memcpy(s16buffer, buffer[0], sizeof(FLAC__int32) * wide_samples);
1120 for(sample = 0; sample < wide_samples; sample++, buf1_+=2)
1121 *buf1_ = (FLAC__int16)buffer[1][sample];
1122 bytes_to_write = 4 * sample;
1124 else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 1 && bps+shift == 16) {
1125 FLAC__int16 *buf1_ = s16buffer;
1126 for(sample = 0; sample < wide_samples; sample++)
1127 *buf1_++ = (FLAC__int16)buffer[0][sample];
1128 bytes_to_write = 2 * sample;
1130 /* generic code for the rest */
1131 else if(bps+shift == 16) {
1132 if(is_unsigned_samples) {
1134 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1135 u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1136 u16buffer[sample++] = (FLAC__uint16)(buffer[1][wide_sample] + 0x8000);
1139 else if(channels == 1) {
1140 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1141 u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1143 else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1144 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1145 for(channel = 0; channel < channels; channel++, sample++)
1146 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
1151 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1152 s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1153 s16buffer[sample++] = (FLAC__int16)(buffer[1][wide_sample]);
1156 else if(channels == 1) {
1157 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1158 s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1160 else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1161 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1162 for(channel = 0; channel < channels; channel++, sample++)
1163 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
1166 if(is_big_endian != is_big_endian_host_) {
1168 const unsigned bytes = sample * 2;
1169 for(byte = 0; byte < bytes; byte += 2) {
1170 tmp = u8buffer[byte];
1171 u8buffer[byte] = u8buffer[byte+1];
1172 u8buffer[byte+1] = tmp;
1175 bytes_to_write = 2 * sample;
1177 else if(bps+shift == 24) {
1178 if(is_unsigned_samples) {
1179 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1180 for(channel = 0; channel < channels; channel++, sample++)
1181 u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
1184 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1185 for(channel = 0; channel < channels; channel++, sample++)
1186 s32buffer[sample] = buffer[channel][wide_sample];
1188 if(is_big_endian != is_big_endian_host_) {
1190 const unsigned bytes = sample * 4;
1191 for(byte = 0; byte < bytes; byte += 4) {
1192 tmp = u8buffer[byte];
1193 u8buffer[byte] = u8buffer[byte+3];
1194 u8buffer[byte+3] = tmp;
1195 tmp = u8buffer[byte+1];
1196 u8buffer[byte+1] = u8buffer[byte+2];
1197 u8buffer[byte+2] = tmp;
1202 const unsigned bytes = sample * 4;
1203 for(lbyte = byte = 0; byte < bytes; ) {
1205 u8buffer[lbyte++] = u8buffer[byte++];
1206 u8buffer[lbyte++] = u8buffer[byte++];
1207 u8buffer[lbyte++] = u8buffer[byte++];
1212 const unsigned bytes = sample * 4;
1213 for(lbyte = byte = 0; byte < bytes; ) {
1214 u8buffer[lbyte++] = u8buffer[byte++];
1215 u8buffer[lbyte++] = u8buffer[byte++];
1216 u8buffer[lbyte++] = u8buffer[byte++];
1220 bytes_to_write = 3 * sample;
1222 else if(bps+shift == 8) {
1223 if(is_unsigned_samples) {
1224 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1225 for(channel = 0; channel < channels; channel++, sample++)
1226 u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
1229 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1230 for(channel = 0; channel < channels; channel++, sample++)
1231 s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
1233 bytes_to_write = sample;
1237 /* double protection */
1238 decoder_session->abort_flag = true;
1239 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1243 if(bytes_to_write > 0) {
1244 if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
1245 /* if a pipe closed when writing to stdout, we let it go without an error message */
1246 if(errno == EPIPE && decoder_session->fout == stdout)
1247 decoder_session->aborting_due_to_until = true;
1248 decoder_session->abort_flag = true;
1249 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1252 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1255 void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1257 DecoderSession *decoder_session = (DecoderSession*)client_data;
1259 if(decoder_session->analysis_mode)
1260 FLAC__stream_decoder_get_decode_position(decoder, &decoder_session->decode_position);
1262 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
1263 FLAC__uint64 skip, until;
1264 decoder_session->got_stream_info = true;
1265 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);
1266 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1267 decoder_session->channels = metadata->data.stream_info.channels;
1268 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1270 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
1271 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1272 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1274 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1275 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1276 flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1277 decoder_session->abort_flag = true;
1280 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1281 flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1282 decoder_session->abort_flag = true;
1285 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1286 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1288 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1289 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1290 decoder_session->abort_flag = true;
1293 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1294 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1297 FLAC__ASSERT(decoder_session->total_samples != 0);
1298 FLAC__ASSERT(0 == decoder_session->cue_specification);
1299 decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1302 if(decoder_session->bps < 4 || decoder_session->bps > 24) {
1303 flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 4-24\n", decoder_session->inbasefilename, decoder_session->bps);
1304 decoder_session->abort_flag = true;
1308 else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1309 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1310 if(decoder_session->total_samples == 0) {
1311 flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1312 decoder_session->abort_flag = true;
1316 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);
1318 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1319 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1321 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1322 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1324 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1325 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1326 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1327 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1329 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1331 else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1332 if (decoder_session->replaygain.spec.apply) {
1333 double reference, gain, peak;
1334 if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
1335 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");
1336 if(decoder_session->treat_warnings_as_errors) {
1337 decoder_session->abort_flag = true;
1342 const char *ls[] = { "no", "peak", "hard" };
1343 const char *ns[] = { "no", "low", "medium", "high" };
1344 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1345 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1346 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1347 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]);
1348 flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1349 /* don't check if(decoder_session->treat_warnings_as_errors) because the user explicitly asked for it */
1352 (void)flac__utils_get_channel_mask_tag(metadata, &decoder_session->channel_mask);
1356 void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1358 DecoderSession *decoder_session = (DecoderSession*)client_data;
1360 flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1361 if(!decoder_session->continue_through_decode_errors) {
1362 decoder_session->abort_flag = true;
1363 if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1364 decoder_session->aborting_due_to_unparseable = true;
1368 void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
1370 const int ilen = strlen(d->inbasefilename) + 1;
1372 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1374 flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
1376 /* print out some more info for some errors: */
1377 if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
1378 flac__utils_printf(stderr, 1,
1380 "An error occurred opening the input file; it is likely that it does not exist\n"
1381 "or is not readable.\n"
1386 void print_error_with_state(const DecoderSession *d, const char *message)
1388 const int ilen = strlen(d->inbasefilename) + 1;
1390 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1391 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", FLAC__stream_decoder_get_resolved_state_string(d->decoder));
1393 /* print out some more info for some errors: */
1394 if (d->aborting_due_to_unparseable) {
1395 flac__utils_printf(stderr, 1,
1397 "The FLAC stream may have been created by a more advanced encoder. Try\n"
1398 " metaflac --show-vendor-tag %s\n"
1399 "If the version number is greater than %s, this decoder is probably\n"
1400 "not able to decode the file. If the version number is not, the file\n"
1401 "may be corrupted, or you may have found a bug. In this case please\n"
1402 "submit a bug report to\n"
1403 " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
1404 "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1405 d->inbasefilename, FLAC__VERSION_STRING
1410 void print_stats(const DecoderSession *decoder_session)
1412 if(flac__utils_verbosity_ >= 2) {
1413 #if defined _MSC_VER || defined __MINGW32__
1414 /* with MSVC you have to spoon feed it the casting */
1415 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1417 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1419 if(decoder_session->total_samples > 0) {
1420 fprintf(stderr, "\r%s: %s%u%% complete",
1421 decoder_session->inbasefilename,
1422 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1423 (unsigned)floor(progress + 0.5)
1427 fprintf(stderr, "\r%s: %s %u samples",
1428 decoder_session->inbasefilename,
1429 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1430 (unsigned)decoder_session->samples_processed