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