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