add support for Wave64 (SF#1769582: https://sourceforge.net/tracker/index.php?func...
[platform/upstream/flac.git] / src / flac / decode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008  Josh Coalson
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17  */
18
19 #if HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #if defined _WIN32 && !defined __CYGWIN__
24 /* where MSVC puts unlink() */
25 # include <io.h>
26 #else
27 # include <unistd.h>
28 #endif
29 #if defined _MSC_VER || defined __MINGW32__
30 #include <sys/types.h> /* for off_t */
31 #if _MSC_VER <= 1600 /* @@@ [2G limit] */
32 #define fseeko fseek
33 #define ftello ftell
34 #endif
35 #endif
36 #include <errno.h>
37 #include <math.h> /* for floor() */
38 #include <stdio.h> /* for FILE etc. */
39 #include <string.h> /* for strcmp(), strerror() */
40 #include "FLAC/all.h"
41 #include "share/grabbag.h"
42 #include "share/replaygain_synthesis.h"
43 #include "decode.h"
44
45 typedef struct {
46 #if FLAC__HAS_OGG
47         FLAC__bool is_ogg;
48         FLAC__bool use_first_serial_number;
49         long serial_number;
50 #endif
51
52         FileFormat format;
53         FLAC__bool treat_warnings_as_errors;
54         FLAC__bool continue_through_decode_errors;
55         FLAC__bool channel_map_none;
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 *infilename;
73         const char *outfilename;
74
75         FLAC__uint64 samples_processed;
76         unsigned frame_counter;
77         FLAC__bool abort_flag;
78         FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
79         FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */
80
81         FLAC__bool iff_headers_need_fixup;
82
83         FLAC__bool is_big_endian;
84         FLAC__bool is_unsigned_samples;
85         FLAC__bool got_stream_info;
86         FLAC__bool has_md5sum;
87         FLAC__uint64 total_samples;
88         unsigned bps;
89         unsigned channels;
90         unsigned sample_rate;
91         FLAC__uint32 channel_mask;
92
93         /* these are used only in analyze mode */
94         FLAC__uint64 decode_position;
95
96         FLAC__StreamDecoder *decoder;
97
98         FILE *fout;
99
100         foreign_metadata_t *foreign_metadata; /* NULL unless --keep-foreign-metadata requested */
101         off_t fm_offset1, fm_offset2, fm_offset3;
102 } DecoderSession;
103
104
105 static FLAC__bool is_big_endian_host_;
106
107
108 /*
109  * local routines
110  */
111 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool use_first_serial_number, long serial_number, FileFormat format, FLAC__bool treat_warnings_as_errors, FLAC__bool continue_through_decode_errors, FLAC__bool channel_map_none, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, foreign_metadata_t *foreign_metadata, const char *infilename, const char *outfilename);
112 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
113 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, const char *infilename);
114 static FLAC__bool DecoderSession_process(DecoderSession *d);
115 static int DecoderSession_finish_ok(DecoderSession *d);
116 static int DecoderSession_finish_error(DecoderSession *d);
117 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
118 static FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples);
119 static FLAC__bool write_riff_wave_fmt_chunk_body(FILE *f, FLAC__bool is_waveformatextensible, unsigned bps, unsigned channels, unsigned sample_rate, FLAC__uint32 channel_mask);
120 static FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate);
121 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
122 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
123 static FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val);
124 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
125 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
126 static FLAC__bool write_sane_extended(FILE *f, unsigned val);
127 static FLAC__bool fixup_iff_headers(DecoderSession *d);
128 static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
129 static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
130 static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
131 static void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status);
132 static void print_error_with_state(const DecoderSession *d, const char *message);
133 static void print_stats(const DecoderSession *decoder_session);
134
135
136 /*
137  * public routines
138  */
139 int flac__decode_file(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, decode_options_t options)
140 {
141         DecoderSession decoder_session;
142
143         FLAC__ASSERT(
144                 options.format == FORMAT_WAVE ||
145                 options.format == FORMAT_WAVE64 ||
146                 options.format == FORMAT_RF64 ||
147                 options.format == FORMAT_AIFF ||
148                 options.format == FORMAT_AIFF_C ||
149                 options.format == FORMAT_RAW
150         );
151
152         if(options.format == FORMAT_RAW) {
153                 decoder_session.is_big_endian = options.format_options.raw.is_big_endian;
154                 decoder_session.is_unsigned_samples = options.format_options.raw.is_unsigned_samples;
155         }
156
157         if(!
158                 DecoderSession_construct(
159                         &decoder_session,
160 #if FLAC__HAS_OGG
161                         options.is_ogg,
162                         options.use_first_serial_number,
163                         options.serial_number,
164 #else
165                         /*is_ogg=*/false,
166                         /*use_first_serial_number=*/false,
167                         /*serial_number=*/0,
168 #endif
169                         options.format,
170                         options.treat_warnings_as_errors,
171                         options.continue_through_decode_errors,
172                         options.channel_map_none,
173                         options.replaygain_synthesis_spec,
174                         analysis_mode,
175                         aopts,
176                         &options.skip_specification,
177                         &options.until_specification,
178                         options.has_cue_specification? &options.cue_specification : 0,
179                         options.format == FORMAT_RAW? NULL : options.format_options.iff.foreign_metadata,
180                         infilename,
181                         outfilename
182                 )
183         )
184                 return 1;
185
186         if(!DecoderSession_init_decoder(&decoder_session, infilename))
187                 return DecoderSession_finish_error(&decoder_session);
188
189         if(!DecoderSession_process(&decoder_session))
190                 return DecoderSession_finish_error(&decoder_session);
191
192         return DecoderSession_finish_ok(&decoder_session);
193 }
194
195 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool use_first_serial_number, long serial_number, FileFormat format, FLAC__bool treat_warnings_as_errors, FLAC__bool continue_through_decode_errors, FLAC__bool channel_map_none, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, foreign_metadata_t *foreign_metadata, const char *infilename, const char *outfilename)
196 {
197 #if FLAC__HAS_OGG
198         d->is_ogg = is_ogg;
199         d->use_first_serial_number = use_first_serial_number;
200         d->serial_number = serial_number;
201 #else
202         (void)is_ogg;
203         (void)use_first_serial_number;
204         (void)serial_number;
205 #endif
206
207         d->format = format;
208         d->treat_warnings_as_errors = treat_warnings_as_errors;
209         d->continue_through_decode_errors = continue_through_decode_errors;
210         d->channel_map_none = channel_map_none;
211         d->replaygain.spec = replaygain_synthesis_spec;
212         d->replaygain.apply = false;
213         d->replaygain.scale = 0.0;
214         /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
215         d->test_only = (0 == outfilename);
216         d->analysis_mode = analysis_mode;
217         d->aopts = aopts;
218         d->skip_specification = skip_specification;
219         d->until_specification = until_specification;
220         d->cue_specification = cue_specification;
221
222         d->inbasefilename = grabbag__file_get_basename(infilename);
223         d->infilename = infilename;
224         d->outfilename = outfilename;
225
226         d->samples_processed = 0;
227         d->frame_counter = 0;
228         d->abort_flag = false;
229         d->aborting_due_to_until = false;
230         d->aborting_due_to_unparseable = false;
231
232         d->iff_headers_need_fixup = false;
233
234         d->total_samples = 0;
235         d->got_stream_info = false;
236         d->has_md5sum = false;
237         d->bps = 0;
238         d->channels = 0;
239         d->sample_rate = 0;
240         d->channel_mask = 0;
241
242         d->decode_position = 0;
243
244         d->decoder = 0;
245
246         d->fout = 0; /* initialized with an open file later if necessary */
247
248         d->foreign_metadata = foreign_metadata;
249
250         FLAC__ASSERT(!(d->test_only && d->analysis_mode));
251
252         if(!d->test_only) {
253                 if(0 == strcmp(outfilename, "-")) {
254                         d->fout = grabbag__file_get_binary_stdout();
255                 }
256                 else {
257                         if(0 == (d->fout = fopen(outfilename, "wb"))) {
258                                 flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
259                                 DecoderSession_destroy(d, /*error_occurred=*/true);
260                                 return false;
261                         }
262                 }
263         }
264
265         if(analysis_mode)
266                 flac__analyze_init(aopts);
267
268         return true;
269 }
270
271 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
272 {
273         if(0 != d->fout && d->fout != stdout) {
274                 fclose(d->fout);
275                 if(error_occurred)
276                         unlink(d->outfilename);
277         }
278 }
279
280 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, const char *infilename)
281 {
282         FLAC__StreamDecoderInitStatus init_status;
283         FLAC__uint32 test = 1;
284
285         is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
286
287         if(!decoder_session->analysis_mode && !decoder_session->test_only && decoder_session->foreign_metadata) {
288                 const char *error;
289                 if(!flac__foreign_metadata_read_from_flac(decoder_session->foreign_metadata, infilename, &error)) {
290                         flac__utils_printf(stderr, 1, "%s: ERROR reading foreign metadata: %s\n", decoder_session->inbasefilename, error);
291                         return false;
292                 }
293         }
294
295         decoder_session->decoder = FLAC__stream_decoder_new();
296
297         if(0 == decoder_session->decoder) {
298                 flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
299                 return false;
300         }
301
302         FLAC__stream_decoder_set_md5_checking(decoder_session->decoder, true);
303         if (0 != decoder_session->cue_specification)
304                 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_CUESHEET);
305         if (decoder_session->replaygain.spec.apply)
306                 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
307
308 #if FLAC__HAS_OGG
309         if(decoder_session->is_ogg) {
310                 if(!decoder_session->use_first_serial_number)
311                         FLAC__stream_decoder_set_ogg_serial_number(decoder_session->decoder, decoder_session->serial_number);
312                 init_status = FLAC__stream_decoder_init_ogg_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
313         }
314         else
315 #endif
316         {
317                 init_status = FLAC__stream_decoder_init_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
318         }
319
320         if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
321                 print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
322                 return false;
323         }
324
325         return true;
326 }
327
328 FLAC__bool DecoderSession_process(DecoderSession *d)
329 {
330         if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder)) {
331                 flac__utils_printf(stderr, 2, "\n");
332                 print_error_with_state(d, "ERROR while decoding metadata");
333                 return false;
334         }
335         if(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM) {
336                 flac__utils_printf(stderr, 2, "\n");
337                 print_error_with_state(d, "ERROR during metadata decoding");
338                 if(!d->continue_through_decode_errors)
339                         return false;
340         }
341
342         if(d->abort_flag)
343                 return false;
344
345         /* set channel mapping */
346         if(!d->channel_map_none) {
347                 /* currently FLAC order matches SMPTE/WAVEFORMATEXTENSIBLE order, so no reordering is necessary; see encode.c */
348                 /* only the channel mask must be set if it was not already picked up from the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag */
349                 if(d->channels == 1) {
350                         if(d->channel_mask == 0)
351                                 d->channel_mask = 0x0001;
352                 }
353                 else if(d->channels == 2) {
354                         if(d->channel_mask == 0)
355                                 d->channel_mask = 0x0003;
356                 }
357                 else if(d->channels == 3) {
358                         if(d->channel_mask == 0)
359                                 d->channel_mask = 0x0007;
360                 }
361                 else if(d->channels == 4) {
362                         if(d->channel_mask == 0)
363                                 d->channel_mask = 0x0033;
364                 }
365                 else if(d->channels == 5) {
366                         if(d->channel_mask == 0)
367                                 d->channel_mask = 0x0607;
368                 }
369                 else if(d->channels == 6) {
370                         if(d->channel_mask == 0)
371                                 d->channel_mask = 0x060f;
372                 }
373         }
374
375         /* write the WAVE/AIFF headers if necessary */
376         if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
377                 if(!write_iff_headers(d->fout, d, d->total_samples)) {
378                         d->abort_flag = true;
379                         return false;
380                 }
381         }
382
383         if(d->skip_specification->value.samples > 0) {
384                 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
385
386                 if(!FLAC__stream_decoder_seek_absolute(d->decoder, skip)) {
387                         print_error_with_state(d, "ERROR seeking while skipping bytes");
388                         return false;
389                 }
390         }
391         if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder) && !d->aborting_due_to_until) {
392                 flac__utils_printf(stderr, 2, "\n");
393                 print_error_with_state(d, "ERROR while decoding data");
394                 if(!d->continue_through_decode_errors)
395                         return false;
396         }
397         if(
398                 (d->abort_flag && !(d->aborting_due_to_until || d->continue_through_decode_errors)) ||
399                 (FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until)
400         ) {
401                 flac__utils_printf(stderr, 2, "\n");
402                 print_error_with_state(d, "ERROR during decoding");
403                 return false;
404         }
405
406         /* write padding bytes for alignment if necessary */
407         if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
408                 const FLAC__uint64 data_size = d->total_samples * d->channels * ((d->bps+7)/8);
409                 unsigned padding;
410                 if(d->format != FORMAT_WAVE64) {
411                         padding = (unsigned)(data_size & 1);
412                 }
413                 else {
414                         /* 8-byte alignment for Wave64 */
415                         padding = (8 - (unsigned)(data_size & 7)) & 7;
416                 }
417                 for( ; padding > 0; --padding) {
418                         if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
419                                 print_error_with_state(
420                                         d,
421                                         d->format == FORMAT_WAVE?  "ERROR writing pad byte to WAVE data chunk" :
422                                         d->format == FORMAT_WAVE64?  "ERROR writing pad bytes to WAVE64 data chunk" :
423                                         d->format == FORMAT_RF64?  "ERROR writing pad byte to RF64 data chunk" :
424                                         "ERROR writing pad byte to AIFF SSND chunk"
425                                 );
426                                 return false;
427                         }
428                 }
429         }
430
431         return true;
432 }
433
434 int DecoderSession_finish_ok(DecoderSession *d)
435 {
436         FLAC__bool ok = true, md5_failure = false;
437
438         if(d->decoder) {
439                 md5_failure = !FLAC__stream_decoder_finish(d->decoder) && !d->aborting_due_to_until;
440                 print_stats(d);
441                 FLAC__stream_decoder_delete(d->decoder);
442         }
443         if(d->analysis_mode)
444                 flac__analyze_finish(d->aopts);
445         if(md5_failure) {
446                 flac__utils_printf(stderr, 1, "\r%s: ERROR, MD5 signature mismatch\n", d->inbasefilename);
447                 ok = d->continue_through_decode_errors;
448         }
449         else {
450                 if(!d->got_stream_info) {
451                         flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since there was no STREAMINFO\n", d->inbasefilename);
452                         ok = !d->treat_warnings_as_errors;
453                 }
454                 else if(!d->has_md5sum) {
455                         flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since it was unset in the STREAMINFO\n", d->inbasefilename);
456                         ok = !d->treat_warnings_as_errors;
457                 }
458                 flac__utils_printf(stderr, 2, "\r%s: %s         \n", d->inbasefilename, d->test_only? "ok           ":d->analysis_mode?"done           ":"done");
459         }
460         DecoderSession_destroy(d, /*error_occurred=*/!ok);
461         if(!d->analysis_mode && !d->test_only && d->format != FORMAT_RAW) {
462                 if(d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))) {
463                         if(!fixup_iff_headers(d))
464                                 return 1;
465                 }
466                 if(d->foreign_metadata) {
467                         const char *error;
468                         if(!flac__foreign_metadata_write_to_iff(d->foreign_metadata, d->infilename, d->outfilename, d->fm_offset1, d->fm_offset2, d->fm_offset3, &error)) {
469                                 flac__utils_printf(stderr, 1, "ERROR updating foreign metadata from %s to %s: %s\n", d->infilename, d->outfilename, error);
470                                 return 1;
471                         }
472                 }
473         }
474         return ok? 0 : 1;
475 }
476
477 int DecoderSession_finish_error(DecoderSession *d)
478 {
479         if(d->decoder) {
480                 (void)FLAC__stream_decoder_finish(d->decoder);
481                 FLAC__stream_decoder_delete(d->decoder);
482         }
483         if(d->analysis_mode)
484                 flac__analyze_finish(d->aopts);
485         DecoderSession_destroy(d, /*error_occurred=*/true);
486         return 1;
487 }
488
489 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
490 {
491         /* convert from mm:ss.sss to sample number if necessary */
492         flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
493
494         /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
495         if(spec->is_relative && spec->value.samples == 0) {
496                 spec->is_relative = false;
497                 return true;
498         }
499
500         /* in any other case the total samples in the input must be known */
501         if(total_samples_in_input == 0) {
502                 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
503                 return false;
504         }
505
506         FLAC__ASSERT(spec->value_is_samples);
507
508         /* convert relative specifications to absolute */
509         if(spec->is_relative) {
510                 if(spec->value.samples <= 0)
511                         spec->value.samples += (FLAC__int64)total_samples_in_input;
512                 else
513                         spec->value.samples += skip;
514                 spec->is_relative = false;
515         }
516
517         /* error check */
518         if(spec->value.samples < 0) {
519                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
520                 return false;
521         }
522         if((FLAC__uint64)spec->value.samples <= skip) {
523                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
524                 return false;
525         }
526         if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
527                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
528                 return false;
529         }
530
531         return true;
532 }
533
534 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
535 {
536         const FileFormat format = decoder_session->format;
537         const char *fmt_desc =
538                 format==FORMAT_WAVE? "WAVE" :
539                 format==FORMAT_WAVE64? "Wave64" :
540                 format==FORMAT_RF64? "RF64" :
541                 "AIFF";
542         const FLAC__bool is_waveformatextensible =
543                 (format == FORMAT_WAVE || format == FORMAT_WAVE64 || format == FORMAT_RF64) &&
544                 (
545                         decoder_session->channel_mask == 2 ||
546                         decoder_session->channel_mask > 3 ||
547                         decoder_session->bps%8 ||
548                         decoder_session->channels > 2
549                 );
550         const FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
551         const FLAC__uint64 aligned_data_size =
552                 format == FORMAT_WAVE64?
553                         (data_size+7) & (~(FLAC__uint64)7) :
554                         (data_size+1) & (~(FLAC__uint64)1);
555
556         FLAC__uint64 iff_size;
557         unsigned foreign_metadata_size = 0; /* size of all non-audio non-fmt/COMM foreign metadata chunks */
558         foreign_metadata_t *fm = decoder_session->foreign_metadata;
559         size_t i;
560
561         FLAC__ASSERT(
562                 format == FORMAT_WAVE ||
563                 format == FORMAT_WAVE64 ||
564                 format == FORMAT_RF64 ||
565                 format == FORMAT_AIFF ||
566                 format == FORMAT_AIFF_C
567         );
568
569         if(samples == 0) {
570                 if(f == stdout) {
571                         flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
572                         flac__utils_printf(stderr, 1, "             Generated %s file will have a data chunk size of 0.  Try\n", fmt_desc);
573                         flac__utils_printf(stderr, 1, "             decoding directly to a file instead.\n");
574                         if(decoder_session->treat_warnings_as_errors)
575                                 return false;
576                 }
577                 else {
578                         decoder_session->iff_headers_need_fixup = true;
579                 }
580         }
581
582         if(fm) {
583                 FLAC__ASSERT(fm->format_block);
584                 FLAC__ASSERT(fm->audio_block);
585                 FLAC__ASSERT(fm->format_block < fm->audio_block);
586                 /* calc foreign metadata size; we always skip the first chunk, ds64 chunk, format chunk, and sound chunk since we write our own */
587                 for(i = format==FORMAT_RF64?2:1; i < fm->num_blocks; i++) {
588                         if(i != fm->format_block && i != fm->audio_block)
589                                 foreign_metadata_size += fm->blocks[i].size;
590                 }
591         }
592
593         if(samples == 0)
594                 iff_size = 0;
595         else if(format == FORMAT_WAVE || format == FORMAT_RF64)
596                 /* 4 for WAVE form bytes */
597                 /* +{36,0} for ds64 chunk */
598                 /* +8+{40,16} for fmt chunk header and body */
599                 /* +8 for data chunk header */
600                 iff_size = 4 + (format==FORMAT_RF64?36:0) + 8+(is_waveformatextensible?40:16) + 8 + foreign_metadata_size + aligned_data_size;
601         else if(format == FORMAT_WAVE64)
602                 /* 16+8 for RIFF GUID and size field */
603                 /* +16 for WAVE GUID */
604                 /* +16+8+{40,16} for fmt chunk header (GUID and size field) and body */
605                 /* +16+8 for data chunk header (GUID and size field) */
606                 iff_size = 16+8 + 16 + 16+8+(is_waveformatextensible?40:16) + 16+8 + foreign_metadata_size + aligned_data_size;
607         else /* AIFF */
608                 /* @@@@@@ can ssnd_offset_size be odd and hence screw up our alignment logic? */
609                 iff_size = 46 + foreign_metadata_size + aligned_data_size + (fm? fm->ssnd_offset_size : 0);
610
611         if(format != FORMAT_WAVE64 && format != FORMAT_RF64 && iff_size >= 0xFFFFFFF4) {
612                 flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file\n", decoder_session->inbasefilename, fmt_desc);
613                 return false;
614         }
615
616         if(format == FORMAT_WAVE || format == FORMAT_WAVE64 || format == FORMAT_RF64) {
617                 /* RIFF header */
618                 switch(format) {
619                         case FORMAT_WAVE:
620                                 if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
621                                         return false;
622                                 if(!write_little_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
623                                         return false;
624                                 if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
625                                         return false;
626                                 break;
627                         case FORMAT_WAVE64:
628                                 /* RIFF GUID 66666972-912E-11CF-A5D6-28DB04C10000 */
629                                 if(flac__utils_fwrite("\x72\x69\x66\x66\x2E\x91\xCF\x11\xD6\xA5\x28\xDB\x04\xC1\x00\x00", 1, 16, f) != 16)
630                                         return false;
631                                 if(!write_little_endian_uint64(f, iff_size))
632                                         return false;
633                                 /* WAVE GUID 65766177-ACF3-11D3-8CD1-00C04F8EDB8A */
634                                 if(flac__utils_fwrite("\x77\x61\x76\x65\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
635                                         return false;
636                                 break;
637                         case FORMAT_RF64:
638                                 if(flac__utils_fwrite("RF64", 1, 4, f) != 4)
639                                         return false;
640                                 if(!write_little_endian_uint32(f, 0xffffffff))
641                                         return false;
642                                 if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
643                                         return false;
644                                 break;
645                         default:
646                                 return false;
647                 }
648
649                 /* ds64 chunk for RF64 */
650                 if(format == FORMAT_RF64) {
651                         if(flac__utils_fwrite("ds64", 1, 4, f) != 4)
652                                 return false;
653
654                         if(!write_little_endian_uint32(f, 28)) /* chunk size */
655                                 return false;
656
657                         if(!write_little_endian_uint64(f, iff_size))
658                                 return false;
659
660                         if(!write_little_endian_uint64(f, data_size))
661                                 return false;
662
663                         if(!write_little_endian_uint64(f, samples)) /*@@@@@@ correct? */
664                                 return false;
665
666                         if(!write_little_endian_uint32(f, 0)) /* table size */
667                                 return false;
668                 }
669
670                 decoder_session->fm_offset1 = ftello(f);
671
672                 if(fm) {
673                         /* seek forward to {allocate} or {skip over already-written chunks} before "fmt " */
674                         for(i = format==FORMAT_RF64?2:1; i < fm->format_block; i++) {
675                                 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
676                                         flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"fmt \"\n", decoder_session->inbasefilename);
677                                         return false;
678                                 }
679                         }
680                 }
681
682                 if(format != FORMAT_WAVE64) {
683                         if(flac__utils_fwrite("fmt ", 1, 4, f) != 4)
684                                 return false;
685                         if(!write_little_endian_uint32(f, is_waveformatextensible? 40 : 16)) /* chunk size */
686                                 return false;
687                 }
688                 else { /* Wave64 */
689                         /* fmt GUID 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A */
690                         if(flac__utils_fwrite("\x66\x6D\x74\x20\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
691                                 return false;
692                         /* chunk size (+16+8 for GUID and size fields) */
693                         if(!write_little_endian_uint64(f, 16+8+(is_waveformatextensible?40:16)))
694                                 return false;
695                 }
696
697                 if(!write_riff_wave_fmt_chunk_body(f, is_waveformatextensible, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate, decoder_session->channel_mask))
698                         return false;
699
700                 decoder_session->fm_offset2 = ftello(f);
701
702                 if(fm) {
703                         /* seek forward to {allocate} or {skip over already-written chunks} after "fmt " but before "data" */
704                         for(i = fm->format_block+1; i < fm->audio_block; i++) {
705                                 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
706                                         flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"fmt \"\n", decoder_session->inbasefilename);
707                                         return false;
708                                 }
709                         }
710                 }
711
712                 if(format != FORMAT_WAVE64) {
713                         if(flac__utils_fwrite("data", 1, 4, f) != 4)
714                                 return false;
715                         if(!write_little_endian_uint32(f, format==FORMAT_RF64? 0xffffffff : (FLAC__uint32)data_size))
716                                 return false;
717                 }
718                 else { /* Wave64 */
719                         /* data GUID 61746164-ACF3-11D3-8CD1-00C04F8EDB8A */
720                         if(flac__utils_fwrite("\x64\x61\x74\x61\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
721                                 return false;
722                         /* +16+8 for GUID and size fields */
723                         if(!write_little_endian_uint64(f, 16+8 + data_size))
724                                 return false;
725                 }
726
727                 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
728         }
729         else {
730                 FLAC__uint32 ssnd_offset_size = (fm? fm->ssnd_offset_size : 0);
731
732                 if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
733                         return false;
734
735                 if(!write_big_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
736                         return false;
737
738                 if(flac__utils_fwrite("AIFF", 1, 4, f) != 4)
739                         return false;
740
741                 decoder_session->fm_offset1 = ftello(f);
742
743                 if(fm) {
744                         /* seek forward to {allocate} or {skip over already-written chunks} before "COMM" */
745                         for(i = 1; i < fm->format_block; i++) {
746                                 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
747                                         flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"COMM\"\n", decoder_session->inbasefilename);
748                                         return false;
749                                 }
750                         }
751                 }
752
753                 if(!write_aiff_form_comm_chunk(f, samples, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate))
754                         return false;
755
756                 decoder_session->fm_offset2 = ftello(f);
757
758                 if(fm) {
759                         /* seek forward to {allocate} or {skip over already-written chunks} after "COMM" but before "SSND" */
760                         for(i = fm->format_block+1; i < fm->audio_block; i++) {
761                                 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
762                                         flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"COMM\"\n", decoder_session->inbasefilename);
763                                         return false;
764                                 }
765                         }
766                 }
767
768                 if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
769                         return false;
770
771                 if(!write_big_endian_uint32(f, (FLAC__uint32)data_size + 8 + ssnd_offset_size)) /* data size */
772                         return false;
773
774                 if(!write_big_endian_uint32(f, ssnd_offset_size))
775                         return false;
776
777                 if(!write_big_endian_uint32(f, 0/*block_size*/))
778                         return false;
779
780                 if(ssnd_offset_size) {
781                         /* seek forward to {allocate} or {skip over already-written} SSND offset */
782                         if(fseeko(f, ssnd_offset_size, SEEK_CUR) < 0) {
783                                 flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping \"SSND\" offset\n", decoder_session->inbasefilename);
784                                 return false;
785                         }
786                 }
787
788                 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
789         }
790
791         return true;
792 }
793
794 FLAC__bool write_riff_wave_fmt_chunk_body(FILE *f, FLAC__bool is_waveformatextensible, unsigned bps, unsigned channels, unsigned sample_rate, FLAC__uint32 channel_mask)
795 {
796         if(!write_little_endian_uint16(f, (FLAC__uint16)(is_waveformatextensible? 65534 : 1))) /* compression code */
797                 return false;
798
799         if(!write_little_endian_uint16(f, (FLAC__uint16)channels))
800                 return false;
801
802         if(!write_little_endian_uint32(f, sample_rate))
803                 return false;
804
805         if(!write_little_endian_uint32(f, sample_rate * channels * ((bps+7) / 8)))
806                 return false;
807
808         if(!write_little_endian_uint16(f, (FLAC__uint16)(channels * ((bps+7) / 8)))) /* block align */
809                 return false;
810
811         if(!write_little_endian_uint16(f, (FLAC__uint16)(((bps+7)/8)*8))) /* bits per sample */
812                 return false;
813
814         if(is_waveformatextensible) {
815                 if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */
816                         return false;
817
818                 if(!write_little_endian_uint16(f, (FLAC__uint16)bps)) /* validBitsPerSample */
819                         return false;
820
821                 if(!write_little_endian_uint32(f, channel_mask))
822                         return false;
823
824                 /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */
825                 if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16)
826                         return false;
827         }
828
829         return true;
830 }
831
832 FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate)
833 {
834         FLAC__ASSERT(samples <= 0xffffffff);
835
836         if(flac__utils_fwrite("COMM", 1, 4, f) != 4)
837                 return false;
838
839         if(!write_big_endian_uint32(f, 18)) /* chunk size = 18 */
840                 return false;
841
842         if(!write_big_endian_uint16(f, (FLAC__uint16)channels))
843                 return false;
844
845         if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
846                 return false;
847
848         if(!write_big_endian_uint16(f, (FLAC__uint16)bps))
849                 return false;
850
851         if(!write_sane_extended(f, sample_rate))
852                 return false;
853
854         return true;
855 }
856
857 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
858 {
859         FLAC__byte *b = (FLAC__byte*)(&val);
860         if(is_big_endian_host_) {
861                 FLAC__byte tmp;
862                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
863         }
864         return flac__utils_fwrite(b, 1, 2, f) == 2;
865 }
866
867 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
868 {
869         FLAC__byte *b = (FLAC__byte*)(&val);
870         if(is_big_endian_host_) {
871                 FLAC__byte tmp;
872                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
873                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
874         }
875         return flac__utils_fwrite(b, 1, 4, f) == 4;
876 }
877
878 FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val)
879 {
880         FLAC__byte *b = (FLAC__byte*)(&val);
881         if(is_big_endian_host_) {
882                 FLAC__byte tmp;
883                 tmp = b[7]; b[7] = b[0]; b[0] = tmp;
884                 tmp = b[6]; b[6] = b[1]; b[1] = tmp;
885                 tmp = b[5]; b[5] = b[2]; b[2] = tmp;
886                 tmp = b[4]; b[4] = b[3]; b[3] = tmp;
887         }
888         return flac__utils_fwrite(b, 1, 8, f) == 8;
889 }
890
891 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
892 {
893         FLAC__byte *b = (FLAC__byte*)(&val);
894         if(!is_big_endian_host_) {
895                 FLAC__byte tmp;
896                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
897         }
898         return flac__utils_fwrite(b, 1, 2, f) == 2;
899 }
900
901 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
902 {
903         FLAC__byte *b = (FLAC__byte*)(&val);
904         if(!is_big_endian_host_) {
905                 FLAC__byte tmp;
906                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
907                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
908         }
909         return flac__utils_fwrite(b, 1, 4, f) == 4;
910 }
911
912 FLAC__bool write_sane_extended(FILE *f, unsigned val)
913         /* Write to 'f' a SANE extended representation of 'val'.  Return false if
914         * the write succeeds; return true otherwise.
915         *
916         * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
917         * of exponent, and 64 bits of significand (mantissa).  Unlike most IEEE-754
918         * representations, it does not imply a 1 above the MSB of the significand.
919         *
920         * Preconditions:
921         *  val!=0U
922         */
923 {
924         unsigned int shift, exponent;
925
926         FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
927
928         for(shift= 0U; (val>>(31-shift))==0U; ++shift)
929                 ;
930         val<<= shift;
931         exponent= 63U-(shift+32U); /* add 32 for unused second word */
932
933         if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
934                 return false;
935         if(!write_big_endian_uint32(f, val))
936                 return false;
937         if(!write_big_endian_uint32(f, 0)) /* unused second word */
938                 return false;
939
940         return true;
941 }
942
943 FLAC__bool fixup_iff_headers(DecoderSession *d)
944 {
945         const char *fmt_desc =
946                 d->format==FORMAT_WAVE? "WAVE" :
947                 d->format==FORMAT_WAVE64? "Wave64" :
948                 d->format==FORMAT_RF64? "RF64" :
949                 "AIFF";
950         FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
951
952         if(0 == f) {
953                 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));
954                 return false;
955         }
956
957         if(!write_iff_headers(f, d, d->samples_processed)) {
958                 fclose(f);
959                 return false;
960         }
961
962         fclose(f);
963         return true;
964 }
965
966 FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
967 {
968         DecoderSession *decoder_session = (DecoderSession*)client_data;
969         FILE *fout = decoder_session->fout;
970         const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
971         const unsigned shift = (decoder_session->format != FORMAT_RAW && (bps%8))? 8-(bps%8): 0;
972         FLAC__bool is_big_endian = (
973                 decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? true : (
974                 decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 ? false :
975                 decoder_session->is_big_endian
976         ));
977         FLAC__bool is_unsigned_samples = (
978                 decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? false : (
979                 decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 ? bps<=8 :
980                 decoder_session->is_unsigned_samples
981         ));
982         unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
983         unsigned frame_bytes = 0;
984         static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
985         FLAC__uint8  *u8buffer  = (FLAC__uint8  *)s8buffer;
986         FLAC__int16  *s16buffer = (FLAC__int16  *)s8buffer;
987         FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
988         FLAC__int32  *s32buffer = (FLAC__int32  *)s8buffer;
989         FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
990         size_t bytes_to_write = 0;
991
992         (void)decoder;
993
994         if(decoder_session->abort_flag)
995                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
996
997         /* sanity-check the bits-per-sample */
998         if(decoder_session->bps) {
999                 if(bps != decoder_session->bps) {
1000                         if(decoder_session->got_stream_info)
1001                                 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);
1002                         else
1003                                 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);
1004                         if(!decoder_session->continue_through_decode_errors)
1005                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1006                 }
1007         }
1008         else {
1009                 /* must not have gotten STREAMINFO, save the bps from the frame header */
1010                 FLAC__ASSERT(!decoder_session->got_stream_info);
1011                 decoder_session->bps = bps;
1012         }
1013
1014         /* sanity-check the #channels */
1015         if(decoder_session->channels) {
1016                 if(channels != decoder_session->channels) {
1017                         if(decoder_session->got_stream_info)
1018                                 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
1019                         else
1020                                 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);
1021                         if(!decoder_session->continue_through_decode_errors)
1022                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1023                 }
1024         }
1025         else {
1026                 /* must not have gotten STREAMINFO, save the #channels from the frame header */
1027                 FLAC__ASSERT(!decoder_session->got_stream_info);
1028                 decoder_session->channels = channels;
1029         }
1030
1031         /* sanity-check the sample rate */
1032         if(decoder_session->sample_rate) {
1033                 if(frame->header.sample_rate != decoder_session->sample_rate) {
1034                         if(decoder_session->got_stream_info)
1035                                 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);
1036                         else
1037                                 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);
1038                         if(!decoder_session->continue_through_decode_errors)
1039                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1040                 }
1041         }
1042         else {
1043                 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
1044                 FLAC__ASSERT(!decoder_session->got_stream_info);
1045                 decoder_session->sample_rate = frame->header.sample_rate;
1046         }
1047
1048         /*
1049          * limit the number of samples to accept based on --until
1050          */
1051         FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1052         /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
1053         if(decoder_session->skip_specification->is_relative) {
1054                 if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
1055                         decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
1056                 else {
1057                         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);
1058                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1059                 }
1060         }
1061         if(decoder_session->until_specification->is_relative) {
1062                 if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
1063                         decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
1064                 else {
1065                         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);
1066                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1067                 }
1068         }
1069         FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1070         FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1071         if(decoder_session->until_specification->value.samples > 0) {
1072                 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1073                 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1074                 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
1075                 FLAC__ASSERT(until >= input_samples_passed);
1076                 if(input_samples_passed + wide_samples > until)
1077                         wide_samples = (unsigned)(until - input_samples_passed);
1078                 if (wide_samples == 0) {
1079                         decoder_session->abort_flag = true;
1080                         decoder_session->aborting_due_to_until = true;
1081                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1082                 }
1083         }
1084
1085         if(decoder_session->analysis_mode) {
1086                 FLAC__uint64 dpos;
1087                 FLAC__stream_decoder_get_decode_position(decoder_session->decoder, &dpos);
1088                 frame_bytes = (unsigned)(dpos-decoder_session->decode_position);
1089                 decoder_session->decode_position = dpos;
1090         }
1091
1092         if(wide_samples > 0) {
1093                 decoder_session->samples_processed += wide_samples;
1094                 decoder_session->frame_counter++;
1095
1096                 if(!(decoder_session->frame_counter & 0x3f))
1097                         print_stats(decoder_session);
1098
1099                 if(decoder_session->analysis_mode) {
1100                         flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->decode_position-frame_bytes, frame_bytes, decoder_session->aopts, fout);
1101                 }
1102                 else if(!decoder_session->test_only) {
1103                         if(shift && !decoder_session->replaygain.apply) {
1104                                 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1105                                         for(channel = 0; channel < channels; channel++)
1106                                                 ((FLAC__int32**)buffer)[channel][wide_sample] <<= shift;/*@@@@@@un-const'ing the buffer is hacky but safe*/
1107                         }
1108                         if(decoder_session->replaygain.apply) {
1109                                 bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
1110                                         u8buffer,
1111                                         !is_big_endian,
1112                                         is_unsigned_samples,
1113                                         buffer,
1114                                         wide_samples,
1115                                         channels,
1116                                         bps, /* source_bps */
1117                                         bps+shift, /* target_bps */
1118                                         decoder_session->replaygain.scale,
1119                                         decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
1120                                         decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
1121                                         &decoder_session->replaygain.dither_context
1122                                 );
1123                         }
1124                         /* first some special code for common cases */
1125                         else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 2 && bps+shift == 16) {
1126                                 FLAC__int16 *buf1_ = s16buffer + 1;
1127                                 if(is_big_endian)
1128                                         memcpy(s16buffer, ((FLAC__byte*)(buffer[0]))+2, sizeof(FLAC__int32) * wide_samples - 2);
1129                                 else
1130                                         memcpy(s16buffer, buffer[0], sizeof(FLAC__int32) * wide_samples);
1131                                 for(sample = 0; sample < wide_samples; sample++, buf1_+=2)
1132                                         *buf1_ = (FLAC__int16)buffer[1][sample];
1133                                 bytes_to_write = 4 * sample;
1134                         }
1135                         else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 1 && bps+shift == 16) {
1136                                 FLAC__int16 *buf1_ = s16buffer;
1137                                 for(sample = 0; sample < wide_samples; sample++)
1138                                         *buf1_++ = (FLAC__int16)buffer[0][sample];
1139                                 bytes_to_write = 2 * sample;
1140                         }
1141                         /* generic code for the rest */
1142                         else if(bps+shift == 16) {
1143                                 if(is_unsigned_samples) {
1144                                         if(channels == 2) {
1145                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1146                                                         u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1147                                                         u16buffer[sample++] = (FLAC__uint16)(buffer[1][wide_sample] + 0x8000);
1148                                                 }
1149                                         }
1150                                         else if(channels == 1) {
1151                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1152                                                         u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1153                                         }
1154                                         else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1155                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1156                                                         for(channel = 0; channel < channels; channel++, sample++)
1157                                                                 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
1158                                         }
1159                                 }
1160                                 else {
1161                                         if(channels == 2) {
1162                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1163                                                         s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1164                                                         s16buffer[sample++] = (FLAC__int16)(buffer[1][wide_sample]);
1165                                                 }
1166                                         }
1167                                         else if(channels == 1) {
1168                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1169                                                         s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1170                                         }
1171                                         else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1172                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1173                                                         for(channel = 0; channel < channels; channel++, sample++)
1174                                                                 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
1175                                         }
1176                                 }
1177                                 if(is_big_endian != is_big_endian_host_) {
1178                                         unsigned char tmp;
1179                                         const unsigned bytes = sample * 2;
1180                                         for(byte = 0; byte < bytes; byte += 2) {
1181                                                 tmp = u8buffer[byte];
1182                                                 u8buffer[byte] = u8buffer[byte+1];
1183                                                 u8buffer[byte+1] = tmp;
1184                                         }
1185                                 }
1186                                 bytes_to_write = 2 * sample;
1187                         }
1188                         else if(bps+shift == 24) {
1189                                 if(is_unsigned_samples) {
1190                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1191                                                 for(channel = 0; channel < channels; channel++, sample++)
1192                                                         u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
1193                                 }
1194                                 else {
1195                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1196                                                 for(channel = 0; channel < channels; channel++, sample++)
1197                                                         s32buffer[sample] = buffer[channel][wide_sample];
1198                                 }
1199                                 if(is_big_endian != is_big_endian_host_) {
1200                                         unsigned char tmp;
1201                                         const unsigned bytes = sample * 4;
1202                                         for(byte = 0; byte < bytes; byte += 4) {
1203                                                 tmp = u8buffer[byte];
1204                                                 u8buffer[byte] = u8buffer[byte+3];
1205                                                 u8buffer[byte+3] = tmp;
1206                                                 tmp = u8buffer[byte+1];
1207                                                 u8buffer[byte+1] = u8buffer[byte+2];
1208                                                 u8buffer[byte+2] = tmp;
1209                                         }
1210                                 }
1211                                 if(is_big_endian) {
1212                                         unsigned lbyte;
1213                                         const unsigned bytes = sample * 4;
1214                                         for(lbyte = byte = 0; byte < bytes; ) {
1215                                                 byte++;
1216                                                 u8buffer[lbyte++] = u8buffer[byte++];
1217                                                 u8buffer[lbyte++] = u8buffer[byte++];
1218                                                 u8buffer[lbyte++] = u8buffer[byte++];
1219                                         }
1220                                 }
1221                                 else {
1222                                         unsigned lbyte;
1223                                         const unsigned bytes = sample * 4;
1224                                         for(lbyte = byte = 0; byte < bytes; ) {
1225                                                 u8buffer[lbyte++] = u8buffer[byte++];
1226                                                 u8buffer[lbyte++] = u8buffer[byte++];
1227                                                 u8buffer[lbyte++] = u8buffer[byte++];
1228                                                 byte++;
1229                                         }
1230                                 }
1231                                 bytes_to_write = 3 * sample;
1232                         }
1233                         else if(bps+shift == 8) {
1234                                 if(is_unsigned_samples) {
1235                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1236                                                 for(channel = 0; channel < channels; channel++, sample++)
1237                                                         u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
1238                                 }
1239                                 else {
1240                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1241                                                 for(channel = 0; channel < channels; channel++, sample++)
1242                                                         s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
1243                                 }
1244                                 bytes_to_write = sample;
1245                         }
1246                         else {
1247                                 FLAC__ASSERT(0);
1248                                 /* double protection */
1249                                 decoder_session->abort_flag = true;
1250                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1251                         }
1252                 }
1253         }
1254         if(bytes_to_write > 0) {
1255                 if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
1256                         /* if a pipe closed when writing to stdout, we let it go without an error message */
1257                         if(errno == EPIPE && decoder_session->fout == stdout)
1258                                 decoder_session->aborting_due_to_until = true;
1259                         decoder_session->abort_flag = true;
1260                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1261                 }
1262         }
1263         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1264 }
1265
1266 void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1267 {
1268         DecoderSession *decoder_session = (DecoderSession*)client_data;
1269
1270         if(decoder_session->analysis_mode)
1271                 FLAC__stream_decoder_get_decode_position(decoder, &decoder_session->decode_position);
1272
1273         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
1274                 FLAC__uint64 skip, until;
1275                 decoder_session->got_stream_info = true;
1276                 decoder_session->has_md5sum = memcmp(metadata->data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16);
1277                 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1278                 decoder_session->channels = metadata->data.stream_info.channels;
1279                 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1280
1281                 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
1282                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1283                 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1284
1285                 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1286                 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1287                         flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1288                         decoder_session->abort_flag = true;
1289                         return;
1290                 }
1291                 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1292                         flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1293                         decoder_session->abort_flag = true;
1294                         return;
1295                 }
1296                 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1297                 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1298
1299                 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1300                 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1301                         decoder_session->abort_flag = true;
1302                         return;
1303                 }
1304                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1305                 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1306
1307                 if(until > 0) {
1308                         FLAC__ASSERT(decoder_session->total_samples != 0);
1309                         FLAC__ASSERT(0 == decoder_session->cue_specification);
1310                         decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1311                 }
1312
1313                 if(decoder_session->bps < 4 || decoder_session->bps > 24) {
1314                         flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 4-24\n", decoder_session->inbasefilename, decoder_session->bps);
1315                         decoder_session->abort_flag = true;
1316                         return;
1317                 }
1318         }
1319         else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1320                 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1321                 if(decoder_session->total_samples == 0) {
1322                         flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1323                         decoder_session->abort_flag = true;
1324                         return;
1325                 }
1326
1327                 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);
1328
1329                 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1330                 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1331
1332                 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1333                 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1334
1335                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1336                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1337                 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1338                 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1339
1340                 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1341         }
1342         else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1343                 if (decoder_session->replaygain.spec.apply) {
1344                         double reference, gain, peak;
1345                         if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
1346                                 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");
1347                                 if(decoder_session->treat_warnings_as_errors) {
1348                                         decoder_session->abort_flag = true;
1349                                         return;
1350                                 }
1351                         }
1352                         else {
1353                                 const char *ls[] = { "no", "peak", "hard" };
1354                                 const char *ns[] = { "no", "low", "medium", "high" };
1355                                 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1356                                 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1357                                 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1358                                 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]);
1359                                 flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1360                                 /* don't check if(decoder_session->treat_warnings_as_errors) because the user explicitly asked for it */
1361                         }
1362                 }
1363                 (void)flac__utils_get_channel_mask_tag(metadata, &decoder_session->channel_mask);
1364         }
1365 }
1366
1367 void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1368 {
1369         DecoderSession *decoder_session = (DecoderSession*)client_data;
1370         (void)decoder;
1371         flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1372         if(!decoder_session->continue_through_decode_errors) {
1373                 decoder_session->abort_flag = true;
1374                 if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1375                         decoder_session->aborting_due_to_unparseable = true;
1376         }
1377 }
1378
1379 void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
1380 {
1381         const int ilen = strlen(d->inbasefilename) + 1;
1382
1383         flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1384
1385         flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
1386
1387         /* print out some more info for some errors: */
1388         if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
1389                 flac__utils_printf(stderr, 1,
1390                         "\n"
1391                         "An error occurred opening the input file; it is likely that it does not exist\n"
1392                         "or is not readable.\n"
1393                 );
1394         }
1395 }
1396
1397 void print_error_with_state(const DecoderSession *d, const char *message)
1398 {
1399         const int ilen = strlen(d->inbasefilename) + 1;
1400
1401         flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1402         flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", FLAC__stream_decoder_get_resolved_state_string(d->decoder));
1403
1404         /* print out some more info for some errors: */
1405         if (d->aborting_due_to_unparseable) {
1406                 flac__utils_printf(stderr, 1,
1407                         "\n"
1408                         "The FLAC stream may have been created by a more advanced encoder.  Try\n"
1409                         "  metaflac --show-vendor-tag %s\n"
1410                         "If the version number is greater than %s, this decoder is probably\n"
1411                         "not able to decode the file.  If the version number is not, the file\n"
1412                         "may be corrupted, or you may have found a bug.  In this case please\n"
1413                         "submit a bug report to\n"
1414                         "    http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
1415                         "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1416                         d->inbasefilename, FLAC__VERSION_STRING
1417                 );
1418         }
1419 }
1420
1421 void print_stats(const DecoderSession *decoder_session)
1422 {
1423         if(flac__utils_verbosity_ >= 2) {
1424 #if defined _MSC_VER || defined __MINGW32__
1425                 /* with MSVC you have to spoon feed it the casting */
1426                 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1427 #else
1428                 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1429 #endif
1430                 if(decoder_session->total_samples > 0) {
1431                         fprintf(stderr, "\r%s: %s%u%% complete",
1432                                 decoder_session->inbasefilename,
1433                                 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1434                                 (unsigned)floor(progress + 0.5)
1435                         );
1436                 }
1437                 else {
1438                         fprintf(stderr, "\r%s: %s %u samples",
1439                                 decoder_session->inbasefilename,
1440                                 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1441                                 (unsigned)decoder_session->samples_processed
1442                         );
1443                 }
1444         }
1445 }