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