*** empty log message ***
[platform/upstream/flac.git] / src / flac / decode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3  *
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.
8  *
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.
13  *
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.
17  */
18
19 #if HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #if defined _WIN32 && !defined __CYGWIN__
24 /* where MSVC puts unlink() */
25 # include <io.h>
26 #else
27 # include <unistd.h>
28 #endif
29 #if defined _MSC_VER || defined __MINGW32__
30 #include <sys/types.h> /* for off_t */
31 #if _MSC_VER <= 1600 /* @@@ [2G limit] */
32 #define fseeko fseek
33 #define ftello ftell
34 #endif
35 #endif
36 #include <errno.h>
37 #include <math.h> /* for floor() */
38 #include <stdio.h> /* for FILE etc. */
39 #include <string.h> /* for strcmp(), strerror() */
40 #include "FLAC/all.h"
41 #include "share/grabbag.h"
42 #include "share/replaygain_synthesis.h"
43 #include "decode.h"
44
45 typedef struct {
46 #if FLAC__HAS_OGG
47         FLAC__bool is_ogg;
48 #endif
49
50         FLAC__bool is_aiff_out;
51         FLAC__bool is_wave_out;
52         FLAC__bool treat_warnings_as_errors;
53         FLAC__bool continue_through_decode_errors;
54         FLAC__bool channel_map_none;
55
56         struct {
57                 replaygain_synthesis_spec_t spec;
58                 FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */
59                 double scale;
60                 DitherContext dither_context;
61         } replaygain;
62
63         FLAC__bool test_only;
64         FLAC__bool analysis_mode;
65         analysis_options aopts;
66         utils__SkipUntilSpecification *skip_specification;
67         utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
68         utils__CueSpecification *cue_specification;
69
70         const char *inbasefilename;
71         const char *outfilename;
72
73         FLAC__uint64 samples_processed;
74         unsigned frame_counter;
75         FLAC__bool abort_flag;
76         FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
77         FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */
78
79         FLAC__bool iff_headers_need_fixup;
80
81         FLAC__bool is_big_endian;
82         FLAC__bool is_unsigned_samples;
83         FLAC__bool got_stream_info;
84         FLAC__bool has_md5sum;
85         FLAC__uint64 total_samples;
86         unsigned bps;
87         unsigned channels;
88         unsigned sample_rate;
89         FLAC__uint32 channel_mask;
90
91         /* these are used only in analyze mode */
92         FLAC__uint64 decode_position;
93
94         FLAC__StreamDecoder *decoder;
95
96         FILE *fout;
97 } DecoderSession;
98
99
100 static FLAC__bool is_big_endian_host_;
101
102
103 /*
104  * local routines
105  */
106 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, 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, const char *infilename, const char *outfilename);
107 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
108 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, decode_options_t decode_options, const char *infilename);
109 static FLAC__bool DecoderSession_process(DecoderSession *d);
110 static int DecoderSession_finish_ok(DecoderSession *d);
111 static int DecoderSession_finish_error(DecoderSession *d);
112 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
113 static FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples);
114 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
115 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
116 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
117 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
118 static FLAC__bool write_sane_extended(FILE *f, unsigned val);
119 static FLAC__bool fixup_iff_headers(DecoderSession *d);
120 static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
121 static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
122 static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
123 static void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status);
124 static void print_error_with_state(const DecoderSession *d, const char *message);
125 static void print_stats(const DecoderSession *decoder_session);
126
127
128 /*
129  * public routines
130  */
131 int flac__decode_aiff(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
132 {
133         DecoderSession decoder_session;
134
135         if(!
136                 DecoderSession_construct(
137                         &decoder_session,
138 #if FLAC__HAS_OGG
139                         options.common.is_ogg,
140 #else
141                         /*is_ogg=*/false,
142 #endif
143                         /*is_aiff_out=*/true,
144                         /*is_wave_out=*/false,
145                         options.common.treat_warnings_as_errors,
146                         options.common.continue_through_decode_errors,
147                         options.common.channel_map_none,
148                         options.common.replaygain_synthesis_spec,
149                         analysis_mode,
150                         aopts,
151                         &options.common.skip_specification,
152                         &options.common.until_specification,
153                         options.common.has_cue_specification? &options.common.cue_specification : 0,
154                         infilename,
155                         outfilename
156                 )
157         )
158                 return 1;
159
160         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
161                 return DecoderSession_finish_error(&decoder_session);
162
163         if(!DecoderSession_process(&decoder_session))
164                 return DecoderSession_finish_error(&decoder_session);
165
166         return DecoderSession_finish_ok(&decoder_session);
167 }
168
169 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
170 {
171         DecoderSession decoder_session;
172
173         if(!
174                 DecoderSession_construct(
175                         &decoder_session,
176 #if FLAC__HAS_OGG
177                         options.common.is_ogg,
178 #else
179                         /*is_ogg=*/false,
180 #endif
181                         /*is_aiff_out=*/false,
182                         /*is_wave_out=*/true,
183                         options.common.treat_warnings_as_errors,
184                         options.common.continue_through_decode_errors,
185                         options.common.channel_map_none,
186                         options.common.replaygain_synthesis_spec,
187                         analysis_mode,
188                         aopts,
189                         &options.common.skip_specification,
190                         &options.common.until_specification,
191                         options.common.has_cue_specification? &options.common.cue_specification : 0,
192                         infilename,
193                         outfilename
194                 )
195         )
196                 return 1;
197
198         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
199                 return DecoderSession_finish_error(&decoder_session);
200
201         if(!DecoderSession_process(&decoder_session))
202                 return DecoderSession_finish_error(&decoder_session);
203
204         return DecoderSession_finish_ok(&decoder_session);
205 }
206
207 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
208 {
209         DecoderSession decoder_session;
210
211         decoder_session.is_big_endian = options.is_big_endian;
212         decoder_session.is_unsigned_samples = options.is_unsigned_samples;
213
214         if(!
215                 DecoderSession_construct(
216                         &decoder_session,
217 #if FLAC__HAS_OGG
218                         options.common.is_ogg,
219 #else
220                         /*is_ogg=*/false,
221 #endif
222                         /*is_aiff_out=*/false,
223                         /*is_wave_out=*/false,
224                         options.common.treat_warnings_as_errors,
225                         options.common.continue_through_decode_errors,
226                         options.common.channel_map_none,
227                         options.common.replaygain_synthesis_spec,
228                         analysis_mode,
229                         aopts,
230                         &options.common.skip_specification,
231                         &options.common.until_specification,
232                         options.common.has_cue_specification? &options.common.cue_specification : 0,
233                         infilename,
234                         outfilename
235                 )
236         )
237                 return 1;
238
239         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
240                 return DecoderSession_finish_error(&decoder_session);
241
242         if(!DecoderSession_process(&decoder_session))
243                 return DecoderSession_finish_error(&decoder_session);
244
245         return DecoderSession_finish_ok(&decoder_session);
246 }
247
248 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, 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, const char *infilename, const char *outfilename)
249 {
250 #if FLAC__HAS_OGG
251         d->is_ogg = is_ogg;
252 #else
253         (void)is_ogg;
254 #endif
255
256         d->is_aiff_out = is_aiff_out;
257         d->is_wave_out = is_wave_out;
258         d->treat_warnings_as_errors = treat_warnings_as_errors;
259         d->continue_through_decode_errors = continue_through_decode_errors;
260         d->channel_map_none = channel_map_none;
261         d->replaygain.spec = replaygain_synthesis_spec;
262         d->replaygain.apply = false;
263         d->replaygain.scale = 0.0;
264         /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
265         d->test_only = (0 == outfilename);
266         d->analysis_mode = analysis_mode;
267         d->aopts = aopts;
268         d->skip_specification = skip_specification;
269         d->until_specification = until_specification;
270         d->cue_specification = cue_specification;
271
272         d->inbasefilename = grabbag__file_get_basename(infilename);
273         d->outfilename = outfilename;
274
275         d->samples_processed = 0;
276         d->frame_counter = 0;
277         d->abort_flag = false;
278         d->aborting_due_to_until = false;
279         d->aborting_due_to_unparseable = false;
280
281         d->iff_headers_need_fixup = false;
282
283         d->total_samples = 0;
284         d->got_stream_info = false;
285         d->has_md5sum = false;
286         d->bps = 0;
287         d->channels = 0;
288         d->sample_rate = 0;
289         d->channel_mask = 0;
290
291         d->decode_position = 0;
292
293         d->decoder = 0;
294
295         d->fout = 0; /* initialized with an open file later if necessary */
296
297         FLAC__ASSERT(!(d->test_only && d->analysis_mode));
298
299         if(!d->test_only) {
300                 if(0 == strcmp(outfilename, "-")) {
301                         d->fout = grabbag__file_get_binary_stdout();
302                 }
303                 else {
304                         if(0 == (d->fout = fopen(outfilename, "wb"))) {
305                                 flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
306                                 DecoderSession_destroy(d, /*error_occurred=*/true);
307                                 return false;
308                         }
309                 }
310         }
311
312         if(analysis_mode)
313                 flac__analyze_init(aopts);
314
315         return true;
316 }
317
318 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
319 {
320         if(0 != d->fout && d->fout != stdout) {
321                 fclose(d->fout);
322                 if(error_occurred)
323                         unlink(d->outfilename);
324         }
325 }
326
327 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, decode_options_t decode_options, const char *infilename)
328 {
329         FLAC__StreamDecoderInitStatus init_status;
330         FLAC__uint32 test = 1;
331
332         is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
333
334         decoder_session->decoder = FLAC__stream_decoder_new();
335
336         if(0 == decoder_session->decoder) {
337                 flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
338                 return false;
339         }
340
341         FLAC__stream_decoder_set_md5_checking(decoder_session->decoder, true);
342         if (0 != decoder_session->cue_specification)
343                 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_CUESHEET);
344         if (decoder_session->replaygain.spec.apply)
345                 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
346
347 #if FLAC__HAS_OGG
348         if(decoder_session->is_ogg) {
349                 if(!decode_options.use_first_serial_number)
350                         FLAC__stream_decoder_set_ogg_serial_number(decoder_session->decoder, decode_options.serial_number);
351                 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);
352         }
353         else
354 #else
355         (void)decode_options;
356 #endif
357         {
358                 init_status = FLAC__stream_decoder_init_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
359         }
360
361         if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
362                 print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
363                 return false;
364         }
365
366         return true;
367 }
368
369 FLAC__bool DecoderSession_process(DecoderSession *d)
370 {
371         if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder)) {
372                 flac__utils_printf(stderr, 2, "\n");
373                 print_error_with_state(d, "ERROR while decoding metadata");
374                 return false;
375         }
376         if(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM) {
377                 flac__utils_printf(stderr, 2, "\n");
378                 print_error_with_state(d, "ERROR during metadata decoding");
379                 if(!d->continue_through_decode_errors)
380                         return false;
381         }
382
383         if(d->abort_flag)
384                 return false;
385
386         /* set channel mapping */
387         if(!d->channel_map_none) {
388                 /* currently FLAC order matches SMPTE/WAVEFORMATEXTENSIBLE order, so no reordering is necessary; see encode.c */
389                 /* only the channel mask must be set if it was not already picked up from the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag */
390                 if(d->channels == 1) {
391                         if(d->channel_mask == 0)
392                                 d->channel_mask = 0x0001;
393                 }
394                 else if(d->channels == 2) {
395                         if(d->channel_mask == 0)
396                                 d->channel_mask = 0x0003;
397                 }
398                 else if(d->channels == 3) {
399                         if(d->channel_mask == 0)
400                                 d->channel_mask = 0x0007;
401                 }
402                 else if(d->channels == 4) {
403                         if(d->channel_mask == 0)
404                                 d->channel_mask = 0x0033;
405                 }
406                 else if(d->channels == 5) {
407                         if(d->channel_mask == 0)
408                                 d->channel_mask = 0x0607;
409                 }
410                 else if(d->channels == 6) {
411                         if(d->channel_mask == 0)
412                                 d->channel_mask = 0x060f;
413                 }
414         }
415
416         /* write the WAVE/AIFF headers if necessary */
417         if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out)) {
418                 if(!write_iff_headers(d->fout, d, d->total_samples)) {
419                         d->abort_flag = true;
420                         return false;
421                 }
422         }
423
424         if(d->skip_specification->value.samples > 0) {
425                 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
426
427                 if(!FLAC__stream_decoder_seek_absolute(d->decoder, skip)) {
428                         print_error_with_state(d, "ERROR seeking while skipping bytes");
429                         return false;
430                 }
431         }
432         if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder) && !d->aborting_due_to_until) {
433                 flac__utils_printf(stderr, 2, "\n");
434                 print_error_with_state(d, "ERROR while decoding data");
435                 if(!d->continue_through_decode_errors)
436                         return false;
437         }
438         if(
439                 (d->abort_flag && !(d->aborting_due_to_until || d->continue_through_decode_errors)) ||
440                 (FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until)
441         ) {
442                 flac__utils_printf(stderr, 2, "\n");
443                 print_error_with_state(d, "ERROR during decoding");
444                 return false;
445         }
446
447         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)) {
448                 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
449                         print_error_with_state(d, d->is_wave_out?
450                                 "ERROR writing pad byte to WAVE data chunk" :
451                                 "ERROR writing pad byte to AIFF SSND chunk"
452                         );
453                         return false;
454                 }
455         }
456
457         return true;
458 }
459
460 int DecoderSession_finish_ok(DecoderSession *d)
461 {
462         FLAC__bool ok = true, md5_failure = false;
463
464         if(d->decoder) {
465                 md5_failure = !FLAC__stream_decoder_finish(d->decoder) && !d->aborting_due_to_until;
466                 print_stats(d);
467                 FLAC__stream_decoder_delete(d->decoder);
468         }
469         if(d->analysis_mode)
470                 flac__analyze_finish(d->aopts);
471         if(md5_failure) {
472                 flac__utils_printf(stderr, 1, "\r%s: ERROR, MD5 signature mismatch\n", d->inbasefilename);
473                 ok = d->continue_through_decode_errors;
474         }
475         else {
476                 if(!d->got_stream_info) {
477                         flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since there was no STREAMINFO\n", d->inbasefilename);
478                         ok = !d->treat_warnings_as_errors;
479                 }
480                 else if(!d->has_md5sum) {
481                         flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since it was unset in the STREAMINFO\n", d->inbasefilename);
482                         ok = !d->treat_warnings_as_errors;
483                 }
484                 flac__utils_printf(stderr, 2, "\r%s: %s         \n", d->inbasefilename, d->test_only? "ok           ":d->analysis_mode?"done           ":"done");
485         }
486         DecoderSession_destroy(d, /*error_occurred=*/!ok);
487         if(!d->test_only && (d->is_wave_out || d->is_aiff_out) && (d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))))
488                 if(!fixup_iff_headers(d))
489                         return 1;
490         return ok? 0 : 1;
491 }
492
493 int DecoderSession_finish_error(DecoderSession *d)
494 {
495         if(d->decoder) {
496                 (void)FLAC__stream_decoder_finish(d->decoder);
497                 FLAC__stream_decoder_delete(d->decoder);
498         }
499         if(d->analysis_mode)
500                 flac__analyze_finish(d->aopts);
501         DecoderSession_destroy(d, /*error_occurred=*/true);
502         return 1;
503 }
504
505 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
506 {
507         /* convert from mm:ss.sss to sample number if necessary */
508         flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
509
510         /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
511         if(spec->is_relative && spec->value.samples == 0) {
512                 spec->is_relative = false;
513                 return true;
514         }
515
516         /* in any other case the total samples in the input must be known */
517         if(total_samples_in_input == 0) {
518                 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
519                 return false;
520         }
521
522         FLAC__ASSERT(spec->value_is_samples);
523
524         /* convert relative specifications to absolute */
525         if(spec->is_relative) {
526                 if(spec->value.samples <= 0)
527                         spec->value.samples += (FLAC__int64)total_samples_in_input;
528                 else
529                         spec->value.samples += skip;
530                 spec->is_relative = false;
531         }
532
533         /* error check */
534         if(spec->value.samples < 0) {
535                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
536                 return false;
537         }
538         if((FLAC__uint64)spec->value.samples <= skip) {
539                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
540                 return false;
541         }
542         if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
543                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
544                 return false;
545         }
546
547         return true;
548 }
549
550 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
551 {
552         const char *fmt_desc = decoder_session->is_wave_out? "WAVE" : "AIFF";
553         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);
554         FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
555         const FLAC__uint32 aligned_data_size = (FLAC__uint32)((data_size+1) & (~1U)); /* we'll check for overflow later */
556         if(samples == 0) {
557                 if(f == stdout) {
558                         flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
559                         flac__utils_printf(stderr, 1, "             Generated %s file will have a data chunk size of 0.  Try\n", fmt_desc);
560                         flac__utils_printf(stderr, 1, "             decoding directly to a file instead.\n");
561                         if(decoder_session->treat_warnings_as_errors)
562                                 return false;
563                 }
564                 else {
565                         decoder_session->iff_headers_need_fixup = true;
566                 }
567         }
568         if(data_size >= 0xFFFFFFDC) {
569                 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);
570                 return false;
571         }
572         if(decoder_session->is_wave_out) {
573                 if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
574                         return false;
575
576                 if(!write_little_endian_uint32(f, aligned_data_size+(is_waveformatextensible?60:36))) /* filesize-8 */
577                         return false;
578
579                 if(flac__utils_fwrite("WAVEfmt ", 1, 8, f) != 8)
580                         return false;
581
582                 if(!write_little_endian_uint32(f, is_waveformatextensible? 40 : 16)) /* chunk size */
583                         return false;
584
585                 if(!write_little_endian_uint16(f, (FLAC__uint16)(is_waveformatextensible? 65534 : 1))) /* compression code */
586                         return false;
587
588                 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
589                         return false;
590
591                 if(!write_little_endian_uint32(f, decoder_session->sample_rate))
592                         return false;
593
594                 if(!write_little_endian_uint32(f, decoder_session->sample_rate * decoder_session->channels * ((decoder_session->bps+7) / 8)))
595                         return false;
596
597                 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels * ((decoder_session->bps+7) / 8)))) /* block align */
598                         return false;
599
600                 if(!write_little_endian_uint16(f, (FLAC__uint16)(((decoder_session->bps+7)/8)*8))) /* bits per sample */
601                         return false;
602
603                 if(is_waveformatextensible) {
604                         if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */
605                                 return false;
606
607                         if(!write_little_endian_uint16(f, (FLAC__uint16)decoder_session->bps)) /* validBitsPerSample */
608                                 return false;
609
610                         if(!write_little_endian_uint32(f, decoder_session->channel_mask))
611                                 return false;
612
613                         /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */
614                         if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16)
615                                 return false;
616                 }
617
618                 if(flac__utils_fwrite("data", 1, 4, f) != 4)
619                         return false;
620
621                 if(!write_little_endian_uint32(f, (FLAC__uint32)data_size)) /* data size */
622                         return false;
623         }
624         else {
625                 if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
626                         return false;
627
628                 if(!write_big_endian_uint32(f, aligned_data_size+46)) /* filesize-8 */
629                         return false;
630
631                 if(flac__utils_fwrite("AIFFCOMM", 1, 8, f) != 8)
632                         return false;
633
634                 if(flac__utils_fwrite("\000\000\000\022", 1, 4, f) != 4) /* chunk size = 18 */
635                         return false;
636
637                 if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
638                         return false;
639
640                 if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
641                         return false;
642
643                 if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->bps)))
644                         return false;
645
646                 if(!write_sane_extended(f, decoder_session->sample_rate))
647                         return false;
648
649                 if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
650                         return false;
651
652                 if(!write_big_endian_uint32(f, (FLAC__uint32)data_size+8)) /* data size */
653                         return false;
654
655                 if(!write_big_endian_uint32(f, 0/*offset*/))
656                         return false;
657
658                 if(!write_big_endian_uint32(f, 0/*block_size*/))
659                         return false;
660         }
661
662         return true;
663 }
664
665 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
666 {
667         FLAC__byte *b = (FLAC__byte*)(&val);
668         if(is_big_endian_host_) {
669                 FLAC__byte tmp;
670                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
671         }
672         return flac__utils_fwrite(b, 1, 2, f) == 2;
673 }
674
675 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
676 {
677         FLAC__byte *b = (FLAC__byte*)(&val);
678         if(is_big_endian_host_) {
679                 FLAC__byte tmp;
680                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
681                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
682         }
683         return flac__utils_fwrite(b, 1, 4, f) == 4;
684 }
685
686 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
687 {
688         FLAC__byte *b = (FLAC__byte*)(&val);
689         if(!is_big_endian_host_) {
690                 FLAC__byte tmp;
691                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
692         }
693         return flac__utils_fwrite(b, 1, 2, f) == 2;
694 }
695
696 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
697 {
698         FLAC__byte *b = (FLAC__byte*)(&val);
699         if(!is_big_endian_host_) {
700                 FLAC__byte tmp;
701                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
702                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
703         }
704         return flac__utils_fwrite(b, 1, 4, f) == 4;
705 }
706
707 FLAC__bool write_sane_extended(FILE *f, unsigned val)
708         /* Write to 'f' a SANE extended representation of 'val'.  Return false if
709         * the write succeeds; return true otherwise.
710         *
711         * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
712         * of exponent, and 64 bits of significand (mantissa).  Unlike most IEEE-754
713         * representations, it does not imply a 1 above the MSB of the significand.
714         *
715         * Preconditions:
716         *  val!=0U
717         */
718 {
719         unsigned int shift, exponent;
720
721         FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
722
723         for(shift= 0U; (val>>(31-shift))==0U; ++shift)
724                 ;
725         val<<= shift;
726         exponent= 63U-(shift+32U); /* add 32 for unused second word */
727
728         if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
729                 return false;
730         if(!write_big_endian_uint32(f, val))
731                 return false;
732         if(!write_big_endian_uint32(f, 0)) /* unused second word */
733                 return false;
734
735         return true;
736 }
737
738 FLAC__bool fixup_iff_headers(DecoderSession *d)
739 {
740         const char *fmt_desc = (d->is_wave_out? "WAVE" : "AIFF");
741         FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
742
743         if(0 == f) {
744                 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));
745                 return false;
746         }
747
748         if(!write_iff_headers(f, d, d->samples_processed)) {
749                 fclose(f);
750                 return false;
751         }
752
753         fclose(f);
754         return true;
755 }
756
757 FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
758 {
759         DecoderSession *decoder_session = (DecoderSession*)client_data;
760         FILE *fout = decoder_session->fout;
761         const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
762         const unsigned shift = ((decoder_session->is_wave_out || decoder_session->is_aiff_out) && (bps%8)? 8-(bps%8): 0);
763         FLAC__bool is_big_endian = (decoder_session->is_aiff_out? true : (decoder_session->is_wave_out? false : decoder_session->is_big_endian));
764         FLAC__bool is_unsigned_samples = (decoder_session->is_aiff_out? false : (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples));
765         unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
766         unsigned frame_bytes = 0;
767         static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
768         FLAC__uint8  *u8buffer  = (FLAC__uint8  *)s8buffer;
769         FLAC__int16  *s16buffer = (FLAC__int16  *)s8buffer;
770         FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
771         FLAC__int32  *s32buffer = (FLAC__int32  *)s8buffer;
772         FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
773         size_t bytes_to_write = 0;
774
775         (void)decoder;
776
777         if(decoder_session->abort_flag)
778                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
779
780         /* sanity-check the bits-per-sample */
781         if(decoder_session->bps) {
782                 if(bps != decoder_session->bps) {
783                         if(decoder_session->got_stream_info)
784                                 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);
785                         else
786                                 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);
787                         if(!decoder_session->continue_through_decode_errors)
788                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
789                 }
790         }
791         else {
792                 /* must not have gotten STREAMINFO, save the bps from the frame header */
793                 FLAC__ASSERT(!decoder_session->got_stream_info);
794                 decoder_session->bps = bps;
795         }
796
797         /* sanity-check the #channels */
798         if(decoder_session->channels) {
799                 if(channels != decoder_session->channels) {
800                         if(decoder_session->got_stream_info)
801                                 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
802                         else
803                                 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);
804                         if(!decoder_session->continue_through_decode_errors)
805                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
806                 }
807         }
808         else {
809                 /* must not have gotten STREAMINFO, save the #channels from the frame header */
810                 FLAC__ASSERT(!decoder_session->got_stream_info);
811                 decoder_session->channels = channels;
812         }
813
814         /* sanity-check the sample rate */
815         if(decoder_session->sample_rate) {
816                 if(frame->header.sample_rate != decoder_session->sample_rate) {
817                         if(decoder_session->got_stream_info)
818                                 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);
819                         else
820                                 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);
821                         if(!decoder_session->continue_through_decode_errors)
822                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
823                 }
824         }
825         else {
826                 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
827                 FLAC__ASSERT(!decoder_session->got_stream_info);
828                 decoder_session->sample_rate = frame->header.sample_rate;
829         }
830
831         /*
832          * limit the number of samples to accept based on --until
833          */
834         FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
835         /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
836         if(decoder_session->skip_specification->is_relative) {
837                 if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
838                         decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
839                 else {
840                         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);
841                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
842                 }
843         }
844         if(decoder_session->until_specification->is_relative) {
845                 if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
846                         decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
847                 else {
848                         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);
849                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
850                 }
851         }
852         FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
853         FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
854         if(decoder_session->until_specification->value.samples > 0) {
855                 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
856                 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
857                 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
858                 FLAC__ASSERT(until >= input_samples_passed);
859                 if(input_samples_passed + wide_samples > until)
860                         wide_samples = (unsigned)(until - input_samples_passed);
861                 if (wide_samples == 0) {
862                         decoder_session->abort_flag = true;
863                         decoder_session->aborting_due_to_until = true;
864                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
865                 }
866         }
867
868         if(decoder_session->analysis_mode) {
869                 FLAC__uint64 dpos;
870                 FLAC__stream_decoder_get_decode_position(decoder_session->decoder, &dpos);
871                 frame_bytes = (unsigned)(dpos-decoder_session->decode_position);
872                 decoder_session->decode_position = dpos;
873         }
874
875         if(wide_samples > 0) {
876                 decoder_session->samples_processed += wide_samples;
877                 decoder_session->frame_counter++;
878
879                 if(!(decoder_session->frame_counter & 0x3f))
880                         print_stats(decoder_session);
881
882                 if(decoder_session->analysis_mode) {
883                         flac__analyze_frame(frame, decoder_session->frame_counter-1, frame_bytes, decoder_session->aopts, fout);
884                 }
885                 else if(!decoder_session->test_only) {
886                         if(shift && !decoder_session->replaygain.apply) {
887                                 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
888                                         for(channel = 0; channel < channels; channel++)
889                                                 ((FLAC__int32**)buffer)[channel][wide_sample] <<= shift;/*@@@@@@un-const'ing the buffer is hacky but safe*/
890                         }
891                         if(decoder_session->replaygain.apply) {
892                                 bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
893                                         u8buffer,
894                                         !is_big_endian,
895                                         is_unsigned_samples,
896                                         buffer,
897                                         wide_samples,
898                                         channels,
899                                         bps, /* source_bps */
900                                         bps+shift, /* target_bps */
901                                         decoder_session->replaygain.scale,
902                                         decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
903                                         decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
904                                         &decoder_session->replaygain.dither_context
905                                 );
906                         }
907                         else if(bps+shift == 8) {
908                                 if(is_unsigned_samples) {
909                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
910                                                 for(channel = 0; channel < channels; channel++, sample++)
911                                                         u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
912                                 }
913                                 else {
914                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
915                                                 for(channel = 0; channel < channels; channel++, sample++)
916                                                         s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
917                                 }
918                                 bytes_to_write = sample;
919                         }
920                         else if(bps+shift == 16) {
921                                 if(is_unsigned_samples) {
922                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
923                                                 for(channel = 0; channel < channels; channel++, sample++)
924                                                         u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
925                                 }
926                                 else {
927                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
928                                                 for(channel = 0; channel < channels; channel++, sample++)
929                                                         s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
930                                 }
931                                 if(is_big_endian != is_big_endian_host_) {
932                                         unsigned char tmp;
933                                         const unsigned bytes = sample * 2;
934                                         for(byte = 0; byte < bytes; byte += 2) {
935                                                 tmp = u8buffer[byte];
936                                                 u8buffer[byte] = u8buffer[byte+1];
937                                                 u8buffer[byte+1] = tmp;
938                                         }
939                                 }
940                                 bytes_to_write = 2 * sample;
941                         }
942                         else if(bps+shift == 24) {
943                                 if(is_unsigned_samples) {
944                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
945                                                 for(channel = 0; channel < channels; channel++, sample++)
946                                                         u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
947                                 }
948                                 else {
949                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
950                                                 for(channel = 0; channel < channels; channel++, sample++)
951                                                         s32buffer[sample] = buffer[channel][wide_sample];
952                                 }
953                                 if(is_big_endian != is_big_endian_host_) {
954                                         unsigned char tmp;
955                                         const unsigned bytes = sample * 4;
956                                         for(byte = 0; byte < bytes; byte += 4) {
957                                                 tmp = u8buffer[byte];
958                                                 u8buffer[byte] = u8buffer[byte+3];
959                                                 u8buffer[byte+3] = tmp;
960                                                 tmp = u8buffer[byte+1];
961                                                 u8buffer[byte+1] = u8buffer[byte+2];
962                                                 u8buffer[byte+2] = tmp;
963                                         }
964                                 }
965                                 if(is_big_endian) {
966                                         unsigned lbyte;
967                                         const unsigned bytes = sample * 4;
968                                         for(lbyte = byte = 0; byte < bytes; ) {
969                                                 byte++;
970                                                 u8buffer[lbyte++] = u8buffer[byte++];
971                                                 u8buffer[lbyte++] = u8buffer[byte++];
972                                                 u8buffer[lbyte++] = u8buffer[byte++];
973                                         }
974                                 }
975                                 else {
976                                         unsigned lbyte;
977                                         const unsigned bytes = sample * 4;
978                                         for(lbyte = byte = 0; byte < bytes; ) {
979                                                 u8buffer[lbyte++] = u8buffer[byte++];
980                                                 u8buffer[lbyte++] = u8buffer[byte++];
981                                                 u8buffer[lbyte++] = u8buffer[byte++];
982                                                 byte++;
983                                         }
984                                 }
985                                 bytes_to_write = 3 * sample;
986                         }
987                         else {
988                                 FLAC__ASSERT(0);
989                                 /* double protection */
990                                 decoder_session->abort_flag = true;
991                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
992                         }
993                 }
994         }
995         if(bytes_to_write > 0) {
996                 if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
997                         /* if a pipe closed when writing to stdout, we let it go without an error message */
998                         if(errno == EPIPE && decoder_session->fout == stdout)
999                                 decoder_session->aborting_due_to_until = true;
1000                         decoder_session->abort_flag = true;
1001                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1002                 }
1003         }
1004         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1005 }
1006
1007 void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1008 {
1009         DecoderSession *decoder_session = (DecoderSession*)client_data;
1010
1011         if(decoder_session->analysis_mode)
1012                 FLAC__stream_decoder_get_decode_position(decoder, &decoder_session->decode_position);
1013
1014         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
1015                 FLAC__uint64 skip, until;
1016                 decoder_session->got_stream_info = true;
1017                 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);
1018                 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1019                 decoder_session->channels = metadata->data.stream_info.channels;
1020                 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1021
1022                 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
1023                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1024                 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1025
1026                 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1027                 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1028                         flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1029                         decoder_session->abort_flag = true;
1030                         return;
1031                 }
1032                 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1033                         flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1034                         decoder_session->abort_flag = true;
1035                         return;
1036                 }
1037                 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1038                 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1039
1040                 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1041                 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1042                         decoder_session->abort_flag = true;
1043                         return;
1044                 }
1045                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1046                 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1047
1048                 if(until > 0) {
1049                         FLAC__ASSERT(decoder_session->total_samples != 0);
1050                         FLAC__ASSERT(0 == decoder_session->cue_specification);
1051                         decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1052                 }
1053
1054                 if(decoder_session->bps < 4 || decoder_session->bps > 24) {
1055                         flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 4-24\n", decoder_session->inbasefilename, decoder_session->bps);
1056                         decoder_session->abort_flag = true;
1057                         return;
1058                 }
1059         }
1060         else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1061                 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1062                 if(decoder_session->total_samples == 0) {
1063                         flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1064                         decoder_session->abort_flag = true;
1065                         return;
1066                 }
1067
1068                 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);
1069
1070                 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1071                 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1072
1073                 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1074                 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1075
1076                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1077                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1078                 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1079                 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1080
1081                 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1082         }
1083         else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1084                 if (decoder_session->replaygain.spec.apply) {
1085                         double reference, gain, peak;
1086                         if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
1087                                 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");
1088                                 if(decoder_session->treat_warnings_as_errors) {
1089                                         decoder_session->abort_flag = true;
1090                                         return;
1091                                 }
1092                         }
1093                         else {
1094                                 const char *ls[] = { "no", "peak", "hard" };
1095                                 const char *ns[] = { "no", "low", "medium", "high" };
1096                                 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1097                                 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1098                                 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1099                                 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]);
1100                                 flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1101                                 /* don't check if(decoder_session->treat_warnings_as_errors) because the user explicitly asked for it */
1102                         }
1103                 }
1104                 (void)flac__utils_get_channel_mask_tag(metadata, &decoder_session->channel_mask);
1105         }
1106 }
1107
1108 void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1109 {
1110         DecoderSession *decoder_session = (DecoderSession*)client_data;
1111         (void)decoder;
1112         flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1113         if(!decoder_session->continue_through_decode_errors) {
1114                 decoder_session->abort_flag = true;
1115                 if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1116                         decoder_session->aborting_due_to_unparseable = true;
1117         }
1118 }
1119
1120 void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
1121 {
1122         const int ilen = strlen(d->inbasefilename) + 1;
1123
1124         flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1125
1126         flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
1127
1128         /* print out some more info for some errors: */
1129         if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
1130                 flac__utils_printf(stderr, 1,
1131                         "\n"
1132                         "An error occurred opening the input file; it is likely that it does not exist\n"
1133                         "or is not readable.\n"
1134                 );
1135         }
1136 }
1137
1138 void print_error_with_state(const DecoderSession *d, const char *message)
1139 {
1140         const int ilen = strlen(d->inbasefilename) + 1;
1141
1142         flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1143         flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", FLAC__stream_decoder_get_resolved_state_string(d->decoder));
1144
1145         /* print out some more info for some errors: */
1146         if (d->aborting_due_to_unparseable) {
1147                 flac__utils_printf(stderr, 1,
1148                         "\n"
1149                         "The FLAC stream may have been created by a more advanced encoder.  Try\n"
1150                         "  metaflac --show-vendor-tag %s\n"
1151                         "If the version number is greater than %s, this decoder is probably\n"
1152                         "not able to decode the file.  If the version number is not, the file\n"
1153                         "may be corrupted, or you may have found a bug.  In this case please\n"
1154                         "submit a bug report to\n"
1155                         "    http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
1156                         "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1157                         d->inbasefilename, FLAC__VERSION_STRING
1158                 );
1159         }
1160 }
1161
1162 void print_stats(const DecoderSession *decoder_session)
1163 {
1164         if(flac__utils_verbosity_ >= 2) {
1165 #if defined _MSC_VER || defined __MINGW32__
1166                 /* with MSVC you have to spoon feed it the casting */
1167                 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1168 #else
1169                 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1170 #endif
1171                 if(decoder_session->total_samples > 0) {
1172                         fprintf(stderr, "\r%s: %s%u%% complete",
1173                                 decoder_session->inbasefilename,
1174                                 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1175                                 (unsigned)floor(progress + 0.5)
1176                         );
1177                 }
1178                 else {
1179                         fprintf(stderr, "\r%s: %s %u samples",
1180                                 decoder_session->inbasefilename,
1181                                 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1182                                 (unsigned)decoder_session->samples_processed
1183                         );
1184                 }
1185         }
1186 }