1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006 Josh Coalson
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 #if defined _WIN32 && !defined __CYGWIN__
24 /* where MSVC puts unlink() */
29 #if defined _MSC_VER || defined __MINGW32__
30 #include <sys/types.h> /* for off_t */
31 #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"
50 FLAC__bool is_aiff_out;
51 FLAC__bool is_wave_out;
52 FLAC__bool continue_through_decode_errors;
53 FLAC__bool channel_map_none;
56 replaygain_synthesis_spec_t spec;
57 FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */
59 DitherContext dither_context;
63 FLAC__bool analysis_mode;
64 analysis_options aopts;
65 utils__SkipUntilSpecification *skip_specification;
66 utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
67 utils__CueSpecification *cue_specification;
69 const char *inbasefilename;
70 const char *outfilename;
72 FLAC__uint64 samples_processed;
73 unsigned frame_counter;
74 FLAC__bool abort_flag;
75 FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
76 FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */
78 FLAC__bool iff_headers_need_fixup;
80 FLAC__bool is_big_endian;
81 FLAC__bool is_unsigned_samples;
82 FLAC__bool got_stream_info;
83 FLAC__bool has_md5sum;
84 FLAC__uint64 total_samples;
88 FLAC__uint32 channel_mask;
90 /* these are used only in analyze mode */
91 FLAC__uint64 decode_position;
93 FLAC__StreamDecoder *decoder;
99 static FLAC__bool is_big_endian_host_;
105 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, 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, const char *infilename, const char *outfilename);
106 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
107 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, decode_options_t decode_options, const char *infilename);
108 static FLAC__bool DecoderSession_process(DecoderSession *d);
109 static int DecoderSession_finish_ok(DecoderSession *d);
110 static int DecoderSession_finish_error(DecoderSession *d);
111 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
112 static FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples);
113 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
114 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
115 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
116 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
117 static FLAC__bool write_sane_extended(FILE *f, unsigned val);
118 static FLAC__bool fixup_iff_headers(DecoderSession *d);
119 static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
120 static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
121 static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
122 static void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status);
123 static void print_error_with_state(const DecoderSession *d, const char *message);
124 static void print_stats(const DecoderSession *decoder_session);
130 int flac__decode_aiff(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
132 DecoderSession decoder_session;
135 DecoderSession_construct(
138 options.common.is_ogg,
142 /*is_aiff_out=*/true,
143 /*is_wave_out=*/false,
144 options.common.continue_through_decode_errors,
145 options.common.channel_map_none,
146 options.common.replaygain_synthesis_spec,
149 &options.common.skip_specification,
150 &options.common.until_specification,
151 options.common.has_cue_specification? &options.common.cue_specification : 0,
158 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
159 return DecoderSession_finish_error(&decoder_session);
161 if(!DecoderSession_process(&decoder_session))
162 return DecoderSession_finish_error(&decoder_session);
164 return DecoderSession_finish_ok(&decoder_session);
167 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
169 DecoderSession decoder_session;
172 DecoderSession_construct(
175 options.common.is_ogg,
179 /*is_aiff_out=*/false,
180 /*is_wave_out=*/true,
181 options.common.continue_through_decode_errors,
182 options.common.channel_map_none,
183 options.common.replaygain_synthesis_spec,
186 &options.common.skip_specification,
187 &options.common.until_specification,
188 options.common.has_cue_specification? &options.common.cue_specification : 0,
195 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
196 return DecoderSession_finish_error(&decoder_session);
198 if(!DecoderSession_process(&decoder_session))
199 return DecoderSession_finish_error(&decoder_session);
201 return DecoderSession_finish_ok(&decoder_session);
204 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
206 DecoderSession decoder_session;
208 decoder_session.is_big_endian = options.is_big_endian;
209 decoder_session.is_unsigned_samples = options.is_unsigned_samples;
212 DecoderSession_construct(
215 options.common.is_ogg,
219 /*is_aiff_out=*/false,
220 /*is_wave_out=*/false,
221 options.common.continue_through_decode_errors,
222 options.common.channel_map_none,
223 options.common.replaygain_synthesis_spec,
226 &options.common.skip_specification,
227 &options.common.until_specification,
228 options.common.has_cue_specification? &options.common.cue_specification : 0,
235 if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
236 return DecoderSession_finish_error(&decoder_session);
238 if(!DecoderSession_process(&decoder_session))
239 return DecoderSession_finish_error(&decoder_session);
241 return DecoderSession_finish_ok(&decoder_session);
244 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, 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, const char *infilename, const char *outfilename)
252 d->is_aiff_out = is_aiff_out;
253 d->is_wave_out = is_wave_out;
254 d->continue_through_decode_errors = continue_through_decode_errors;
255 d->channel_map_none = channel_map_none;
256 d->replaygain.spec = replaygain_synthesis_spec;
257 d->replaygain.apply = false;
258 d->replaygain.scale = 0.0;
259 /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
260 d->test_only = (0 == outfilename);
261 d->analysis_mode = analysis_mode;
263 d->skip_specification = skip_specification;
264 d->until_specification = until_specification;
265 d->cue_specification = cue_specification;
267 d->inbasefilename = grabbag__file_get_basename(infilename);
268 d->outfilename = outfilename;
270 d->samples_processed = 0;
271 d->frame_counter = 0;
272 d->abort_flag = false;
273 d->aborting_due_to_until = false;
274 d->aborting_due_to_unparseable = false;
276 d->iff_headers_need_fixup = false;
278 d->total_samples = 0;
279 d->got_stream_info = false;
280 d->has_md5sum = false;
286 d->decode_position = 0;
290 d->fout = 0; /* initialized with an open file later if necessary */
292 FLAC__ASSERT(!(d->test_only && d->analysis_mode));
295 if(0 == strcmp(outfilename, "-")) {
296 d->fout = grabbag__file_get_binary_stdout();
299 if(0 == (d->fout = fopen(outfilename, "wb"))) {
300 flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
301 DecoderSession_destroy(d, /*error_occurred=*/true);
308 flac__analyze_init(aopts);
313 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
315 if(0 != d->fout && d->fout != stdout) {
318 unlink(d->outfilename);
322 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, decode_options_t decode_options, const char *infilename)
324 FLAC__StreamDecoderInitStatus init_status;
325 FLAC__uint32 test = 1;
327 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
329 decoder_session->decoder = FLAC__stream_decoder_new();
331 if(0 == decoder_session->decoder) {
332 flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
336 FLAC__stream_decoder_set_md5_checking(decoder_session->decoder, true);
337 if (0 != decoder_session->cue_specification)
338 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_CUESHEET);
339 if (decoder_session->replaygain.spec.apply)
340 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
343 if(decoder_session->is_ogg) {
344 if(!decode_options.use_first_serial_number)
345 FLAC__stream_decoder_set_ogg_serial_number(decoder_session->decoder, decode_options.serial_number);
346 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);
350 (void)decode_options;
353 init_status = FLAC__stream_decoder_init_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
356 if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
357 print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
364 FLAC__bool DecoderSession_process(DecoderSession *d)
366 if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder)) {
367 flac__utils_printf(stderr, 2, "\n");
368 print_error_with_state(d, "ERROR while decoding metadata");
371 if(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM) {
372 flac__utils_printf(stderr, 2, "\n");
373 print_error_with_state(d, "ERROR during metadata decoding");
374 if(!d->continue_through_decode_errors)
381 /* set channel mapping */
382 if(!d->channel_map_none) {
383 /* currently FLAC order matches SMPTE/WAVEFORMATEXTENSIBLE order, so no reordering is necessary; see encode.c */
384 /* only the channel mask must be set if it was not already picked up from the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag */
385 if(d->channels == 1) {
386 if(d->channel_mask == 0)
387 d->channel_mask = 0x0001;
389 else if(d->channels == 2) {
390 if(d->channel_mask == 0)
391 d->channel_mask = 0x0003;
393 else if(d->channels == 3) {
394 if(d->channel_mask == 0)
395 d->channel_mask = 0x0007;
397 else if(d->channels == 4) {
398 if(d->channel_mask == 0)
399 d->channel_mask = 0x0033;
401 else if(d->channels == 5) {
402 if(d->channel_mask == 0)
403 d->channel_mask = 0x0607;
405 else if(d->channels == 6) {
406 if(d->channel_mask == 0)
407 d->channel_mask = 0x060f;
411 /* write the WAVE/AIFF headers if necessary */
412 if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out)) {
413 if(!write_iff_headers(d->fout, d, d->total_samples)) {
414 d->abort_flag = true;
419 if(d->skip_specification->value.samples > 0) {
420 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
422 if(!FLAC__stream_decoder_seek_absolute(d->decoder, skip)) {
423 print_error_with_state(d, "ERROR seeking while skipping bytes");
427 if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder) && !d->aborting_due_to_until) {
428 flac__utils_printf(stderr, 2, "\n");
429 print_error_with_state(d, "ERROR while decoding data");
430 if(!d->continue_through_decode_errors)
434 (d->abort_flag && !(d->aborting_due_to_until || d->continue_through_decode_errors)) ||
435 (FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until)
437 flac__utils_printf(stderr, 2, "\n");
438 print_error_with_state(d, "ERROR during decoding");
442 if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out) && ((d->total_samples * d->channels * ((d->bps+7)/8)) & 1)) {
443 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
444 print_error_with_state(d, d->is_wave_out?
445 "ERROR writing pad byte to WAVE data chunk" :
446 "ERROR writing pad byte to AIFF SSND chunk"
455 int DecoderSession_finish_ok(DecoderSession *d)
457 FLAC__bool ok = true, md5_failure = false;
460 md5_failure = !FLAC__stream_decoder_finish(d->decoder) && !d->aborting_due_to_until;
462 FLAC__stream_decoder_delete(d->decoder);
465 flac__analyze_finish(d->aopts);
467 flac__utils_printf(stderr, 1, "\r%s: ERROR, MD5 signature mismatch\n", d->inbasefilename);
468 ok = d->continue_through_decode_errors;
471 if(!d->got_stream_info) {
472 flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since there was no STREAMINFO\n", d->inbasefilename);
474 else if(!d->has_md5sum) {
475 flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since it was unset in the STREAMINFO\n", d->inbasefilename);
477 flac__utils_printf(stderr, 2, "\r%s: %s \n", d->inbasefilename, d->test_only? "ok ":d->analysis_mode?"done ":"done");
479 DecoderSession_destroy(d, /*error_occurred=*/!ok);
480 if(!d->test_only && (d->is_wave_out || d->is_aiff_out) && (d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))))
481 if(!fixup_iff_headers(d))
486 int DecoderSession_finish_error(DecoderSession *d)
489 (void)FLAC__stream_decoder_finish(d->decoder);
490 FLAC__stream_decoder_delete(d->decoder);
493 flac__analyze_finish(d->aopts);
494 DecoderSession_destroy(d, /*error_occurred=*/true);
498 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
500 /* convert from mm:ss.sss to sample number if necessary */
501 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
503 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
504 if(spec->is_relative && spec->value.samples == 0) {
505 spec->is_relative = false;
509 /* in any other case the total samples in the input must be known */
510 if(total_samples_in_input == 0) {
511 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
515 FLAC__ASSERT(spec->value_is_samples);
517 /* convert relative specifications to absolute */
518 if(spec->is_relative) {
519 if(spec->value.samples <= 0)
520 spec->value.samples += (FLAC__int64)total_samples_in_input;
522 spec->value.samples += skip;
523 spec->is_relative = false;
527 if(spec->value.samples < 0) {
528 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
531 if((FLAC__uint64)spec->value.samples <= skip) {
532 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
535 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
536 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
543 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
545 const char *fmt_desc = decoder_session->is_wave_out? "WAVE" : "AIFF";
546 const FLAC__bool is_waveformatextensible = decoder_session->is_wave_out && (decoder_session->channel_mask == 2 || decoder_session->channel_mask > 3 || decoder_session->bps%8 || decoder_session->channels > 2);
547 FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
548 const FLAC__uint32 aligned_data_size = (FLAC__uint32)((data_size+1) & (~1U)); /* we'll check for overflow later */
551 flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
552 flac__utils_printf(stderr, 1, " Generated %s file will have a data chunk size of 0. Try\n", fmt_desc);
553 flac__utils_printf(stderr, 1, " decoding directly to a file instead.\n");
556 decoder_session->iff_headers_need_fixup = true;
559 if(data_size >= 0xFFFFFFDC) {
560 flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file chunk\n", decoder_session->inbasefilename, fmt_desc);
563 if(decoder_session->is_wave_out) {
564 if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
567 if(!write_little_endian_uint32(f, aligned_data_size+(is_waveformatextensible?60:36))) /* filesize-8 */
570 if(flac__utils_fwrite("WAVEfmt ", 1, 8, f) != 8)
573 if(!write_little_endian_uint32(f, is_waveformatextensible? 40 : 16)) /* chunk size */
576 if(!write_little_endian_uint16(f, (FLAC__uint16)(is_waveformatextensible? 65534 : 1))) /* compression code */
579 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
582 if(!write_little_endian_uint32(f, decoder_session->sample_rate))
585 if(!write_little_endian_uint32(f, decoder_session->sample_rate * decoder_session->channels * ((decoder_session->bps+7) / 8)))
588 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels * ((decoder_session->bps+7) / 8)))) /* block align */
591 if(!write_little_endian_uint16(f, (FLAC__uint16)(((decoder_session->bps+7)/8)*8))) /* bits per sample */
594 if(is_waveformatextensible) {
595 if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */
598 if(!write_little_endian_uint16(f, (FLAC__uint16)decoder_session->bps)) /* validBitsPerSample */
601 if(!write_little_endian_uint32(f, decoder_session->channel_mask))
604 /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */
605 if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16)
609 if(flac__utils_fwrite("data", 1, 4, f) != 4)
612 if(!write_little_endian_uint32(f, (FLAC__uint32)data_size)) /* data size */
616 if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
619 if(!write_big_endian_uint32(f, aligned_data_size+46)) /* filesize-8 */
622 if(flac__utils_fwrite("AIFFCOMM", 1, 8, f) != 8)
625 if(flac__utils_fwrite("\000\000\000\022", 1, 4, f) != 4) /* chunk size = 18 */
628 if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
631 if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
634 if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->bps)))
637 if(!write_sane_extended(f, decoder_session->sample_rate))
640 if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
643 if(!write_big_endian_uint32(f, (FLAC__uint32)data_size+8)) /* data size */
646 if(!write_big_endian_uint32(f, 0/*offset*/))
649 if(!write_big_endian_uint32(f, 0/*block_size*/))
656 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
658 FLAC__byte *b = (FLAC__byte*)(&val);
659 if(is_big_endian_host_) {
661 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
663 return flac__utils_fwrite(b, 1, 2, f) == 2;
666 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
668 FLAC__byte *b = (FLAC__byte*)(&val);
669 if(is_big_endian_host_) {
671 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
672 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
674 return flac__utils_fwrite(b, 1, 4, f) == 4;
677 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
679 FLAC__byte *b = (FLAC__byte*)(&val);
680 if(!is_big_endian_host_) {
682 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
684 return flac__utils_fwrite(b, 1, 2, f) == 2;
687 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
689 FLAC__byte *b = (FLAC__byte*)(&val);
690 if(!is_big_endian_host_) {
692 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
693 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
695 return flac__utils_fwrite(b, 1, 4, f) == 4;
698 FLAC__bool write_sane_extended(FILE *f, unsigned val)
699 /* Write to 'f' a SANE extended representation of 'val'. Return false if
700 * the write succeeds; return true otherwise.
702 * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
703 * of exponent, and 64 bits of significand (mantissa). Unlike most IEEE-754
704 * representations, it does not imply a 1 above the MSB of the significand.
710 unsigned int shift, exponent;
712 FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
714 for(shift= 0U; (val>>(31-shift))==0U; ++shift)
717 exponent= 63U-(shift+32U); /* add 32 for unused second word */
719 if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
721 if(!write_big_endian_uint32(f, val))
723 if(!write_big_endian_uint32(f, 0)) /* unused second word */
729 FLAC__bool fixup_iff_headers(DecoderSession *d)
731 const char *fmt_desc = (d->is_wave_out? "WAVE" : "AIFF");
732 FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
735 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));
739 if(!write_iff_headers(f, d, d->samples_processed)) {
748 FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
750 DecoderSession *decoder_session = (DecoderSession*)client_data;
751 FILE *fout = decoder_session->fout;
752 const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
753 const unsigned shift = ((decoder_session->is_wave_out || decoder_session->is_aiff_out) && (bps%8)? 8-(bps%8): 0);
754 FLAC__bool is_big_endian = (decoder_session->is_aiff_out? true : (decoder_session->is_wave_out? false : decoder_session->is_big_endian));
755 FLAC__bool is_unsigned_samples = (decoder_session->is_aiff_out? false : (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples));
756 unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
757 static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
758 FLAC__uint8 *u8buffer = (FLAC__uint8 *)s8buffer;
759 FLAC__int16 *s16buffer = (FLAC__int16 *)s8buffer;
760 FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
761 FLAC__int32 *s32buffer = (FLAC__int32 *)s8buffer;
762 FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
763 size_t bytes_to_write = 0;
767 if(decoder_session->abort_flag)
768 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
770 /* sanity-check the bits-per-sample */
771 if(decoder_session->bps) {
772 if(bps != decoder_session->bps) {
773 if(decoder_session->got_stream_info)
774 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);
776 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);
777 if(!decoder_session->continue_through_decode_errors)
778 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
782 /* must not have gotten STREAMINFO, save the bps from the frame header */
783 FLAC__ASSERT(!decoder_session->got_stream_info);
784 decoder_session->bps = bps;
787 /* sanity-check the #channels */
788 if(decoder_session->channels) {
789 if(channels != decoder_session->channels) {
790 if(decoder_session->got_stream_info)
791 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
793 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);
794 if(!decoder_session->continue_through_decode_errors)
795 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
799 /* must not have gotten STREAMINFO, save the #channels from the frame header */
800 FLAC__ASSERT(!decoder_session->got_stream_info);
801 decoder_session->channels = channels;
804 /* sanity-check the sample rate */
805 if(decoder_session->sample_rate) {
806 if(frame->header.sample_rate != decoder_session->sample_rate) {
807 if(decoder_session->got_stream_info)
808 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);
810 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);
811 if(!decoder_session->continue_through_decode_errors)
812 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
816 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
817 FLAC__ASSERT(!decoder_session->got_stream_info);
818 decoder_session->sample_rate = frame->header.sample_rate;
822 * limit the number of samples to accept based on --until
824 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
825 /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
826 if(decoder_session->skip_specification->is_relative) {
827 if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
828 decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
830 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);
831 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
834 if(decoder_session->until_specification->is_relative) {
835 if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
836 decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
838 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);
839 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
842 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
843 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
844 if(decoder_session->until_specification->value.samples > 0) {
845 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
846 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
847 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
848 FLAC__ASSERT(until >= input_samples_passed);
849 if(input_samples_passed + wide_samples > until)
850 wide_samples = (unsigned)(until - input_samples_passed);
851 if (wide_samples == 0) {
852 decoder_session->abort_flag = true;
853 decoder_session->aborting_due_to_until = true;
854 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
858 if(wide_samples > 0) {
859 decoder_session->samples_processed += wide_samples;
860 decoder_session->frame_counter++;
862 if(!(decoder_session->frame_counter & 0x3f))
863 print_stats(decoder_session);
865 if(decoder_session->analysis_mode) {
867 FLAC__stream_decoder_get_decode_position(decoder_session->decoder, &dpos);
868 flac__analyze_frame(frame, decoder_session->frame_counter-1, (unsigned)(dpos-decoder_session->decode_position), decoder_session->aopts, fout);
869 decoder_session->decode_position = dpos;
871 else if(!decoder_session->test_only) {
872 if(shift && !decoder_session->replaygain.apply) {
873 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
874 for(channel = 0; channel < channels; channel++)
875 ((FLAC__int32**)buffer)[channel][wide_sample] <<= shift;/*@@@@@@un-const'ing the buffer is hacky but safe*/
877 if(decoder_session->replaygain.apply) {
878 bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
885 bps, /* source_bps */
886 bps+shift, /* target_bps */
887 decoder_session->replaygain.scale,
888 decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
889 decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
890 &decoder_session->replaygain.dither_context
893 else if(bps+shift == 8) {
894 if(is_unsigned_samples) {
895 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
896 for(channel = 0; channel < channels; channel++, sample++)
897 u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
900 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
901 for(channel = 0; channel < channels; channel++, sample++)
902 s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
904 bytes_to_write = sample;
906 else if(bps+shift == 16) {
907 if(is_unsigned_samples) {
908 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
909 for(channel = 0; channel < channels; channel++, sample++)
910 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
913 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
914 for(channel = 0; channel < channels; channel++, sample++)
915 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
917 if(is_big_endian != is_big_endian_host_) {
919 const unsigned bytes = sample * 2;
920 for(byte = 0; byte < bytes; byte += 2) {
921 tmp = u8buffer[byte];
922 u8buffer[byte] = u8buffer[byte+1];
923 u8buffer[byte+1] = tmp;
926 bytes_to_write = 2 * sample;
928 else if(bps+shift == 24) {
929 if(is_unsigned_samples) {
930 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
931 for(channel = 0; channel < channels; channel++, sample++)
932 u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
935 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
936 for(channel = 0; channel < channels; channel++, sample++)
937 s32buffer[sample] = buffer[channel][wide_sample];
939 if(is_big_endian != is_big_endian_host_) {
941 const unsigned bytes = sample * 4;
942 for(byte = 0; byte < bytes; byte += 4) {
943 tmp = u8buffer[byte];
944 u8buffer[byte] = u8buffer[byte+3];
945 u8buffer[byte+3] = tmp;
946 tmp = u8buffer[byte+1];
947 u8buffer[byte+1] = u8buffer[byte+2];
948 u8buffer[byte+2] = tmp;
953 const unsigned bytes = sample * 4;
954 for(lbyte = byte = 0; byte < bytes; ) {
956 u8buffer[lbyte++] = u8buffer[byte++];
957 u8buffer[lbyte++] = u8buffer[byte++];
958 u8buffer[lbyte++] = u8buffer[byte++];
963 const unsigned bytes = sample * 4;
964 for(lbyte = byte = 0; byte < bytes; ) {
965 u8buffer[lbyte++] = u8buffer[byte++];
966 u8buffer[lbyte++] = u8buffer[byte++];
967 u8buffer[lbyte++] = u8buffer[byte++];
971 bytes_to_write = 3 * sample;
975 /* double protection */
976 decoder_session->abort_flag = true;
977 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
981 if(bytes_to_write > 0) {
982 if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
983 /* if a pipe closed when writing to stdout, we let it go without an error message */
984 if(errno == EPIPE && decoder_session->fout == stdout)
985 decoder_session->aborting_due_to_until = true;
986 decoder_session->abort_flag = true;
987 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
990 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
993 void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
995 DecoderSession *decoder_session = (DecoderSession*)client_data;
997 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
998 FLAC__uint64 skip, until;
999 decoder_session->got_stream_info = true;
1000 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);
1001 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1002 decoder_session->channels = metadata->data.stream_info.channels;
1003 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1005 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
1006 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1007 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1009 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1010 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1011 flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1012 decoder_session->abort_flag = true;
1015 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1016 flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1017 decoder_session->abort_flag = true;
1020 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1021 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1023 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1024 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1025 decoder_session->abort_flag = true;
1028 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1029 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1032 FLAC__ASSERT(decoder_session->total_samples != 0);
1033 FLAC__ASSERT(0 == decoder_session->cue_specification);
1034 decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1037 if(decoder_session->bps < 4 || decoder_session->bps > 24) {
1038 flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 4-24\n", decoder_session->inbasefilename, decoder_session->bps);
1039 decoder_session->abort_flag = true;
1043 else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1044 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1045 if(decoder_session->total_samples == 0) {
1046 flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1047 decoder_session->abort_flag = true;
1051 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);
1053 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1054 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1056 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1057 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1059 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1060 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1061 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1062 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1064 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1066 else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1067 if (decoder_session->replaygain.spec.apply) {
1068 double reference, gain, peak;
1069 if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
1070 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");
1073 const char *ls[] = { "no", "peak", "hard" };
1074 const char *ns[] = { "no", "low", "medium", "high" };
1075 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1076 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1077 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1078 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]);
1079 flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1082 (void)flac__utils_get_channel_mask_tag(metadata, &decoder_session->channel_mask);
1086 void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1088 DecoderSession *decoder_session = (DecoderSession*)client_data;
1090 flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1091 if(!decoder_session->continue_through_decode_errors) {
1092 decoder_session->abort_flag = true;
1093 if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1094 decoder_session->aborting_due_to_unparseable = true;
1098 void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
1100 const int ilen = strlen(d->inbasefilename) + 1;
1102 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1104 flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
1106 /* print out some more info for some errors: */
1107 if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
1108 flac__utils_printf(stderr, 1,
1110 "An error occurred opening the input file; it is likely that it does not exist\n"
1111 "or is not readable.\n"
1116 void print_error_with_state(const DecoderSession *d, const char *message)
1118 const int ilen = strlen(d->inbasefilename) + 1;
1120 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1121 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", FLAC__stream_decoder_get_resolved_state_string(d->decoder));
1123 /* print out some more info for some errors: */
1124 if (d->aborting_due_to_unparseable) {
1125 flac__utils_printf(stderr, 1,
1127 "The FLAC stream may have been created by a more advanced encoder. Try\n"
1128 " metaflac --show-vendor-tag %s\n"
1129 "If the version number is greater than %s, this decoder is probably\n"
1130 "not able to decode the file. If the version number is not, the file\n"
1131 "may be corrupted, or you may have found a bug. In this case please\n"
1132 "submit a bug report to\n"
1133 " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
1134 "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1135 d->inbasefilename, FLAC__VERSION_STRING
1140 void print_stats(const DecoderSession *decoder_session)
1142 if(flac__utils_verbosity_ >= 2) {
1143 #if defined _MSC_VER || defined __MINGW32__
1144 /* with MSVC you have to spoon feed it the casting */
1145 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1147 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1149 if(decoder_session->total_samples > 0) {
1150 fprintf(stderr, "\r%s: %s%u%% complete",
1151 decoder_session->inbasefilename,
1152 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1153 (unsigned)floor(progress + 0.5)
1157 fprintf(stderr, "\r%s: %s %u samples",
1158 decoder_session->inbasefilename,
1159 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1160 (unsigned)decoder_session->samples_processed