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