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