1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007 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"
45 #ifdef TARGET_MSDOS /* @@@ [2G limit] */
53 FLAC__bool use_first_serial_number;
57 FLAC__bool is_aiff_out;
58 FLAC__bool is_wave_out;
59 FLAC__bool treat_warnings_as_errors;
60 FLAC__bool continue_through_decode_errors;
61 FLAC__bool channel_map_none;
64 replaygain_synthesis_spec_t spec;
65 FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */
67 DitherContext dither_context;
71 FLAC__bool analysis_mode;
72 analysis_options aopts;
73 utils__SkipUntilSpecification *skip_specification;
74 utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
75 utils__CueSpecification *cue_specification;
77 const char *inbasefilename;
78 const char *infilename;
79 const char *outfilename;
81 FLAC__uint64 samples_processed;
82 unsigned frame_counter;
83 FLAC__bool abort_flag;
84 FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
85 FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */
87 FLAC__bool iff_headers_need_fixup;
89 FLAC__bool is_big_endian;
90 FLAC__bool is_unsigned_samples;
91 FLAC__bool got_stream_info;
92 FLAC__bool has_md5sum;
93 FLAC__uint64 total_samples;
97 FLAC__uint32 channel_mask;
99 /* these are used only in analyze mode */
100 FLAC__uint64 decode_position;
102 FLAC__StreamDecoder *decoder;
106 foreign_metadata_t *foreign_metadata; /* NULL unless --keep-foreign-metadata requested */
107 off_t fm_offset1, fm_offset2, fm_offset3;
111 static FLAC__bool is_big_endian_host_;
117 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool use_first_serial_number, long serial_number, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, 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);
118 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
119 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, const char *infilename);
120 static FLAC__bool DecoderSession_process(DecoderSession *d);
121 static int DecoderSession_finish_ok(DecoderSession *d);
122 static int DecoderSession_finish_error(DecoderSession *d);
123 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
124 static FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples);
125 static FLAC__bool write_riff_wave_fmt_chunk(FILE *f, FLAC__bool is_waveformatextensible, unsigned bps, unsigned channels, unsigned sample_rate, FLAC__uint32 channel_mask);
126 static FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate);
127 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
128 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
129 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
130 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
131 static FLAC__bool write_sane_extended(FILE *f, unsigned val);
132 static FLAC__bool fixup_iff_headers(DecoderSession *d);
133 static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
134 static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
135 static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
136 static void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status);
137 static void print_error_with_state(const DecoderSession *d, const char *message);
138 static void print_stats(const DecoderSession *decoder_session);
144 int flac__decode_aiff(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
146 DecoderSession decoder_session;
149 DecoderSession_construct(
152 options.common.is_ogg,
153 options.common.use_first_serial_number,
154 options.common.serial_number,
157 /*use_first_serial_number=*/false,
160 /*is_aiff_out=*/true,
161 /*is_wave_out=*/false,
162 options.common.treat_warnings_as_errors,
163 options.common.continue_through_decode_errors,
164 options.common.channel_map_none,
165 options.common.replaygain_synthesis_spec,
168 &options.common.skip_specification,
169 &options.common.until_specification,
170 options.common.has_cue_specification? &options.common.cue_specification : 0,
171 options.foreign_metadata,
178 if(!DecoderSession_init_decoder(&decoder_session, infilename))
179 return DecoderSession_finish_error(&decoder_session);
181 if(!DecoderSession_process(&decoder_session))
182 return DecoderSession_finish_error(&decoder_session);
184 return DecoderSession_finish_ok(&decoder_session);
187 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
189 DecoderSession decoder_session;
192 DecoderSession_construct(
195 options.common.is_ogg,
196 options.common.use_first_serial_number,
197 options.common.serial_number,
200 /*use_first_serial_number=*/false,
203 /*is_aiff_out=*/false,
204 /*is_wave_out=*/true,
205 options.common.treat_warnings_as_errors,
206 options.common.continue_through_decode_errors,
207 options.common.channel_map_none,
208 options.common.replaygain_synthesis_spec,
211 &options.common.skip_specification,
212 &options.common.until_specification,
213 options.common.has_cue_specification? &options.common.cue_specification : 0,
214 options.foreign_metadata,
221 if(!DecoderSession_init_decoder(&decoder_session, infilename))
222 return DecoderSession_finish_error(&decoder_session);
224 if(!DecoderSession_process(&decoder_session))
225 return DecoderSession_finish_error(&decoder_session);
227 return DecoderSession_finish_ok(&decoder_session);
230 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
232 DecoderSession decoder_session;
234 decoder_session.is_big_endian = options.is_big_endian;
235 decoder_session.is_unsigned_samples = options.is_unsigned_samples;
238 DecoderSession_construct(
241 options.common.is_ogg,
242 options.common.use_first_serial_number,
243 options.common.serial_number,
246 /*use_first_serial_number=*/false,
249 /*is_aiff_out=*/false,
250 /*is_wave_out=*/false,
251 options.common.treat_warnings_as_errors,
252 options.common.continue_through_decode_errors,
253 options.common.channel_map_none,
254 options.common.replaygain_synthesis_spec,
257 &options.common.skip_specification,
258 &options.common.until_specification,
259 options.common.has_cue_specification? &options.common.cue_specification : 0,
260 /*foreign_metadata=*/NULL,
267 if(!DecoderSession_init_decoder(&decoder_session, infilename))
268 return DecoderSession_finish_error(&decoder_session);
270 if(!DecoderSession_process(&decoder_session))
271 return DecoderSession_finish_error(&decoder_session);
273 return DecoderSession_finish_ok(&decoder_session);
276 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool use_first_serial_number, long serial_number, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, 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)
280 d->use_first_serial_number = use_first_serial_number;
281 d->serial_number = serial_number;
284 (void)use_first_serial_number;
288 d->is_aiff_out = is_aiff_out;
289 d->is_wave_out = is_wave_out;
290 d->treat_warnings_as_errors = treat_warnings_as_errors;
291 d->continue_through_decode_errors = continue_through_decode_errors;
292 d->channel_map_none = channel_map_none;
293 d->replaygain.spec = replaygain_synthesis_spec;
294 d->replaygain.apply = false;
295 d->replaygain.scale = 0.0;
296 /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
297 d->test_only = (0 == outfilename);
298 d->analysis_mode = analysis_mode;
300 d->skip_specification = skip_specification;
301 d->until_specification = until_specification;
302 d->cue_specification = cue_specification;
304 d->inbasefilename = grabbag__file_get_basename(infilename);
305 d->infilename = infilename;
306 d->outfilename = outfilename;
308 d->samples_processed = 0;
309 d->frame_counter = 0;
310 d->abort_flag = false;
311 d->aborting_due_to_until = false;
312 d->aborting_due_to_unparseable = false;
314 d->iff_headers_need_fixup = false;
316 d->total_samples = 0;
317 d->got_stream_info = false;
318 d->has_md5sum = false;
324 d->decode_position = 0;
328 d->fout = 0; /* initialized with an open file later if necessary */
330 d->foreign_metadata = foreign_metadata;
332 FLAC__ASSERT(!(d->test_only && d->analysis_mode));
335 if(0 == strcmp(outfilename, "-")) {
336 d->fout = grabbag__file_get_binary_stdout();
339 if(0 == (d->fout = fopen(outfilename, "wb"))) {
340 flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
341 DecoderSession_destroy(d, /*error_occurred=*/true);
348 flac__analyze_init(aopts);
353 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
355 if(0 != d->fout && d->fout != stdout) {
358 unlink(d->outfilename);
362 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, const char *infilename)
364 FLAC__StreamDecoderInitStatus init_status;
365 FLAC__uint32 test = 1;
367 is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
369 if(!decoder_session->analysis_mode && !decoder_session->test_only && (decoder_session->is_wave_out || decoder_session->is_aiff_out)) {
370 if(decoder_session->foreign_metadata) {
372 if(!flac__foreign_metadata_read_from_flac(decoder_session->foreign_metadata, infilename, &error)) {
373 flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", decoder_session->inbasefilename, error);
379 decoder_session->decoder = FLAC__stream_decoder_new();
381 if(0 == decoder_session->decoder) {
382 flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
386 FLAC__stream_decoder_set_md5_checking(decoder_session->decoder, true);
387 if (0 != decoder_session->cue_specification)
388 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_CUESHEET);
389 if (decoder_session->replaygain.spec.apply)
390 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
393 if(decoder_session->is_ogg) {
394 if(!decoder_session->use_first_serial_number)
395 FLAC__stream_decoder_set_ogg_serial_number(decoder_session->decoder, decoder_session->serial_number);
396 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);
401 init_status = FLAC__stream_decoder_init_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
404 if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
405 print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
412 FLAC__bool DecoderSession_process(DecoderSession *d)
414 if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder)) {
415 flac__utils_printf(stderr, 2, "\n");
416 print_error_with_state(d, "ERROR while decoding metadata");
419 if(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM) {
420 flac__utils_printf(stderr, 2, "\n");
421 print_error_with_state(d, "ERROR during metadata decoding");
422 if(!d->continue_through_decode_errors)
429 /* set channel mapping */
430 if(!d->channel_map_none) {
431 /* currently FLAC order matches SMPTE/WAVEFORMATEXTENSIBLE order, so no reordering is necessary; see encode.c */
432 /* only the channel mask must be set if it was not already picked up from the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag */
433 if(d->channels == 1) {
434 if(d->channel_mask == 0)
435 d->channel_mask = 0x0001;
437 else if(d->channels == 2) {
438 if(d->channel_mask == 0)
439 d->channel_mask = 0x0003;
441 else if(d->channels == 3) {
442 if(d->channel_mask == 0)
443 d->channel_mask = 0x0007;
445 else if(d->channels == 4) {
446 if(d->channel_mask == 0)
447 d->channel_mask = 0x0033;
449 else if(d->channels == 5) {
450 if(d->channel_mask == 0)
451 d->channel_mask = 0x0607;
453 else if(d->channels == 6) {
454 if(d->channel_mask == 0)
455 d->channel_mask = 0x060f;
459 /* write the WAVE/AIFF headers if necessary */
460 if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out)) {
461 if(!write_iff_headers(d->fout, d, d->total_samples)) {
462 d->abort_flag = true;
467 if(d->skip_specification->value.samples > 0) {
468 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
470 if(!FLAC__stream_decoder_seek_absolute(d->decoder, skip)) {
471 print_error_with_state(d, "ERROR seeking while skipping bytes");
475 if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder) && !d->aborting_due_to_until) {
476 flac__utils_printf(stderr, 2, "\n");
477 print_error_with_state(d, "ERROR while decoding data");
478 if(!d->continue_through_decode_errors)
482 (d->abort_flag && !(d->aborting_due_to_until || d->continue_through_decode_errors)) ||
483 (FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until)
485 flac__utils_printf(stderr, 2, "\n");
486 print_error_with_state(d, "ERROR during decoding");
490 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)) {
491 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
492 print_error_with_state(d, d->is_wave_out?
493 "ERROR writing pad byte to WAVE data chunk" :
494 "ERROR writing pad byte to AIFF SSND chunk"
503 int DecoderSession_finish_ok(DecoderSession *d)
505 FLAC__bool ok = true, md5_failure = false;
508 md5_failure = !FLAC__stream_decoder_finish(d->decoder) && !d->aborting_due_to_until;
510 FLAC__stream_decoder_delete(d->decoder);
513 flac__analyze_finish(d->aopts);
515 flac__utils_printf(stderr, 1, "\r%s: ERROR, MD5 signature mismatch\n", d->inbasefilename);
516 ok = d->continue_through_decode_errors;
519 if(!d->got_stream_info) {
520 flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since there was no STREAMINFO\n", d->inbasefilename);
521 ok = !d->treat_warnings_as_errors;
523 else if(!d->has_md5sum) {
524 flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since it was unset in the STREAMINFO\n", d->inbasefilename);
525 ok = !d->treat_warnings_as_errors;
527 flac__utils_printf(stderr, 2, "\r%s: %s \n", d->inbasefilename, d->test_only? "ok ":d->analysis_mode?"done ":"done");
529 DecoderSession_destroy(d, /*error_occurred=*/!ok);
530 if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out)) {
531 if(d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))) {
532 if(!fixup_iff_headers(d))
535 if(d->foreign_metadata) {
537 if(!flac__foreign_metadata_write_to_iff(d->foreign_metadata, d->infilename, d->outfilename, d->fm_offset1, d->fm_offset2, d->fm_offset3, &error)) {
538 flac__utils_printf(stderr, 1, "ERROR updating foreign metadata from %s to %s: %s\n", d->infilename, d->outfilename, error);
546 int DecoderSession_finish_error(DecoderSession *d)
549 (void)FLAC__stream_decoder_finish(d->decoder);
550 FLAC__stream_decoder_delete(d->decoder);
553 flac__analyze_finish(d->aopts);
554 DecoderSession_destroy(d, /*error_occurred=*/true);
558 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
560 /* convert from mm:ss.sss to sample number if necessary */
561 flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
563 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
564 if(spec->is_relative && spec->value.samples == 0) {
565 spec->is_relative = false;
569 /* in any other case the total samples in the input must be known */
570 if(total_samples_in_input == 0) {
571 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
575 FLAC__ASSERT(spec->value_is_samples);
577 /* convert relative specifications to absolute */
578 if(spec->is_relative) {
579 if(spec->value.samples <= 0)
580 spec->value.samples += (FLAC__int64)total_samples_in_input;
582 spec->value.samples += skip;
583 spec->is_relative = false;
587 if(spec->value.samples < 0) {
588 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
591 if((FLAC__uint64)spec->value.samples <= skip) {
592 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
595 if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
596 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
603 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
605 const char *fmt_desc = decoder_session->is_wave_out? "WAVE" : "AIFF";
606 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);
607 FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
608 const FLAC__uint32 aligned_data_size = (FLAC__uint32)((data_size+1) & (~1U)); /* we'll check for overflow later */
610 unsigned foreign_metadata_size = 0; /* size of all non-audio non-fmt/COMM foreign metadata chunks */
611 foreign_metadata_t *fm = decoder_session->foreign_metadata;
616 flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
617 flac__utils_printf(stderr, 1, " Generated %s file will have a data chunk size of 0. Try\n", fmt_desc);
618 flac__utils_printf(stderr, 1, " decoding directly to a file instead.\n");
619 if(decoder_session->treat_warnings_as_errors)
623 decoder_session->iff_headers_need_fixup = true;
628 FLAC__ASSERT(fm->format_block);
629 FLAC__ASSERT(fm->audio_block);
630 FLAC__ASSERT(fm->format_block < fm->audio_block);
631 /* calc foreign metadata size; for RIFF/AIFF we always skip the first chunk, format chunk, and sound chunk since we write our own */
632 for(i = 1; i < fm->num_blocks; i++) {
633 if(i != fm->format_block && i != fm->audio_block)
634 foreign_metadata_size += fm->blocks[i].size;
638 if(data_size + foreign_metadata_size + 60/*worst-case*/ >= 0xFFFFFFF4) {
639 flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file\n", decoder_session->inbasefilename, fmt_desc);
643 if(decoder_session->is_wave_out) {
644 if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
647 if(!write_little_endian_uint32(f, foreign_metadata_size + aligned_data_size + (is_waveformatextensible?60:36))) /* filesize-8 */
650 if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
653 decoder_session->fm_offset1 = ftello(f);
656 /* seek forward to {allocate} or {skip over already-written chunks} before "fmt " */
657 for(i = 1; i < fm->format_block; i++) {
658 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
659 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"fmt \"\n", decoder_session->inbasefilename);
665 if(!write_riff_wave_fmt_chunk(f, is_waveformatextensible, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate, decoder_session->channel_mask))
668 decoder_session->fm_offset2 = ftello(f);
671 /* seek forward to {allocate} or {skip over already-written chunks} after "fmt " but before "data" */
672 for(i = fm->format_block+1; i < fm->audio_block; i++) {
673 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
674 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"fmt \"\n", decoder_session->inbasefilename);
680 if(flac__utils_fwrite("data", 1, 4, f) != 4)
683 if(!write_little_endian_uint32(f, (FLAC__uint32)data_size)) /* data size */
686 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
689 FLAC__uint32 ssnd_offset_size = (fm? fm->ssnd_offset_size : 0);
691 if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
694 if(!write_big_endian_uint32(f, foreign_metadata_size + aligned_data_size + 46 + ssnd_offset_size)) /* filesize-8 */
697 if(flac__utils_fwrite("AIFF", 1, 4, f) != 4)
700 decoder_session->fm_offset1 = ftello(f);
703 /* seek forward to {allocate} or {skip over already-written chunks} before "COMM" */
704 for(i = 1; i < fm->format_block; i++) {
705 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
706 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"COMM\"\n", decoder_session->inbasefilename);
712 if(!write_aiff_form_comm_chunk(f, samples, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate))
715 decoder_session->fm_offset2 = ftello(f);
718 /* seek forward to {allocate} or {skip over already-written chunks} after "COMM" but before "SSND" */
719 for(i = fm->format_block+1; i < fm->audio_block; i++) {
720 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
721 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"COMM\"\n", decoder_session->inbasefilename);
727 if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
730 if(!write_big_endian_uint32(f, (FLAC__uint32)data_size + 8 + ssnd_offset_size)) /* data size */
733 if(!write_big_endian_uint32(f, ssnd_offset_size))
736 if(!write_big_endian_uint32(f, 0/*block_size*/))
739 if(ssnd_offset_size) {
740 /* seek forward to {allocate} or {skip over already-written} SSND offset */
741 if(fseeko(f, ssnd_offset_size, SEEK_CUR) < 0) {
742 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping \"SSND\" offset\n", decoder_session->inbasefilename);
747 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
753 FLAC__bool write_riff_wave_fmt_chunk(FILE *f, FLAC__bool is_waveformatextensible, unsigned bps, unsigned channels, unsigned sample_rate, FLAC__uint32 channel_mask)
755 if(flac__utils_fwrite("fmt ", 1, 4, f) != 4)
758 if(!write_little_endian_uint32(f, is_waveformatextensible? 40 : 16)) /* chunk size */
761 if(!write_little_endian_uint16(f, (FLAC__uint16)(is_waveformatextensible? 65534 : 1))) /* compression code */
764 if(!write_little_endian_uint16(f, (FLAC__uint16)channels))
767 if(!write_little_endian_uint32(f, sample_rate))
770 if(!write_little_endian_uint32(f, sample_rate * channels * ((bps+7) / 8)))
773 if(!write_little_endian_uint16(f, (FLAC__uint16)(channels * ((bps+7) / 8)))) /* block align */
776 if(!write_little_endian_uint16(f, (FLAC__uint16)(((bps+7)/8)*8))) /* bits per sample */
779 if(is_waveformatextensible) {
780 if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */
783 if(!write_little_endian_uint16(f, (FLAC__uint16)bps)) /* validBitsPerSample */
786 if(!write_little_endian_uint32(f, channel_mask))
789 /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */
790 if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16)
797 FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate)
799 FLAC__ASSERT(samples <= 0xffffffff);
801 if(flac__utils_fwrite("COMM", 1, 4, f) != 4)
804 if(!write_big_endian_uint32(f, 18)) /* chunk size = 18 */
807 if(!write_big_endian_uint16(f, (FLAC__uint16)channels))
810 if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
813 if(!write_big_endian_uint16(f, (FLAC__uint16)bps))
816 if(!write_sane_extended(f, sample_rate))
822 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
824 FLAC__byte *b = (FLAC__byte*)(&val);
825 if(is_big_endian_host_) {
827 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
829 return flac__utils_fwrite(b, 1, 2, f) == 2;
832 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
834 FLAC__byte *b = (FLAC__byte*)(&val);
835 if(is_big_endian_host_) {
837 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
838 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
840 return flac__utils_fwrite(b, 1, 4, f) == 4;
843 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
845 FLAC__byte *b = (FLAC__byte*)(&val);
846 if(!is_big_endian_host_) {
848 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
850 return flac__utils_fwrite(b, 1, 2, f) == 2;
853 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
855 FLAC__byte *b = (FLAC__byte*)(&val);
856 if(!is_big_endian_host_) {
858 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
859 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
861 return flac__utils_fwrite(b, 1, 4, f) == 4;
864 FLAC__bool write_sane_extended(FILE *f, unsigned val)
865 /* Write to 'f' a SANE extended representation of 'val'. Return false if
866 * the write succeeds; return true otherwise.
868 * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
869 * of exponent, and 64 bits of significand (mantissa). Unlike most IEEE-754
870 * representations, it does not imply a 1 above the MSB of the significand.
876 unsigned int shift, exponent;
878 FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
880 for(shift= 0U; (val>>(31-shift))==0U; ++shift)
883 exponent= 63U-(shift+32U); /* add 32 for unused second word */
885 if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
887 if(!write_big_endian_uint32(f, val))
889 if(!write_big_endian_uint32(f, 0)) /* unused second word */
895 FLAC__bool fixup_iff_headers(DecoderSession *d)
897 const char *fmt_desc = (d->is_wave_out? "WAVE" : "AIFF");
898 FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
901 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));
905 if(!write_iff_headers(f, d, d->samples_processed)) {
914 FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
916 DecoderSession *decoder_session = (DecoderSession*)client_data;
917 FILE *fout = decoder_session->fout;
918 const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
919 const unsigned shift = ((decoder_session->is_wave_out || decoder_session->is_aiff_out) && (bps%8)? 8-(bps%8): 0);
920 FLAC__bool is_big_endian = (decoder_session->is_aiff_out? true : (decoder_session->is_wave_out? false : decoder_session->is_big_endian));
921 FLAC__bool is_unsigned_samples = (decoder_session->is_aiff_out? false : (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples));
922 unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
923 unsigned frame_bytes = 0;
924 static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
925 FLAC__uint8 *u8buffer = (FLAC__uint8 *)s8buffer;
926 FLAC__int16 *s16buffer = (FLAC__int16 *)s8buffer;
927 FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
928 FLAC__int32 *s32buffer = (FLAC__int32 *)s8buffer;
929 FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
930 size_t bytes_to_write = 0;
934 if(decoder_session->abort_flag)
935 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
937 /* sanity-check the bits-per-sample */
938 if(decoder_session->bps) {
939 if(bps != decoder_session->bps) {
940 if(decoder_session->got_stream_info)
941 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);
943 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);
944 if(!decoder_session->continue_through_decode_errors)
945 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
949 /* must not have gotten STREAMINFO, save the bps from the frame header */
950 FLAC__ASSERT(!decoder_session->got_stream_info);
951 decoder_session->bps = bps;
954 /* sanity-check the #channels */
955 if(decoder_session->channels) {
956 if(channels != decoder_session->channels) {
957 if(decoder_session->got_stream_info)
958 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
960 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);
961 if(!decoder_session->continue_through_decode_errors)
962 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
966 /* must not have gotten STREAMINFO, save the #channels from the frame header */
967 FLAC__ASSERT(!decoder_session->got_stream_info);
968 decoder_session->channels = channels;
971 /* sanity-check the sample rate */
972 if(decoder_session->sample_rate) {
973 if(frame->header.sample_rate != decoder_session->sample_rate) {
974 if(decoder_session->got_stream_info)
975 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);
977 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);
978 if(!decoder_session->continue_through_decode_errors)
979 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
983 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
984 FLAC__ASSERT(!decoder_session->got_stream_info);
985 decoder_session->sample_rate = frame->header.sample_rate;
989 * limit the number of samples to accept based on --until
991 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
992 /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
993 if(decoder_session->skip_specification->is_relative) {
994 if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
995 decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
997 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);
998 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1001 if(decoder_session->until_specification->is_relative) {
1002 if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
1003 decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
1005 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);
1006 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1009 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1010 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1011 if(decoder_session->until_specification->value.samples > 0) {
1012 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1013 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1014 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
1015 FLAC__ASSERT(until >= input_samples_passed);
1016 if(input_samples_passed + wide_samples > until)
1017 wide_samples = (unsigned)(until - input_samples_passed);
1018 if (wide_samples == 0) {
1019 decoder_session->abort_flag = true;
1020 decoder_session->aborting_due_to_until = true;
1021 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1025 if(decoder_session->analysis_mode) {
1027 FLAC__stream_decoder_get_decode_position(decoder_session->decoder, &dpos);
1028 frame_bytes = (unsigned)(dpos-decoder_session->decode_position);
1029 decoder_session->decode_position = dpos;
1032 if(wide_samples > 0) {
1033 decoder_session->samples_processed += wide_samples;
1034 decoder_session->frame_counter++;
1036 if(!(decoder_session->frame_counter & 0x3f))
1037 print_stats(decoder_session);
1039 if(decoder_session->analysis_mode) {
1040 flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->decode_position-frame_bytes, frame_bytes, decoder_session->aopts, fout);
1042 else if(!decoder_session->test_only) {
1043 if(shift && !decoder_session->replaygain.apply) {
1044 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1045 for(channel = 0; channel < channels; channel++)
1046 ((FLAC__int32**)buffer)[channel][wide_sample] <<= shift;/*@@@@@@un-const'ing the buffer is hacky but safe*/
1048 if(decoder_session->replaygain.apply) {
1049 bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
1052 is_unsigned_samples,
1056 bps, /* source_bps */
1057 bps+shift, /* target_bps */
1058 decoder_session->replaygain.scale,
1059 decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
1060 decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
1061 &decoder_session->replaygain.dither_context
1064 /* first some special code for common cases */
1065 else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 2 && bps+shift == 16) {
1066 FLAC__int16 *buf1_ = s16buffer + 1;
1068 memcpy(s16buffer, ((FLAC__byte*)(buffer[0]))+2, sizeof(FLAC__int32) * wide_samples - 2);
1070 memcpy(s16buffer, buffer[0], sizeof(FLAC__int32) * wide_samples);
1071 for(sample = 0; sample < wide_samples; sample++, buf1_+=2)
1072 *buf1_ = (FLAC__int16)buffer[1][sample];
1073 bytes_to_write = 4 * sample;
1075 else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 1 && bps+shift == 16) {
1076 FLAC__int16 *buf1_ = s16buffer;
1077 for(sample = 0; sample < wide_samples; sample++)
1078 *buf1_++ = (FLAC__int16)buffer[0][sample];
1079 bytes_to_write = 2 * sample;
1081 /* generic code for the rest */
1082 else if(bps+shift == 16) {
1083 if(is_unsigned_samples) {
1085 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1086 u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1087 u16buffer[sample++] = (FLAC__uint16)(buffer[1][wide_sample] + 0x8000);
1090 else if(channels == 1) {
1091 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1092 u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1094 else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1095 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1096 for(channel = 0; channel < channels; channel++, sample++)
1097 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
1102 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1103 s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1104 s16buffer[sample++] = (FLAC__int16)(buffer[1][wide_sample]);
1107 else if(channels == 1) {
1108 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1109 s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1111 else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1112 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1113 for(channel = 0; channel < channels; channel++, sample++)
1114 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
1117 if(is_big_endian != is_big_endian_host_) {
1119 const unsigned bytes = sample * 2;
1120 for(byte = 0; byte < bytes; byte += 2) {
1121 tmp = u8buffer[byte];
1122 u8buffer[byte] = u8buffer[byte+1];
1123 u8buffer[byte+1] = tmp;
1126 bytes_to_write = 2 * sample;
1128 else if(bps+shift == 24) {
1129 if(is_unsigned_samples) {
1130 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1131 for(channel = 0; channel < channels; channel++, sample++)
1132 u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
1135 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1136 for(channel = 0; channel < channels; channel++, sample++)
1137 s32buffer[sample] = buffer[channel][wide_sample];
1139 if(is_big_endian != is_big_endian_host_) {
1141 const unsigned bytes = sample * 4;
1142 for(byte = 0; byte < bytes; byte += 4) {
1143 tmp = u8buffer[byte];
1144 u8buffer[byte] = u8buffer[byte+3];
1145 u8buffer[byte+3] = tmp;
1146 tmp = u8buffer[byte+1];
1147 u8buffer[byte+1] = u8buffer[byte+2];
1148 u8buffer[byte+2] = tmp;
1153 const unsigned bytes = sample * 4;
1154 for(lbyte = byte = 0; byte < bytes; ) {
1156 u8buffer[lbyte++] = u8buffer[byte++];
1157 u8buffer[lbyte++] = u8buffer[byte++];
1158 u8buffer[lbyte++] = u8buffer[byte++];
1163 const unsigned bytes = sample * 4;
1164 for(lbyte = byte = 0; byte < bytes; ) {
1165 u8buffer[lbyte++] = u8buffer[byte++];
1166 u8buffer[lbyte++] = u8buffer[byte++];
1167 u8buffer[lbyte++] = u8buffer[byte++];
1171 bytes_to_write = 3 * sample;
1173 else if(bps+shift == 8) {
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 u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
1180 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1181 for(channel = 0; channel < channels; channel++, sample++)
1182 s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
1184 bytes_to_write = sample;
1188 /* double protection */
1189 decoder_session->abort_flag = true;
1190 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1194 if(bytes_to_write > 0) {
1195 if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
1196 /* if a pipe closed when writing to stdout, we let it go without an error message */
1197 if(errno == EPIPE && decoder_session->fout == stdout)
1198 decoder_session->aborting_due_to_until = true;
1199 decoder_session->abort_flag = true;
1200 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1203 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1206 void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1208 DecoderSession *decoder_session = (DecoderSession*)client_data;
1210 if(decoder_session->analysis_mode)
1211 FLAC__stream_decoder_get_decode_position(decoder, &decoder_session->decode_position);
1213 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
1214 FLAC__uint64 skip, until;
1215 decoder_session->got_stream_info = true;
1216 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);
1217 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1218 decoder_session->channels = metadata->data.stream_info.channels;
1219 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1221 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
1222 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1223 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1225 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1226 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1227 flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1228 decoder_session->abort_flag = true;
1231 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1232 flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1233 decoder_session->abort_flag = true;
1236 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1237 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1239 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1240 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1241 decoder_session->abort_flag = true;
1244 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1245 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1248 FLAC__ASSERT(decoder_session->total_samples != 0);
1249 FLAC__ASSERT(0 == decoder_session->cue_specification);
1250 decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1253 if(decoder_session->bps < 4 || decoder_session->bps > 24) {
1254 flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 4-24\n", decoder_session->inbasefilename, decoder_session->bps);
1255 decoder_session->abort_flag = true;
1259 else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1260 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1261 if(decoder_session->total_samples == 0) {
1262 flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1263 decoder_session->abort_flag = true;
1267 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);
1269 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1270 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1272 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1273 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1275 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1276 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1277 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1278 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1280 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1282 else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1283 if (decoder_session->replaygain.spec.apply) {
1284 double reference, gain, peak;
1285 if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
1286 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");
1287 if(decoder_session->treat_warnings_as_errors) {
1288 decoder_session->abort_flag = true;
1293 const char *ls[] = { "no", "peak", "hard" };
1294 const char *ns[] = { "no", "low", "medium", "high" };
1295 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1296 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1297 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1298 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]);
1299 flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1300 /* don't check if(decoder_session->treat_warnings_as_errors) because the user explicitly asked for it */
1303 (void)flac__utils_get_channel_mask_tag(metadata, &decoder_session->channel_mask);
1307 void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1309 DecoderSession *decoder_session = (DecoderSession*)client_data;
1311 flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1312 if(!decoder_session->continue_through_decode_errors) {
1313 decoder_session->abort_flag = true;
1314 if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1315 decoder_session->aborting_due_to_unparseable = true;
1319 void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
1321 const int ilen = strlen(d->inbasefilename) + 1;
1323 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1325 flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
1327 /* print out some more info for some errors: */
1328 if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
1329 flac__utils_printf(stderr, 1,
1331 "An error occurred opening the input file; it is likely that it does not exist\n"
1332 "or is not readable.\n"
1337 void print_error_with_state(const DecoderSession *d, const char *message)
1339 const int ilen = strlen(d->inbasefilename) + 1;
1341 flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1342 flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", FLAC__stream_decoder_get_resolved_state_string(d->decoder));
1344 /* print out some more info for some errors: */
1345 if (d->aborting_due_to_unparseable) {
1346 flac__utils_printf(stderr, 1,
1348 "The FLAC stream may have been created by a more advanced encoder. Try\n"
1349 " metaflac --show-vendor-tag %s\n"
1350 "If the version number is greater than %s, this decoder is probably\n"
1351 "not able to decode the file. If the version number is not, the file\n"
1352 "may be corrupted, or you may have found a bug. In this case please\n"
1353 "submit a bug report to\n"
1354 " http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
1355 "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1356 d->inbasefilename, FLAC__VERSION_STRING
1361 void print_stats(const DecoderSession *decoder_session)
1363 if(flac__utils_verbosity_ >= 2) {
1364 #if defined _MSC_VER || defined __MINGW32__
1365 /* with MSVC you have to spoon feed it the casting */
1366 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1368 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1370 if(decoder_session->total_samples > 0) {
1371 fprintf(stderr, "\r%s: %s%u%% complete",
1372 decoder_session->inbasefilename,
1373 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1374 (unsigned)floor(progress + 0.5)
1378 fprintf(stderr, "\r%s: %s %u samples",
1379 decoder_session->inbasefilename,
1380 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1381 (unsigned)decoder_session->samples_processed