update Makefile.lite system to work on x86_64 linux
[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                 iff_size = 46 + foreign_metadata_size + aligned_data_size;
609
610         if(format != FORMAT_WAVE64 && format != FORMAT_RF64 && iff_size >= 0xFFFFFFF4) {
611                 flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file\n", decoder_session->inbasefilename, fmt_desc);
612                 return false;
613         }
614
615         if(format == FORMAT_WAVE || format == FORMAT_WAVE64 || format == FORMAT_RF64) {
616                 /* RIFF header */
617                 switch(format) {
618                         case FORMAT_WAVE:
619                                 if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
620                                         return false;
621                                 if(!write_little_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
622                                         return false;
623                                 if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
624                                         return false;
625                                 break;
626                         case FORMAT_WAVE64:
627                                 /* RIFF GUID 66666972-912E-11CF-A5D6-28DB04C10000 */
628                                 if(flac__utils_fwrite("\x72\x69\x66\x66\x2E\x91\xCF\x11\xD6\xA5\x28\xDB\x04\xC1\x00\x00", 1, 16, f) != 16)
629                                         return false;
630                                 if(!write_little_endian_uint64(f, iff_size))
631                                         return false;
632                                 /* WAVE GUID 65766177-ACF3-11D3-8CD1-00C04F8EDB8A */
633                                 if(flac__utils_fwrite("\x77\x61\x76\x65\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
634                                         return false;
635                                 break;
636                         case FORMAT_RF64:
637                                 if(flac__utils_fwrite("RF64", 1, 4, f) != 4)
638                                         return false;
639                                 if(!write_little_endian_uint32(f, 0xffffffff))
640                                         return false;
641                                 if(flac__utils_fwrite("WAVE", 1, 4, f) != 4)
642                                         return false;
643                                 break;
644                         default:
645                                 return false;
646                 }
647
648                 /* ds64 chunk for RF64 */
649                 if(format == FORMAT_RF64) {
650                         if(flac__utils_fwrite("ds64", 1, 4, f) != 4)
651                                 return false;
652
653                         if(!write_little_endian_uint32(f, 28)) /* chunk size */
654                                 return false;
655
656                         if(!write_little_endian_uint64(f, iff_size))
657                                 return false;
658
659                         if(!write_little_endian_uint64(f, data_size))
660                                 return false;
661
662                         if(!write_little_endian_uint64(f, samples)) /*@@@@@@ correct? */
663                                 return false;
664
665                         if(!write_little_endian_uint32(f, 0)) /* table size */
666                                 return false;
667                 }
668
669                 decoder_session->fm_offset1 = ftello(f);
670
671                 if(fm) {
672                         /* seek forward to {allocate} or {skip over already-written chunks} before "fmt " */
673                         for(i = format==FORMAT_RF64?2:1; i < fm->format_block; i++) {
674                                 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
675                                         flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"fmt \"\n", decoder_session->inbasefilename);
676                                         return false;
677                                 }
678                         }
679                 }
680
681                 if(format != FORMAT_WAVE64) {
682                         if(flac__utils_fwrite("fmt ", 1, 4, f) != 4)
683                                 return false;
684                         if(!write_little_endian_uint32(f, is_waveformatextensible? 40 : 16)) /* chunk size */
685                                 return false;
686                 }
687                 else { /* Wave64 */
688                         /* fmt GUID 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A */
689                         if(flac__utils_fwrite("\x66\x6D\x74\x20\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
690                                 return false;
691                         /* chunk size (+16+8 for GUID and size fields) */
692                         if(!write_little_endian_uint64(f, 16+8+(is_waveformatextensible?40:16)))
693                                 return false;
694                 }
695
696                 if(!write_riff_wave_fmt_chunk_body(f, is_waveformatextensible, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate, decoder_session->channel_mask))
697                         return false;
698
699                 decoder_session->fm_offset2 = ftello(f);
700
701                 if(fm) {
702                         /* seek forward to {allocate} or {skip over already-written chunks} after "fmt " but before "data" */
703                         for(i = fm->format_block+1; i < fm->audio_block; i++) {
704                                 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
705                                         flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"fmt \"\n", decoder_session->inbasefilename);
706                                         return false;
707                                 }
708                         }
709                 }
710
711                 if(format != FORMAT_WAVE64) {
712                         if(flac__utils_fwrite("data", 1, 4, f) != 4)
713                                 return false;
714                         if(!write_little_endian_uint32(f, format==FORMAT_RF64? 0xffffffff : (FLAC__uint32)data_size))
715                                 return false;
716                 }
717                 else { /* Wave64 */
718                         /* data GUID 61746164-ACF3-11D3-8CD1-00C04F8EDB8A */
719                         if(flac__utils_fwrite("\x64\x61\x74\x61\xF3\xAC\xD3\x11\xD1\x8C\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f) != 16)
720                                 return false;
721                         /* +16+8 for GUID and size fields */
722                         if(!write_little_endian_uint64(f, 16+8 + data_size))
723                                 return false;
724                 }
725
726                 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
727         }
728         else {
729                 if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
730                         return false;
731
732                 if(!write_big_endian_uint32(f, (FLAC__uint32)iff_size)) /* filesize-8 */
733                         return false;
734
735                 if(flac__utils_fwrite("AIFF", 1, 4, f) != 4)
736                         return false;
737
738                 decoder_session->fm_offset1 = ftello(f);
739
740                 if(fm) {
741                         /* seek forward to {allocate} or {skip over already-written chunks} before "COMM" */
742                         for(i = 1; i < fm->format_block; i++) {
743                                 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
744                                         flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata before \"COMM\"\n", decoder_session->inbasefilename);
745                                         return false;
746                                 }
747                         }
748                 }
749
750                 if(!write_aiff_form_comm_chunk(f, samples, decoder_session->bps, decoder_session->channels, decoder_session->sample_rate))
751                         return false;
752
753                 decoder_session->fm_offset2 = ftello(f);
754
755                 if(fm) {
756                         /* seek forward to {allocate} or {skip over already-written chunks} after "COMM" but before "SSND" */
757                         for(i = fm->format_block+1; i < fm->audio_block; i++) {
758                                 if(fseeko(f, fm->blocks[i].size, SEEK_CUR) < 0) {
759                                         flac__utils_printf(stderr, 1, "%s: ERROR: allocating/skipping foreign metadata after \"COMM\"\n", decoder_session->inbasefilename);
760                                         return false;
761                                 }
762                         }
763                 }
764
765                 if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
766                         return false;
767
768                 if(!write_big_endian_uint32(f, (FLAC__uint32)data_size + 8)) /* data size */
769                         return false;
770
771                 if(!write_big_endian_uint32(f, 0/*offset_size*/))
772                         return false;
773
774                 if(!write_big_endian_uint32(f, 0/*block_size*/))
775                         return false;
776
777                 decoder_session->fm_offset3 = ftello(f) + aligned_data_size;
778         }
779
780         return true;
781 }
782
783 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)
784 {
785         if(!write_little_endian_uint16(f, (FLAC__uint16)(is_waveformatextensible? 65534 : 1))) /* compression code */
786                 return false;
787
788         if(!write_little_endian_uint16(f, (FLAC__uint16)channels))
789                 return false;
790
791         if(!write_little_endian_uint32(f, sample_rate))
792                 return false;
793
794         if(!write_little_endian_uint32(f, sample_rate * channels * ((bps+7) / 8)))
795                 return false;
796
797         if(!write_little_endian_uint16(f, (FLAC__uint16)(channels * ((bps+7) / 8)))) /* block align */
798                 return false;
799
800         if(!write_little_endian_uint16(f, (FLAC__uint16)(((bps+7)/8)*8))) /* bits per sample */
801                 return false;
802
803         if(is_waveformatextensible) {
804                 if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */
805                         return false;
806
807                 if(!write_little_endian_uint16(f, (FLAC__uint16)bps)) /* validBitsPerSample */
808                         return false;
809
810                 if(!write_little_endian_uint32(f, channel_mask))
811                         return false;
812
813                 /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */
814                 if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16)
815                         return false;
816         }
817
818         return true;
819 }
820
821 FLAC__bool write_aiff_form_comm_chunk(FILE *f, FLAC__uint64 samples, unsigned bps, unsigned channels, unsigned sample_rate)
822 {
823         FLAC__ASSERT(samples <= 0xffffffff);
824
825         if(flac__utils_fwrite("COMM", 1, 4, f) != 4)
826                 return false;
827
828         if(!write_big_endian_uint32(f, 18)) /* chunk size = 18 */
829                 return false;
830
831         if(!write_big_endian_uint16(f, (FLAC__uint16)channels))
832                 return false;
833
834         if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
835                 return false;
836
837         if(!write_big_endian_uint16(f, (FLAC__uint16)bps))
838                 return false;
839
840         if(!write_sane_extended(f, sample_rate))
841                 return false;
842
843         return true;
844 }
845
846 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
847 {
848         FLAC__byte *b = (FLAC__byte*)(&val);
849         if(is_big_endian_host_) {
850                 FLAC__byte tmp;
851                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
852         }
853         return flac__utils_fwrite(b, 1, 2, f) == 2;
854 }
855
856 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
857 {
858         FLAC__byte *b = (FLAC__byte*)(&val);
859         if(is_big_endian_host_) {
860                 FLAC__byte tmp;
861                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
862                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
863         }
864         return flac__utils_fwrite(b, 1, 4, f) == 4;
865 }
866
867 FLAC__bool write_little_endian_uint64(FILE *f, FLAC__uint64 val)
868 {
869         FLAC__byte *b = (FLAC__byte*)(&val);
870         if(is_big_endian_host_) {
871                 FLAC__byte tmp;
872                 tmp = b[7]; b[7] = b[0]; b[0] = tmp;
873                 tmp = b[6]; b[6] = b[1]; b[1] = tmp;
874                 tmp = b[5]; b[5] = b[2]; b[2] = tmp;
875                 tmp = b[4]; b[4] = b[3]; b[3] = tmp;
876         }
877         return flac__utils_fwrite(b, 1, 8, f) == 8;
878 }
879
880 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
881 {
882         FLAC__byte *b = (FLAC__byte*)(&val);
883         if(!is_big_endian_host_) {
884                 FLAC__byte tmp;
885                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
886         }
887         return flac__utils_fwrite(b, 1, 2, f) == 2;
888 }
889
890 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
891 {
892         FLAC__byte *b = (FLAC__byte*)(&val);
893         if(!is_big_endian_host_) {
894                 FLAC__byte tmp;
895                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
896                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
897         }
898         return flac__utils_fwrite(b, 1, 4, f) == 4;
899 }
900
901 FLAC__bool write_sane_extended(FILE *f, unsigned val)
902         /* Write to 'f' a SANE extended representation of 'val'.  Return false if
903         * the write succeeds; return true otherwise.
904         *
905         * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
906         * of exponent, and 64 bits of significand (mantissa).  Unlike most IEEE-754
907         * representations, it does not imply a 1 above the MSB of the significand.
908         *
909         * Preconditions:
910         *  val!=0U
911         */
912 {
913         unsigned int shift, exponent;
914
915         FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
916
917         for(shift= 0U; (val>>(31-shift))==0U; ++shift)
918                 ;
919         val<<= shift;
920         exponent= 63U-(shift+32U); /* add 32 for unused second word */
921
922         if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
923                 return false;
924         if(!write_big_endian_uint32(f, val))
925                 return false;
926         if(!write_big_endian_uint32(f, 0)) /* unused second word */
927                 return false;
928
929         return true;
930 }
931
932 FLAC__bool fixup_iff_headers(DecoderSession *d)
933 {
934         const char *fmt_desc =
935                 d->format==FORMAT_WAVE? "WAVE" :
936                 d->format==FORMAT_WAVE64? "Wave64" :
937                 d->format==FORMAT_RF64? "RF64" :
938                 "AIFF";
939         FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
940
941         if(0 == f) {
942                 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));
943                 return false;
944         }
945
946         if(!write_iff_headers(f, d, d->samples_processed)) {
947                 fclose(f);
948                 return false;
949         }
950
951         fclose(f);
952         return true;
953 }
954
955 FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
956 {
957         DecoderSession *decoder_session = (DecoderSession*)client_data;
958         FILE *fout = decoder_session->fout;
959         const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
960         const unsigned shift = (decoder_session->format != FORMAT_RAW && (bps%8))? 8-(bps%8): 0;
961         FLAC__bool is_big_endian = (
962                 decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? true : (
963                 decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 ? false :
964                 decoder_session->is_big_endian
965         ));
966         FLAC__bool is_unsigned_samples = (
967                 decoder_session->format == FORMAT_AIFF || decoder_session->format == FORMAT_AIFF_C ? false : (
968                 decoder_session->format == FORMAT_WAVE || decoder_session->format == FORMAT_WAVE64 || decoder_session->format == FORMAT_RF64 ? bps<=8 :
969                 decoder_session->is_unsigned_samples
970         ));
971         unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
972         unsigned frame_bytes = 0;
973         static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
974         FLAC__uint8  *u8buffer  = (FLAC__uint8  *)s8buffer;
975         FLAC__int16  *s16buffer = (FLAC__int16  *)s8buffer;
976         FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
977         FLAC__int32  *s32buffer = (FLAC__int32  *)s8buffer;
978         FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
979         size_t bytes_to_write = 0;
980
981         (void)decoder;
982
983         if(decoder_session->abort_flag)
984                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
985
986         /* sanity-check the bits-per-sample */
987         if(decoder_session->bps) {
988                 if(bps != decoder_session->bps) {
989                         if(decoder_session->got_stream_info)
990                                 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);
991                         else
992                                 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);
993                         if(!decoder_session->continue_through_decode_errors)
994                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
995                 }
996         }
997         else {
998                 /* must not have gotten STREAMINFO, save the bps from the frame header */
999                 FLAC__ASSERT(!decoder_session->got_stream_info);
1000                 decoder_session->bps = bps;
1001         }
1002
1003         /* sanity-check the #channels */
1004         if(decoder_session->channels) {
1005                 if(channels != decoder_session->channels) {
1006                         if(decoder_session->got_stream_info)
1007                                 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
1008                         else
1009                                 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);
1010                         if(!decoder_session->continue_through_decode_errors)
1011                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1012                 }
1013         }
1014         else {
1015                 /* must not have gotten STREAMINFO, save the #channels from the frame header */
1016                 FLAC__ASSERT(!decoder_session->got_stream_info);
1017                 decoder_session->channels = channels;
1018         }
1019
1020         /* sanity-check the sample rate */
1021         if(decoder_session->sample_rate) {
1022                 if(frame->header.sample_rate != decoder_session->sample_rate) {
1023                         if(decoder_session->got_stream_info)
1024                                 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);
1025                         else
1026                                 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);
1027                         if(!decoder_session->continue_through_decode_errors)
1028                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1029                 }
1030         }
1031         else {
1032                 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
1033                 FLAC__ASSERT(!decoder_session->got_stream_info);
1034                 decoder_session->sample_rate = frame->header.sample_rate;
1035         }
1036
1037         /*
1038          * limit the number of samples to accept based on --until
1039          */
1040         FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1041         /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
1042         if(decoder_session->skip_specification->is_relative) {
1043                 if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
1044                         decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
1045                 else {
1046                         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);
1047                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1048                 }
1049         }
1050         if(decoder_session->until_specification->is_relative) {
1051                 if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
1052                         decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
1053                 else {
1054                         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);
1055                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1056                 }
1057         }
1058         FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1059         FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1060         if(decoder_session->until_specification->value.samples > 0) {
1061                 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1062                 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1063                 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
1064                 FLAC__ASSERT(until >= input_samples_passed);
1065                 if(input_samples_passed + wide_samples > until)
1066                         wide_samples = (unsigned)(until - input_samples_passed);
1067                 if (wide_samples == 0) {
1068                         decoder_session->abort_flag = true;
1069                         decoder_session->aborting_due_to_until = true;
1070                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1071                 }
1072         }
1073
1074         if(decoder_session->analysis_mode) {
1075                 FLAC__uint64 dpos;
1076                 FLAC__stream_decoder_get_decode_position(decoder_session->decoder, &dpos);
1077                 frame_bytes = (unsigned)(dpos-decoder_session->decode_position);
1078                 decoder_session->decode_position = dpos;
1079         }
1080
1081         if(wide_samples > 0) {
1082                 decoder_session->samples_processed += wide_samples;
1083                 decoder_session->frame_counter++;
1084
1085                 if(!(decoder_session->frame_counter & 0x3f))
1086                         print_stats(decoder_session);
1087
1088                 if(decoder_session->analysis_mode) {
1089                         flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->decode_position-frame_bytes, frame_bytes, decoder_session->aopts, fout);
1090                 }
1091                 else if(!decoder_session->test_only) {
1092                         if(shift && !decoder_session->replaygain.apply) {
1093                                 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1094                                         for(channel = 0; channel < channels; channel++)
1095                                                 ((FLAC__int32**)buffer)[channel][wide_sample] <<= shift;/*@@@@@@un-const'ing the buffer is hacky but safe*/
1096                         }
1097                         if(decoder_session->replaygain.apply) {
1098                                 bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
1099                                         u8buffer,
1100                                         !is_big_endian,
1101                                         is_unsigned_samples,
1102                                         buffer,
1103                                         wide_samples,
1104                                         channels,
1105                                         bps, /* source_bps */
1106                                         bps+shift, /* target_bps */
1107                                         decoder_session->replaygain.scale,
1108                                         decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
1109                                         decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
1110                                         &decoder_session->replaygain.dither_context
1111                                 );
1112                         }
1113                         /* first some special code for common cases */
1114                         else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 2 && bps+shift == 16) {
1115                                 FLAC__int16 *buf1_ = s16buffer + 1;
1116                                 if(is_big_endian)
1117                                         memcpy(s16buffer, ((FLAC__byte*)(buffer[0]))+2, sizeof(FLAC__int32) * wide_samples - 2);
1118                                 else
1119                                         memcpy(s16buffer, buffer[0], sizeof(FLAC__int32) * wide_samples);
1120                                 for(sample = 0; sample < wide_samples; sample++, buf1_+=2)
1121                                         *buf1_ = (FLAC__int16)buffer[1][sample];
1122                                 bytes_to_write = 4 * sample;
1123                         }
1124                         else if(is_big_endian == is_big_endian_host_ && !is_unsigned_samples && channels == 1 && bps+shift == 16) {
1125                                 FLAC__int16 *buf1_ = s16buffer;
1126                                 for(sample = 0; sample < wide_samples; sample++)
1127                                         *buf1_++ = (FLAC__int16)buffer[0][sample];
1128                                 bytes_to_write = 2 * sample;
1129                         }
1130                         /* generic code for the rest */
1131                         else if(bps+shift == 16) {
1132                                 if(is_unsigned_samples) {
1133                                         if(channels == 2) {
1134                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1135                                                         u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1136                                                         u16buffer[sample++] = (FLAC__uint16)(buffer[1][wide_sample] + 0x8000);
1137                                                 }
1138                                         }
1139                                         else if(channels == 1) {
1140                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1141                                                         u16buffer[sample++] = (FLAC__uint16)(buffer[0][wide_sample] + 0x8000);
1142                                         }
1143                                         else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1144                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1145                                                         for(channel = 0; channel < channels; channel++, sample++)
1146                                                                 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
1147                                         }
1148                                 }
1149                                 else {
1150                                         if(channels == 2) {
1151                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
1152                                                         s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1153                                                         s16buffer[sample++] = (FLAC__int16)(buffer[1][wide_sample]);
1154                                                 }
1155                                         }
1156                                         else if(channels == 1) {
1157                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1158                                                         s16buffer[sample++] = (FLAC__int16)(buffer[0][wide_sample]);
1159                                         }
1160                                         else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1161                                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1162                                                         for(channel = 0; channel < channels; channel++, sample++)
1163                                                                 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
1164                                         }
1165                                 }
1166                                 if(is_big_endian != is_big_endian_host_) {
1167                                         unsigned char tmp;
1168                                         const unsigned bytes = sample * 2;
1169                                         for(byte = 0; byte < bytes; byte += 2) {
1170                                                 tmp = u8buffer[byte];
1171                                                 u8buffer[byte] = u8buffer[byte+1];
1172                                                 u8buffer[byte+1] = tmp;
1173                                         }
1174                                 }
1175                                 bytes_to_write = 2 * sample;
1176                         }
1177                         else if(bps+shift == 24) {
1178                                 if(is_unsigned_samples) {
1179                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1180                                                 for(channel = 0; channel < channels; channel++, sample++)
1181                                                         u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
1182                                 }
1183                                 else {
1184                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1185                                                 for(channel = 0; channel < channels; channel++, sample++)
1186                                                         s32buffer[sample] = buffer[channel][wide_sample];
1187                                 }
1188                                 if(is_big_endian != is_big_endian_host_) {
1189                                         unsigned char tmp;
1190                                         const unsigned bytes = sample * 4;
1191                                         for(byte = 0; byte < bytes; byte += 4) {
1192                                                 tmp = u8buffer[byte];
1193                                                 u8buffer[byte] = u8buffer[byte+3];
1194                                                 u8buffer[byte+3] = tmp;
1195                                                 tmp = u8buffer[byte+1];
1196                                                 u8buffer[byte+1] = u8buffer[byte+2];
1197                                                 u8buffer[byte+2] = tmp;
1198                                         }
1199                                 }
1200                                 if(is_big_endian) {
1201                                         unsigned lbyte;
1202                                         const unsigned bytes = sample * 4;
1203                                         for(lbyte = byte = 0; byte < bytes; ) {
1204                                                 byte++;
1205                                                 u8buffer[lbyte++] = u8buffer[byte++];
1206                                                 u8buffer[lbyte++] = u8buffer[byte++];
1207                                                 u8buffer[lbyte++] = u8buffer[byte++];
1208                                         }
1209                                 }
1210                                 else {
1211                                         unsigned lbyte;
1212                                         const unsigned bytes = sample * 4;
1213                                         for(lbyte = byte = 0; byte < bytes; ) {
1214                                                 u8buffer[lbyte++] = u8buffer[byte++];
1215                                                 u8buffer[lbyte++] = u8buffer[byte++];
1216                                                 u8buffer[lbyte++] = u8buffer[byte++];
1217                                                 byte++;
1218                                         }
1219                                 }
1220                                 bytes_to_write = 3 * sample;
1221                         }
1222                         else if(bps+shift == 8) {
1223                                 if(is_unsigned_samples) {
1224                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1225                                                 for(channel = 0; channel < channels; channel++, sample++)
1226                                                         u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
1227                                 }
1228                                 else {
1229                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1230                                                 for(channel = 0; channel < channels; channel++, sample++)
1231                                                         s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
1232                                 }
1233                                 bytes_to_write = sample;
1234                         }
1235                         else {
1236                                 FLAC__ASSERT(0);
1237                                 /* double protection */
1238                                 decoder_session->abort_flag = true;
1239                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1240                         }
1241                 }
1242         }
1243         if(bytes_to_write > 0) {
1244                 if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
1245                         /* if a pipe closed when writing to stdout, we let it go without an error message */
1246                         if(errno == EPIPE && decoder_session->fout == stdout)
1247                                 decoder_session->aborting_due_to_until = true;
1248                         decoder_session->abort_flag = true;
1249                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1250                 }
1251         }
1252         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1253 }
1254
1255 void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1256 {
1257         DecoderSession *decoder_session = (DecoderSession*)client_data;
1258
1259         if(decoder_session->analysis_mode)
1260                 FLAC__stream_decoder_get_decode_position(decoder, &decoder_session->decode_position);
1261
1262         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
1263                 FLAC__uint64 skip, until;
1264                 decoder_session->got_stream_info = true;
1265                 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);
1266                 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1267                 decoder_session->channels = metadata->data.stream_info.channels;
1268                 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1269
1270                 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
1271                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1272                 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1273
1274                 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1275                 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1276                         flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1277                         decoder_session->abort_flag = true;
1278                         return;
1279                 }
1280                 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1281                         flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1282                         decoder_session->abort_flag = true;
1283                         return;
1284                 }
1285                 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1286                 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1287
1288                 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1289                 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1290                         decoder_session->abort_flag = true;
1291                         return;
1292                 }
1293                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1294                 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1295
1296                 if(until > 0) {
1297                         FLAC__ASSERT(decoder_session->total_samples != 0);
1298                         FLAC__ASSERT(0 == decoder_session->cue_specification);
1299                         decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1300                 }
1301
1302                 if(decoder_session->bps < 4 || decoder_session->bps > 24) {
1303                         flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 4-24\n", decoder_session->inbasefilename, decoder_session->bps);
1304                         decoder_session->abort_flag = true;
1305                         return;
1306                 }
1307         }
1308         else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1309                 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1310                 if(decoder_session->total_samples == 0) {
1311                         flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1312                         decoder_session->abort_flag = true;
1313                         return;
1314                 }
1315
1316                 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);
1317
1318                 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1319                 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1320
1321                 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1322                 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1323
1324                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1325                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1326                 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1327                 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1328
1329                 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1330         }
1331         else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1332                 if (decoder_session->replaygain.spec.apply) {
1333                         double reference, gain, peak;
1334                         if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
1335                                 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");
1336                                 if(decoder_session->treat_warnings_as_errors) {
1337                                         decoder_session->abort_flag = true;
1338                                         return;
1339                                 }
1340                         }
1341                         else {
1342                                 const char *ls[] = { "no", "peak", "hard" };
1343                                 const char *ns[] = { "no", "low", "medium", "high" };
1344                                 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1345                                 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1346                                 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1347                                 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]);
1348                                 flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1349                                 /* don't check if(decoder_session->treat_warnings_as_errors) because the user explicitly asked for it */
1350                         }
1351                 }
1352                 (void)flac__utils_get_channel_mask_tag(metadata, &decoder_session->channel_mask);
1353         }
1354 }
1355
1356 void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1357 {
1358         DecoderSession *decoder_session = (DecoderSession*)client_data;
1359         (void)decoder;
1360         flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1361         if(!decoder_session->continue_through_decode_errors) {
1362                 decoder_session->abort_flag = true;
1363                 if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1364                         decoder_session->aborting_due_to_unparseable = true;
1365         }
1366 }
1367
1368 void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
1369 {
1370         const int ilen = strlen(d->inbasefilename) + 1;
1371
1372         flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1373
1374         flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
1375
1376         /* print out some more info for some errors: */
1377         if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
1378                 flac__utils_printf(stderr, 1,
1379                         "\n"
1380                         "An error occurred opening the input file; it is likely that it does not exist\n"
1381                         "or is not readable.\n"
1382                 );
1383         }
1384 }
1385
1386 void print_error_with_state(const DecoderSession *d, const char *message)
1387 {
1388         const int ilen = strlen(d->inbasefilename) + 1;
1389
1390         flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1391         flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", FLAC__stream_decoder_get_resolved_state_string(d->decoder));
1392
1393         /* print out some more info for some errors: */
1394         if (d->aborting_due_to_unparseable) {
1395                 flac__utils_printf(stderr, 1,
1396                         "\n"
1397                         "The FLAC stream may have been created by a more advanced encoder.  Try\n"
1398                         "  metaflac --show-vendor-tag %s\n"
1399                         "If the version number is greater than %s, this decoder is probably\n"
1400                         "not able to decode the file.  If the version number is not, the file\n"
1401                         "may be corrupted, or you may have found a bug.  In this case please\n"
1402                         "submit a bug report to\n"
1403                         "    http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
1404                         "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1405                         d->inbasefilename, FLAC__VERSION_STRING
1406                 );
1407         }
1408 }
1409
1410 void print_stats(const DecoderSession *decoder_session)
1411 {
1412         if(flac__utils_verbosity_ >= 2) {
1413 #if defined _MSC_VER || defined __MINGW32__
1414                 /* with MSVC you have to spoon feed it the casting */
1415                 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1416 #else
1417                 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1418 #endif
1419                 if(decoder_session->total_samples > 0) {
1420                         fprintf(stderr, "\r%s: %s%u%% complete",
1421                                 decoder_session->inbasefilename,
1422                                 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1423                                 (unsigned)floor(progress + 0.5)
1424                         );
1425                 }
1426                 else {
1427                         fprintf(stderr, "\r%s: %s %u samples",
1428                                 decoder_session->inbasefilename,
1429                                 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1430                                 (unsigned)decoder_session->samples_processed
1431                         );
1432                 }
1433         }
1434 }