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