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