Fix -Wshadow warnings when compiling with mingw-gcc.
[flac.git] / src / flac / decode.c
blob24fe320976b0b4172cff5ccd823e85b8a79ba5b8
1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009 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 along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #if HAVE_CONFIG_H
20 # include <config.h>
21 #endif
23 #include <errno.h>
24 #include <math.h> /* for floor() */
25 #include <stdio.h> /* for FILE etc. */
26 #include <string.h> /* for strcmp(), strerror() */
27 #include "FLAC/all.h"
28 #include "share/grabbag.h"
29 #include "share/replaygain_synthesis.h"
30 #include "share/compat.h"
31 #include "decode.h"
33 typedef struct {
34 #if FLAC__HAS_OGG
35 FLAC__bool is_ogg;
36 FLAC__bool use_first_serial_number;
37 long serial_number;
38 #endif
40 FileFormat format;
41 FLAC__bool treat_warnings_as_errors;
42 FLAC__bool continue_through_decode_errors;
43 FLAC__bool channel_map_none;
45 struct {
46 replaygain_synthesis_spec_t spec;
47 FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */
48 double scale;
49 DitherContext dither_context;
50 } replaygain;
52 FLAC__bool test_only;
53 FLAC__bool analysis_mode;
54 analysis_options aopts;
55 utils__SkipUntilSpecification *skip_specification;
56 utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
57 utils__CueSpecification *cue_specification;
59 const char *inbasefilename;
60 const char *infilename;
61 const char *outfilename;
63 FLAC__uint64 samples_processed;
64 unsigned frame_counter;
65 FLAC__bool abort_flag;
66 FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
67 FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */
68 FLAC__bool error_callback_suppress_messages; /* turn on to prevent repeating messages from the error callback */
70 FLAC__bool iff_headers_need_fixup;
72 FLAC__bool is_big_endian;
73 FLAC__bool is_unsigned_samples;
74 FLAC__bool got_stream_info;
75 FLAC__bool has_md5sum;
76 FLAC__uint64 total_samples;
77 unsigned bps;
78 unsigned channels;
79 unsigned sample_rate;
80 FLAC__uint32 channel_mask;
82 /* these are used only in analyze mode */
83 FLAC__uint64 decode_position;
85 FLAC__StreamDecoder *decoder;
87 FILE *fout;
89 foreign_metadata_t *foreign_metadata; /* NULL unless --keep-foreign-metadata requested */
90 FLAC__off_t fm_offset1, fm_offset2, fm_offset3;
91 } DecoderSession;
94 static FLAC__bool is_big_endian_host_;
98 * local routines
100 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);
101 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
102 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, const char *infilename);
103 static FLAC__bool DecoderSession_process(DecoderSession *d);
104 static int DecoderSession_finish_ok(DecoderSession *d);
105 static int DecoderSession_finish_error(DecoderSession *d);
106 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
107 static FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples);
108 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);
109 static FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate);
110 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
111 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
112 static FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val);
113 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
114 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
115 static FLAC__bool write_sane_extended(FILE *f, unsigned val);
116 static FLAC__bool fixup_iff_headers(DecoderSession *d);
117 static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
118 static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
119 static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
120 static void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status);
121 static void print_error_with_state(const DecoderSession *d, const char *message);
122 static void print_stats(const DecoderSession *decoder_session);
126 * public routines
128 int flac__decode_file(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, decode_options_t options)
130 DecoderSession decoder_session;
132 FLAC__ASSERT(
133 options.format == FORMAT_WAVE ||
134 options.format == FORMAT_WAVE64 ||
135 options.format == FORMAT_RF64 ||
136 options.format == FORMAT_AIFF ||
137 options.format == FORMAT_AIFF_C ||
138 options.format == FORMAT_RAW
141 if(options.format == FORMAT_RAW) {
142 decoder_session.is_big_endian = options.format_options.raw.is_big_endian;
143 decoder_session.is_unsigned_samples = options.format_options.raw.is_unsigned_samples;
146 if(!
147 DecoderSession_construct(
148 &decoder_session,
149 #if FLAC__HAS_OGG
150 options.is_ogg,
151 options.use_first_serial_number,
152 options.serial_number,
153 #else
154 /*is_ogg=*/false,
155 /*use_first_serial_number=*/false,
156 /*serial_number=*/0,
157 #endif
158 options.format,
159 options.treat_warnings_as_errors,
160 options.continue_through_decode_errors,
161 options.channel_map_none,
162 options.replaygain_synthesis_spec,
163 analysis_mode,
164 aopts,
165 &options.skip_specification,
166 &options.until_specification,
167 options.has_cue_specification? &options.cue_specification : 0,
168 options.format == FORMAT_RAW? NULL : options.format_options.iff.foreign_metadata,
169 infilename,
170 outfilename
173 return 1;
175 stats_new_file();
176 if(!DecoderSession_init_decoder(&decoder_session, infilename))
177 return DecoderSession_finish_error(&decoder_session);
179 if(!DecoderSession_process(&decoder_session))
180 return DecoderSession_finish_error(&decoder_session);
182 return DecoderSession_finish_ok(&decoder_session);
185 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)
187 #if FLAC__HAS_OGG
188 d->is_ogg = is_ogg;
189 d->use_first_serial_number = use_first_serial_number;
190 d->serial_number = serial_number;
191 #else
192 (void)is_ogg;
193 (void)use_first_serial_number;
194 (void)serial_number;
195 #endif
197 d->format = format;
198 d->treat_warnings_as_errors = treat_warnings_as_errors;
199 d->continue_through_decode_errors = continue_through_decode_errors;
200 d->channel_map_none = channel_map_none;
201 d->replaygain.spec = replaygain_synthesis_spec;
202 d->replaygain.apply = false;
203 d->replaygain.scale = 0.0;
204 /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
205 d->test_only = (0 == outfilename);
206 d->analysis_mode = analysis_mode;
207 d->aopts = aopts;
208 d->skip_specification = skip_specification;
209 d->until_specification = until_specification;
210 d->cue_specification = cue_specification;
212 d->inbasefilename = grabbag__file_get_basename(infilename);
213 d->infilename = infilename;
214 d->outfilename = outfilename;
216 d->samples_processed = 0;
217 d->frame_counter = 0;
218 d->abort_flag = false;
219 d->aborting_due_to_until = false;
220 d->aborting_due_to_unparseable = false;
221 d->error_callback_suppress_messages = false;
223 d->iff_headers_need_fixup = false;
225 d->total_samples = 0;
226 d->got_stream_info = false;
227 d->has_md5sum = false;
228 d->bps = 0;
229 d->channels = 0;
230 d->sample_rate = 0;
231 d->channel_mask = 0;
233 d->decode_position = 0;
235 d->decoder = 0;
237 d->fout = 0; /* initialized with an open file later if necessary */
239 d->foreign_metadata = foreign_metadata;
241 FLAC__ASSERT(!(d->test_only && d->analysis_mode));
243 if(!d->test_only) {
244 if(0 == strcmp(outfilename, "-")) {
245 d->fout = grabbag__file_get_binary_stdout();
247 else {
248 if(0 == (d->fout = flac_fopen(outfilename, "wb"))) {
249 flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
250 DecoderSession_destroy(d, /*error_occurred=*/true);
251 return false;
256 if(analysis_mode)
257 flac__analyze_init(aopts);
259 return true;
262 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
264 if(0 != d->fout && d->fout != stdout) {
265 fclose(d->fout);
266 if(error_occurred)
267 flac_unlink(d->outfilename);
271 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, const char *infilename)
273 FLAC__StreamDecoderInitStatus init_status;
274 FLAC__uint32 test = 1;
276 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
278 if(!decoder_session->analysis_mode && !decoder_session->test_only && decoder_session->foreign_metadata) {
279 const char *error;
280 if(!flac__foreign_metadata_read_from_flac(decoder_session->foreign_metadata, infilename, &error)) {
281 flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", decoder_session->inbasefilename, error);
282 return false;
286 decoder_session->decoder = FLAC__stream_decoder_new();
288 if(0 == decoder_session->decoder) {
289 flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
290 return false;
293 FLAC__stream_decoder_set_md5_checking(decoder_session->decoder, true);
294 if (0 != decoder_session->cue_specification)
295 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_CUESHEET);
296 if (decoder_session->replaygain.spec.apply)
297 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
299 #if FLAC__HAS_OGG
300 if(decoder_session->is_ogg) {
301 if(!decoder_session->use_first_serial_number)
302 FLAC__stream_decoder_set_ogg_serial_number(decoder_session->decoder, decoder_session->serial_number);
303 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);
305 else
306 #endif
308 init_status = FLAC__stream_decoder_init_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
311 if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
312 print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
313 return false;
316 return true;
319 FLAC__bool DecoderSession_process(DecoderSession *d)
321 if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder)) {
322 flac__utils_printf(stderr, 2, "\n");
323 print_error_with_state(d, "ERROR while decoding metadata");
324 return false;
326 if(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM) {
327 flac__utils_printf(stderr, 2, "\n");
328 print_error_with_state(d, "ERROR during metadata decoding");
329 if(!d->continue_through_decode_errors)
330 return false;
333 if(d->abort_flag)
334 return false;
336 /* set channel mapping */
337 /* currently FLAC order matches SMPTE/WAVEFORMATEXTENSIBLE order, so no reordering is necessary; see encode.c */
338 /* only the channel mask must be set if it was not already picked up from the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag */
339 if(!d->channel_map_none && d->channel_mask == 0) {
340 if(d->channels == 1) {
341 d->channel_mask = 0x0001;
343 else if(d->channels == 2) {
344 d->channel_mask = 0x0003;
346 else if(d->channels == 3) {
347 d->channel_mask = 0x0007;
349 else if(d->channels == 4) {
350 d->channel_mask = 0x0033;
352 else if(d->channels == 5) {
353 d->channel_mask = 0x0607;
355 else if(d->channels == 6) {
356 d->channel_mask = 0x060f;
358 else if(d->channels == 7) {
359 d->channel_mask = 0x070f;
361 else if(d->channels == 8) {
362 d->channel_mask = 0x063f;
366 /* write the WAVE/AIFF headers if necessary */
367 if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
368 if(!write_iff_headers(d->fout, d, d->total_samples)) {
369 d->abort_flag = true;
370 return false;
374 if(d->skip_specification->value.samples > 0) {
375 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
377 if(!FLAC__stream_decoder_seek_absolute(d->decoder, skip)) {
378 print_error_with_state(d, "ERROR seeking while skipping bytes");
379 return false;
382 if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder) && !d->aborting_due_to_until) {
383 flac__utils_printf(stderr, 2, "\n");
384 print_error_with_state(d, "ERROR while decoding data");
385 if(!d->continue_through_decode_errors)
386 return false;
389 (d->abort_flag && !(d->aborting_due_to_until || d->continue_through_decode_errors)) ||
390 (FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until)
392 flac__utils_printf(stderr, 2, "\n");
393 print_error_with_state(d, "ERROR during decoding");
394 return false;
397 /* write padding bytes for alignment if necessary */
398 if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
399 const FLAC__uint64 data_size = d->total_samples * d->channels * ((d->bps+7)/8);
400 unsigned padding;
401 if(d->format != FORMAT_WAVE64) {
402 padding = (unsigned)(data_size & 1);
404 else {
405 /* 8-byte alignment for Wave64 */
406 padding = (8 - (unsigned)(data_size & 7)) & 7;
408 for( ; padding > 0; --padding) {
409 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
410 print_error_with_state(
412 d->format == FORMAT_WAVE? "ERROR writing pad byte to WAVE data chunk" :
413 d->format == FORMAT_WAVE64? "ERROR writing pad bytes to WAVE64 data chunk" :
414 d->format == FORMAT_RF64? "ERROR writing pad byte to RF64 data chunk" :
415 "ERROR writing pad byte to AIFF SSND chunk"
417 return false;
422 return true;
425 int DecoderSession_finish_ok(DecoderSession *d)
427 FLAC__bool ok = true, md5_failure = false;
429 if(d->decoder) {
430 md5_failure = !FLAC__stream_decoder_finish(d->decoder) && !d->aborting_due_to_until;
431 print_stats(d);
432 FLAC__stream_decoder_delete(d->decoder);
434 if(d->analysis_mode)
435 flac__analyze_finish(d->aopts);
436 if(md5_failure) {
437 stats_print_name(1, d->inbasefilename);
438 flac__utils_printf(stderr, 1, "ERROR, MD5 signature mismatch\n");
439 ok = d->continue_through_decode_errors;
441 else {
442 if(!d->got_stream_info) {
443 stats_print_name(1, d->inbasefilename);
444 flac__utils_printf(stderr, 1, "WARNING, cannot check MD5 signature since there was no STREAMINFO\n");
445 ok = !d->treat_warnings_as_errors;
447 else if(!d->has_md5sum) {
448 stats_print_name(1, d->inbasefilename);
449 flac__utils_printf(stderr, 1, "WARNING, cannot check MD5 signature since it was unset in the STREAMINFO\n");
450 ok = !d->treat_warnings_as_errors;
452 stats_print_name(2, d->inbasefilename);
453 flac__utils_printf(stderr, 2, "%s \n", d->test_only? "ok ":d->analysis_mode?"done ":"done");
455 DecoderSession_destroy(d, /*error_occurred=*/!ok);
456 if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
457 if(d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))) {
458 if(!fixup_iff_headers(d))
459 return 1;
461 if(d->foreign_metadata) {
462 const char *error;
463 if(!flac__foreign_metadata_write_to_iff(d->foreign_metadata, d->infilename, d->outfilename, d->fm_offset1, d->fm_offset2, d->fm_offset3, &error)) {
464 flac__utils_printf(stderr, 1, "ERROR updating foreign metadata from %s to %s: %s\n", d->infilename, d->outfilename, error);
465 return 1;
469 return ok? 0 : 1;
472 int DecoderSession_finish_error(DecoderSession *d)
474 if(d->decoder) {
475 (void)FLAC__stream_decoder_finish(d->decoder);
476 FLAC__stream_decoder_delete(d->decoder);
478 if(d->analysis_mode)
479 flac__analyze_finish(d->aopts);
480 DecoderSession_destroy(d, /*error_occurred=*/true);
481 return 1;
484 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
486 /* convert from mm:ss.sss to sample number if necessary */
487 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
489 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
490 if(spec->is_relative && spec->value.samples == 0) {
491 spec->is_relative = false;
492 return true;
495 /* in any other case the total samples in the input must be known */
496 if(total_samples_in_input == 0) {
497 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
498 return false;
501 FLAC__ASSERT(spec->value_is_samples);
503 /* convert relative specifications to absolute */
504 if(spec->is_relative) {
505 if(spec->value.samples <= 0)
506 spec->value.samples += (FLAC__int64)total_samples_in_input;
507 else
508 spec->value.samples += skip;
509 spec->is_relative = false;
512 /* error check */
513 if(spec->value.samples < 0) {
514 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
515 return false;
517 if((FLAC__uint64)spec->value.samples <= skip) {
518 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
519 return false;
521 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
522 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
523 return false;
526 return true;
529 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
531 const FileFormat format = decoder_session->format;
532 const char *fmt_desc =
533 format==FORMAT_WAVE? "WAVE" :
534 format==FORMAT_WAVE64? "Wave64" :
535 format==FORMAT_RF64? "RF64" :
536 "AIFF";
537 const FLAC__bool is_waveformatextensible =
538 (format == FORMAT_WAVE || format == FORMAT_WAVE64 || format == FORMAT_RF64) &&
540 decoder_session->channel_mask == 2 ||
541 decoder_session->channel_mask > 3 ||
542 decoder_session->bps%8 ||
543 decoder_session->channels > 2
545 const FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
546 const FLAC__uint64 aligned_data_size =
547 format == FORMAT_WAVE64?
548 (data_size+7) & (~(FLAC__uint64)7) :
549 (data_size+1) & (~(FLAC__uint64)1);
551 FLAC__uint64 iff_size;
552 unsigned foreign_metadata_size = 0; /* size of all non-audio non-fmt/COMM foreign metadata chunks */
553 foreign_metadata_t *fm = decoder_session->foreign_metadata;
554 size_t i;
556 FLAC__ASSERT(
557 format == FORMAT_WAVE ||
558 format == FORMAT_WAVE64 ||
559 format == FORMAT_RF64 ||
560 format == FORMAT_AIFF ||
561 format == FORMAT_AIFF_C
564 if(samples == 0) {
565 if(f == stdout) {
566 flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
567 flac__utils_printf(stderr, 1, " Generated %s file will have a data chunk size of 0. Try\n", fmt_desc);
568 flac__utils_printf(stderr, 1, " decoding directly to a file instead.\n");
569 if(decoder_session->treat_warnings_as_errors)
570 return false;
572 else {
573 decoder_session->iff_headers_need_fixup = true;
577 if(fm) {
578 FLAC__ASSERT(fm->format_block);
579 FLAC__ASSERT(fm->audio_block);
580 FLAC__ASSERT(fm->format_block < fm->audio_block);
581 /* calc foreign metadata size; we always skip the first chunk, ds64 chunk, format chunk, and sound chunk since we write our own */
582 for(i = format==FORMAT_RF64?2:1; i < fm->num_blocks; i++) {
583 if(i != fm->format_block && i != fm->audio_block)
584 foreign_metadata_size += fm->blocks[i].size;
588 if(samples == 0)
589 iff_size = 0;
590 else if(format == FORMAT_WAVE || format == FORMAT_RF64)
591 /* 4 for WAVE form bytes */
592 /* +{36,0} for ds64 chunk */
593 /* +8+{40,16} for fmt chunk header and body */
594 /* +8 for data chunk header */
595 iff_size = 4 + (format==FORMAT_RF64?36:0) + 8+(is_waveformatextensible?40:16) + 8 + foreign_metadata_size + aligned_data_size;
596 else if(format == FORMAT_WAVE64)
597 /* 16+8 for RIFF GUID and size field */
598 /* +16 for WAVE GUID */
599 /* +16+8+{40,16} for fmt chunk header (GUID and size field) and body */
600 /* +16+8 for data chunk header (GUID and size field) */
601 iff_size = 16+8 + 16 + 16+8+(is_waveformatextensible?40:16) + 16+8 + foreign_metadata_size + aligned_data_size;
602 else /* AIFF */
603 iff_size = 46 + foreign_metadata_size + aligned_data_size;
605 if(format != FORMAT_WAVE64 && format != FORMAT_RF64 && iff_size >= 0xFFFFFFF4) {
606 flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file\n", decoder_session->inbasefilename, fmt_desc);
607 return false;
610 if(format == FORMAT_WAVE || format == FORMAT_WAVE64 || format == FORMAT_RF64) {
611 /* RIFF header */
612 switch(format) {
613 case FORMAT_WAVE:
614 if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
615 return false;
616 if(!write_little_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
617 return false;
618 if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
619 return false;
620 break;
621 case FORMAT_WAVE64:
622 /* RIFF GUID 66666972-912E-11CF-A5D6-28DB04C10000 */
623 if(flac__utils_fwrite("\x72\x69\x66\x66\x2E\x91\xCF\x11\xA5\xD6\x28\xDB\x04\xC1\x00\x00", 1, 16, f) != 16)
624 return false;
625 if(!write_little_endian_uint64(f, iff_size))
626 return false;
627 /* WAVE GUID 65766177-ACF3-11D3-8CD1-00C04F8EDB8A */
628 if(flac__utils_fwrite("\x77\x61\x76\x65\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
629 return false;
630 break;
631 case FORMAT_RF64:
632 if(flac__utils_fwrite("RF64", 1, 4, f) != 4)
633 return false;
634 if(!write_little_endian_uint32(f, 0xffffffff))
635 return false;
636 if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
637 return false;
638 break;
639 default:
640 return false;
643 /* ds64 chunk for RF64 */
644 if(format == FORMAT_RF64) {
645 if(flac__utils_fwrite("ds64", 1, 4, f) != 4)
646 return false;
648 if(!write_little_endian_uint32(f, 28)) /* chunk size */
649 return false;
651 if(!write_little_endian_uint64(f, iff_size))
652 return false;
654 if(!write_little_endian_uint64(f, data_size))
655 return false;
657 if(!write_little_endian_uint64(f, samples)) /*@@@@@@ correct? */
658 return false;
660 if(!write_little_endian_uint32(f, 0)) /* table size */
661 return false;
664 decoder_session->fm_offset1 = ftello(f);
666 if(fm) {
667 /* seek forward to {allocate} or {skip over already-written chunks} before "fmt " */
668 for(i = format==FORMAT_RF64?2:1; i < fm->format_block; i++) {
669 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
670 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"fmt \"\n", decoder_session->inbasefilename);
671 return false;
676 if(format != FORMAT_WAVE64) {
677 if(flac__utils_fwrite("fmt ", 1, 4, f) != 4)
678 return false;
679 if(!write_little_endian_uint32(f, is_waveformatextensible? 40 : 16)) /* chunk size */
680 return false;
682 else { /* Wave64 */
683 /* fmt GUID 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A */
684 if(flac__utils_fwrite("\x66\x6D\x74\x20\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
685 return false;
686 /* chunk size (+16+8 for GUID and size fields) */
687 if(!write_little_endian_uint64(f, 16+8+(is_waveformatextensible?40:16)))
688 return false;
691 if(!write_riff_wave_fmt_chunk_body(f, is_waveformatextensible, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate, decoder_session->channel_mask))
692 return false;
694 decoder_session->fm_offset2 = ftello(f);
696 if(fm) {
697 /* seek forward to {allocate} or {skip over already-written chunks} after "fmt " but before "data" */
698 for(i = fm->format_block+1; i < fm->audio_block; i++) {
699 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
700 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"fmt \"\n", decoder_session->inbasefilename);
701 return false;
706 if(format != FORMAT_WAVE64) {
707 if(flac__utils_fwrite("data", 1, 4, f) != 4)
708 return false;
709 if(!write_little_endian_uint32(f, format==FORMAT_RF64? 0xffffffff : (FLAC__uint32)data_size))
710 return false;
712 else { /* Wave64 */
713 /* data GUID 61746164-ACF3-11D3-8CD1-00C04F8EDB8A */
714 if(flac__utils_fwrite("\x64\x61\x74\x61\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
715 return false;
716 /* +16+8 for GUID and size fields */
717 if(!write_little_endian_uint64(f, 16+8 + data_size))
718 return false;
721 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
723 else {
724 if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
725 return false;
727 if(!write_big_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
728 return false;
730 if(flac__utils_fwrite("AIFF", 1, 4, f) != 4)
731 return false;
733 decoder_session->fm_offset1 = ftello(f);
735 if(fm) {
736 /* seek forward to {allocate} or {skip over already-written chunks} before "COMM" */
737 for(i = 1; i < fm->format_block; i++) {
738 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
739 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"COMM\"\n", decoder_session->inbasefilename);
740 return false;
745 if(!write_aiff_form_comm_chunk(f, samples, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate))
746 return false;
748 decoder_session->fm_offset2 = ftello(f);
750 if(fm) {
751 /* seek forward to {allocate} or {skip over already-written chunks} after "COMM" but before "SSND" */
752 for(i = fm->format_block+1; i < fm->audio_block; i++) {
753 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
754 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"COMM\"\n", decoder_session->inbasefilename);
755 return false;
760 if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
761 return false;
763 if(!write_big_endian_uint32(f, (FLAC__uint32)data_size + 8)) /* data size */
764 return false;
766 if(!write_big_endian_uint32(f, 0/*offset_size*/))
767 return false;
769 if(!write_big_endian_uint32(f, 0/*block_size*/))
770 return false;
772 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
775 return true;
778 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)
780 if(!write_little_endian_uint16(f, (FLAC__uint16)(is_waveformatextensible? 65534 : 1))) /* compression code */
781 return false;
783 if(!write_little_endian_uint16(f, (FLAC__uint16)channels))
784 return false;
786 if(!write_little_endian_uint32(f, sample_rate))
787 return false;
789 if(!write_little_endian_uint32(f, sample_rate * channels * ((bps+7) / 8)))
790 return false;
792 if(!write_little_endian_uint16(f, (FLAC__uint16)(channels * ((bps+7) / 8)))) /* block align */
793 return false;
795 if(!write_little_endian_uint16(f, (FLAC__uint16)(((bps+7)/8)*8))) /* bits per sample */
796 return false;
798 if(is_waveformatextensible) {
799 if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */
800 return false;
802 if(!write_little_endian_uint16(f, (FLAC__uint16)bps)) /* validBitsPerSample */
803 return false;
805 if(!write_little_endian_uint32(f, channel_mask))
806 return false;
808 /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */
809 if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16)
810 return false;
813 return true;
816 FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate)
818 FLAC__ASSERT(samples <= 0xffffffff);
820 if(flac__utils_fwrite("COMM", 1, 4, f) != 4)
821 return false;
823 if(!write_big_endian_uint32(f, 18)) /* chunk size = 18 */
824 return false;
826 if(!write_big_endian_uint16(f, (FLAC__uint16)channels))
827 return false;
829 if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
830 return false;
832 if(!write_big_endian_uint16(f, (FLAC__uint16)bps))
833 return false;
835 if(!write_sane_extended(f, sample_rate))
836 return false;
838 return true;
841 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
843 FLAC__byte *b = (FLAC__byte*)(&val);
844 if(is_big_endian_host_) {
845 FLAC__byte tmp;
846 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
848 return flac__utils_fwrite(b, 1, 2, f) == 2;
851 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
853 FLAC__byte *b = (FLAC__byte*)(&val);
854 if(is_big_endian_host_) {
855 FLAC__byte tmp;
856 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
857 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
859 return flac__utils_fwrite(b, 1, 4, f) == 4;
862 FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val)
864 FLAC__byte *b = (FLAC__byte*)(&val);
865 if(is_big_endian_host_) {
866 FLAC__byte tmp;
867 tmp = b[7]; b[7] = b[0]; b[0] = tmp;
868 tmp = b[6]; b[6] = b[1]; b[1] = tmp;
869 tmp = b[5]; b[5] = b[2]; b[2] = tmp;
870 tmp = b[4]; b[4] = b[3]; b[3] = tmp;
872 return flac__utils_fwrite(b, 1, 8, f) == 8;
875 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
877 FLAC__byte *b = (FLAC__byte*)(&val);
878 if(!is_big_endian_host_) {
879 FLAC__byte tmp;
880 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
882 return flac__utils_fwrite(b, 1, 2, f) == 2;
885 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
887 FLAC__byte *b = (FLAC__byte*)(&val);
888 if(!is_big_endian_host_) {
889 FLAC__byte tmp;
890 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
891 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
893 return flac__utils_fwrite(b, 1, 4, f) == 4;
896 FLAC__bool write_sane_extended(FILE *f, unsigned val)
897 /* Write to 'f' a SANE extended representation of 'val'. Return false if
898 * the write succeeds; return true otherwise.
900 * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
901 * of exponent, and 64 bits of significand (mantissa). Unlike most IEEE-754
902 * representations, it does not imply a 1 above the MSB of the significand.
904 * Preconditions:
905 * val!=0U
908 unsigned int shift, exponent;
910 FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
912 for(shift= 0U; (val>>(31-shift))==0U; ++shift)
914 val<<= shift;
915 exponent= 63U-(shift+32U); /* add 32 for unused second word */
917 if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
918 return false;
919 if(!write_big_endian_uint32(f, val))
920 return false;
921 if(!write_big_endian_uint32(f, 0)) /* unused second word */
922 return false;
924 return true;
927 FLAC__bool fixup_iff_headers(DecoderSession *d)
929 const char *fmt_desc =
930 d->format==FORMAT_WAVE? "WAVE" :
931 d->format==FORMAT_WAVE64? "Wave64" :
932 d->format==FORMAT_RF64? "RF64" :
933 "AIFF";
934 FILE *f = flac_fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
936 if(0 == f) {
937 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));
938 return false;
941 if(!write_iff_headers(f, d, d->samples_processed)) {
942 fclose(f);
943 return false;
946 fclose(f);
947 return true;
950 FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
952 DecoderSession *decoder_session = (DecoderSession*)client_data;
953 FILE *fout = decoder_session->fout;
954 const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
955 const unsigned shift = (decoder_session->format != FORMAT_RAW && (bps%8))? 8-(bps%8): 0;
956 FLAC__bool is_big_endian = (
957 decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? true : (
958 decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 ? false :
959 decoder_session->is_big_endian
961 FLAC__bool is_unsigned_samples = (
962 decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? false : (
963 decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 ? bps<=8 :
964 decoder_session->is_unsigned_samples
966 unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel;
967 unsigned frame_bytes = 0;
968 static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
969 FLAC__uint8 *u8buffer = (FLAC__uint8 *)s8buffer;
970 FLAC__int16 *s16buffer = (FLAC__int16 *)s8buffer;
971 FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
972 FLAC__int32 *s32buffer = (FLAC__int32 *)s8buffer;
973 FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
974 size_t bytes_to_write = 0;
976 (void)decoder;
978 if(decoder_session->abort_flag)
979 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
981 /* sanity-check the bits-per-sample */
982 if(decoder_session->bps) {
983 if(bps != decoder_session->bps) {
984 if(decoder_session->got_stream_info)
985 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);
986 else
987 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);
988 if(!decoder_session->continue_through_decode_errors)
989 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
992 else {
993 /* must not have gotten STREAMINFO, save the bps from the frame header */
994 FLAC__ASSERT(!decoder_session->got_stream_info);
995 decoder_session->bps = bps;
998 /* sanity-check the #channels */
999 if(decoder_session->channels) {
1000 if(channels != decoder_session->channels) {
1001 if(decoder_session->got_stream_info)
1002 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
1003 else
1004 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);
1005 if(!decoder_session->continue_through_decode_errors)
1006 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1009 else {
1010 /* must not have gotten STREAMINFO, save the #channels from the frame header */
1011 FLAC__ASSERT(!decoder_session->got_stream_info);
1012 decoder_session->channels = channels;
1015 /* sanity-check the sample rate */
1016 if(decoder_session->sample_rate) {
1017 if(frame->header.sample_rate != decoder_session->sample_rate) {
1018 if(decoder_session->got_stream_info)
1019 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);
1020 else
1021 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);
1022 if(!decoder_session->continue_through_decode_errors)
1023 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1026 else {
1027 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
1028 FLAC__ASSERT(!decoder_session->got_stream_info);
1029 decoder_session->sample_rate = frame->header.sample_rate;
1033 * limit the number of samples to accept based on --until
1035 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1036 /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
1037 if(decoder_session->skip_specification->is_relative) {
1038 if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
1039 decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
1040 else {
1041 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);
1042 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1045 if(decoder_session->until_specification->is_relative) {
1046 if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
1047 decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
1048 else {
1049 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);
1050 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1053 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1054 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1055 if(decoder_session->until_specification->value.samples > 0) {
1056 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1057 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1058 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
1059 FLAC__ASSERT(until >= input_samples_passed);
1060 if(input_samples_passed + wide_samples > until)
1061 wide_samples = (unsigned)(until - input_samples_passed);
1062 if (wide_samples == 0) {
1063 decoder_session->abort_flag = true;
1064 decoder_session->aborting_due_to_until = true;
1065 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1069 if(decoder_session->analysis_mode) {
1070 FLAC__uint64 dpos;
1071 FLAC__stream_decoder_get_decode_position(decoder_session->decoder, &dpos);
1072 frame_bytes = (unsigned)(dpos-decoder_session->decode_position);
1073 decoder_session->decode_position = dpos;
1076 if(wide_samples > 0) {
1077 decoder_session->samples_processed += wide_samples;
1078 decoder_session->frame_counter++;
1080 if(!(decoder_session->frame_counter & 0x3f))
1081 print_stats(decoder_session);
1083 if(decoder_session->analysis_mode) {
1084 flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->decode_position-frame_bytes, frame_bytes, decoder_session->aopts, fout);
1086 else if(!decoder_session->test_only) {
1087 if(shift && !decoder_session->replaygain.apply) {
1088 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1089 for(channel = 0; channel < channels; channel++)
1090 ((FLAC__int32**)buffer)[channel][wide_sample] <<= shift;/*@@@@@@un-const'ing the buffer is hacky but safe*/
1092 if(decoder_session->replaygain.apply) {
1093 bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
1094 u8buffer,
1095 !is_big_endian,
1096 is_unsigned_samples,
1097 buffer,
1098 wide_samples,
1099 channels,
1100 bps, /* source_bps */
1101 bps+shift, /* target_bps */
1102 decoder_session->replaygain.scale,
1103 decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
1104 decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
1105 &decoder_session->replaygain.dither_context
1108 /* first some special code for common cases */
1109 else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 2 && bps+shift == 16) {
1110 FLAC__int16 *buf1_ = s16buffer + 1;
1111 if(is_big_endian)
1112 memcpy(s16buffer, ((FLAC__byte*)(buffer[0]))+2, sizeof(FLAC__int32) * wide_samples - 2);
1113 else
1114 memcpy(s16buffer, buffer[0], sizeof(FLAC__int32) * wide_samples);
1115 for(sample = 0; sample < wide_samples; sample++, buf1_+=2)
1116 *buf1_ = (FLAC__int16)buffer[1][sample];
1117 bytes_to_write = 4 * sample;
1119 else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 1 && bps+shift == 16) {
1120 FLAC__int16 *buf1_ = s16buffer;
1121 for(sample = 0; sample < wide_samples; sample++)
1122 *buf1_++ = (FLAC__int16)buffer[0][sample];
1123 bytes_to_write = 2 * sample;
1125 /* generic code for the rest */
1126 else if(bps+shift == 16) {
1127 if(is_unsigned_samples) {
1128 if(channels == 2) {
1129 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1130 u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1131 u16buffer[sample++] = (FLAC__uint16)(buffer[1][wide_sample] + 0x8000);
1134 else if(channels == 1) {
1135 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1136 u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1138 else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1139 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1140 for(channel = 0; channel < channels; channel++, sample++)
1141 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
1144 else {
1145 if(channels == 2) {
1146 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1147 s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1148 s16buffer[sample++] = (FLAC__int16)(buffer[1][wide_sample]);
1151 else if(channels == 1) {
1152 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1153 s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1155 else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1156 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1157 for(channel = 0; channel < channels; channel++, sample++)
1158 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
1161 if(is_big_endian != is_big_endian_host_) {
1162 unsigned char tmp;
1163 const unsigned bytes = sample * 2;
1164 unsigned b;
1165 for(b = 0; b < bytes; b += 2) {
1166 tmp = u8buffer[b];
1167 u8buffer[b] = u8buffer[b+1];
1168 u8buffer[b+1] = tmp;
1171 bytes_to_write = 2 * sample;
1173 else if(bps+shift == 24) {
1174 if(is_unsigned_samples) {
1175 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1176 for(channel = 0; channel < channels; channel++, sample++)
1177 u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
1179 else {
1180 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1181 for(channel = 0; channel < channels; channel++, sample++)
1182 s32buffer[sample] = buffer[channel][wide_sample];
1184 if(is_big_endian != is_big_endian_host_) {
1185 unsigned char tmp;
1186 const unsigned bytes = sample * 4;
1187 unsigned b;
1188 for(b = 0; b < bytes; b += 4) {
1189 tmp = u8buffer[b];
1190 u8buffer[b] = u8buffer[b+3];
1191 u8buffer[b+3] = tmp;
1192 tmp = u8buffer[b+1];
1193 u8buffer[b+1] = u8buffer[b+2];
1194 u8buffer[b+2] = tmp;
1197 if(is_big_endian) {
1198 unsigned b, lbyte;
1199 const unsigned bytes = sample * 4;
1200 for(lbyte = b = 0; b < bytes; ) {
1201 b++;
1202 u8buffer[lbyte++] = u8buffer[b++];
1203 u8buffer[lbyte++] = u8buffer[b++];
1204 u8buffer[lbyte++] = u8buffer[b++];
1207 else {
1208 unsigned b, lbyte;
1209 const unsigned bytes = sample * 4;
1210 for(lbyte = b = 0; b < bytes; ) {
1211 u8buffer[lbyte++] = u8buffer[b++];
1212 u8buffer[lbyte++] = u8buffer[b++];
1213 u8buffer[lbyte++] = u8buffer[b++];
1214 b++;
1217 bytes_to_write = 3 * sample;
1219 else if(bps+shift == 8) {
1220 if(is_unsigned_samples) {
1221 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1222 for(channel = 0; channel < channels; channel++, sample++)
1223 u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
1225 else {
1226 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1227 for(channel = 0; channel < channels; channel++, sample++)
1228 s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
1230 bytes_to_write = sample;
1232 else {
1233 FLAC__ASSERT(0);
1234 /* double protection */
1235 decoder_session->abort_flag = true;
1236 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1240 if(bytes_to_write > 0) {
1241 if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
1242 /* if a pipe closed when writing to stdout, we let it go without an error message */
1243 if(errno == EPIPE && decoder_session->fout == stdout)
1244 decoder_session->aborting_due_to_until = true;
1245 decoder_session->abort_flag = true;
1246 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1249 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1252 void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1254 DecoderSession *decoder_session = (DecoderSession*)client_data;
1256 if(decoder_session->analysis_mode)
1257 FLAC__stream_decoder_get_decode_position(decoder, &decoder_session->decode_position);
1259 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
1260 FLAC__uint64 skip, until;
1261 decoder_session->got_stream_info = true;
1262 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);
1263 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1264 decoder_session->channels = metadata->data.stream_info.channels;
1265 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1267 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
1268 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1269 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1271 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1272 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1273 flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1274 decoder_session->abort_flag = true;
1275 return;
1277 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1278 flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1279 decoder_session->abort_flag = true;
1280 return;
1282 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1283 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1285 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1286 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1287 decoder_session->abort_flag = true;
1288 return;
1290 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1291 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1293 if(until > 0) {
1294 FLAC__ASSERT(decoder_session->total_samples != 0);
1295 FLAC__ASSERT(0 == decoder_session->cue_specification);
1296 decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1299 if(decoder_session->bps < 4 || decoder_session->bps > 24) {
1300 flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 4-24\n", decoder_session->inbasefilename, decoder_session->bps);
1301 decoder_session->abort_flag = true;
1302 return;
1305 else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1306 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1307 if(decoder_session->total_samples == 0) {
1308 flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1309 decoder_session->abort_flag = true;
1310 return;
1313 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);
1315 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1316 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1318 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1319 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1321 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1322 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1323 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1324 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1326 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1328 else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1329 if (decoder_session->replaygain.spec.apply) {
1330 double reference, gain, peak;
1331 if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
1332 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");
1333 if(decoder_session->treat_warnings_as_errors) {
1334 decoder_session->abort_flag = true;
1335 return;
1338 else {
1339 const char *ls[] = { "no", "peak", "hard" };
1340 const char *ns[] = { "no", "low", "medium", "high" };
1341 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1342 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1343 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1344 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]);
1345 flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1346 /* don't check if(decoder_session->treat_warnings_as_errors) because the user explicitly asked for it */
1349 (void)flac__utils_get_channel_mask_tag(metadata, &decoder_session->channel_mask);
1353 void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1355 DecoderSession *decoder_session = (DecoderSession*)client_data;
1356 (void)decoder;
1357 if(!decoder_session->error_callback_suppress_messages)
1358 stats_print_name(1, decoder_session->inbasefilename);
1359 flac__utils_printf(stderr, 1, "*** Got error code %d:%s\n", status, FLAC__StreamDecoderErrorStatusString[status]);
1360 if(!decoder_session->continue_through_decode_errors) {
1361 /* if we got a sync error while looking for metadata, either it's not a FLAC file (more likely) or the file is corrupted */
1363 !decoder_session->error_callback_suppress_messages &&
1364 status == FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC &&
1365 FLAC__stream_decoder_get_state(decoder) == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
1367 flac__utils_printf(stderr, 1,
1368 "\n"
1369 "The input file is either not a FLAC file or is corrupted. If you are\n"
1370 "convinced it is a FLAC file, you can rerun the same command and add the\n"
1371 "-F parameter to try and recover as much as possible from the file.\n"
1373 decoder_session->error_callback_suppress_messages = true;
1375 else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1376 decoder_session->aborting_due_to_unparseable = true;
1377 decoder_session->abort_flag = true;
1381 void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
1383 const int ilen = strlen(d->inbasefilename) + 1;
1385 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1387 flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
1389 /* print out some more info for some errors: */
1390 if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
1391 flac__utils_printf(stderr, 1,
1392 "\n"
1393 "An error occurred opening the input file; it is likely that it does not exist\n"
1394 "or is not readable.\n"
1399 void print_error_with_state(const DecoderSession *d, const char *message)
1401 const int ilen = strlen(d->inbasefilename) + 1;
1403 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1404 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", FLAC__stream_decoder_get_resolved_state_string(d->decoder));
1406 /* print out some more info for some errors: */
1407 if (d->aborting_due_to_unparseable) {
1408 flac__utils_printf(stderr, 1,
1409 "\n"
1410 "The FLAC stream may have been created by a more advanced encoder. Try\n"
1411 " metaflac --show-vendor-tag %s\n"
1412 "If the version number is greater than %s, this decoder is probably\n"
1413 "not able to decode the file. If the version number is not, the file\n"
1414 "may be corrupted, or you may have found a bug. In this case please\n"
1415 "submit a bug report to\n"
1416 " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
1417 "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1418 d->inbasefilename, FLAC__VERSION_STRING
1423 void print_stats(const DecoderSession *decoder_session)
1425 if(flac__utils_verbosity_ >= 2) {
1426 #if defined _MSC_VER || defined __MINGW32__
1427 /* with MSVC you have to spoon feed it the casting */
1428 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1429 #else
1430 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1431 #endif
1433 if(decoder_session->total_samples > 0) {
1434 if ((unsigned)floor(progress + 0.5) == 100)
1435 return;
1437 stats_print_name(2, decoder_session->inbasefilename);
1438 stats_print_info(2, "%s%u%% complete",
1439 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1440 (unsigned)floor(progress + 0.5)
1443 else {
1444 stats_print_name(2, decoder_session->inbasefilename);
1445 stats_print_info(2, "%s %" PRIu64 " samples",
1446 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1447 decoder_session->samples_processed