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