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