7a6d2bae35a9156e9b000ecf5118a06b93e0799a
[platform/upstream/flac.git] / src / flac / decode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001,2002,2003,2004  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 #ifdef 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 #include <math.h> /* for floor() */
30 #include <stdio.h> /* for FILE et al. */
31 #include <string.h> /* for strcmp() */
32 #include "FLAC/all.h"
33 #include "share/grabbag.h"
34 #include "share/replaygain_synthesis.h"
35 #include "decode.h"
36
37 #ifdef FLAC__HAS_OGG
38 #include "OggFLAC/file_decoder.h"
39 #endif
40
41 typedef struct {
42 #ifdef FLAC__HAS_OGG
43         FLAC__bool is_ogg;
44 #endif
45
46         FLAC__bool verbose;
47         FLAC__bool silent;
48         FLAC__bool is_aiff_out;
49         FLAC__bool is_wave_out;
50         FLAC__bool continue_through_decode_errors;
51
52         struct {
53                 replaygain_synthesis_spec_t spec;
54                 FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */
55                 double scale;
56                 DitherContext dither_context;
57         } replaygain;
58
59         FLAC__bool test_only;
60         FLAC__bool analysis_mode;
61         analysis_options aopts;
62         utils__SkipUntilSpecification *skip_specification;
63         utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
64         utils__CueSpecification *cue_specification;
65
66         const char *inbasefilename;
67         const char *outfilename;
68
69         FLAC__uint64 samples_processed;
70         unsigned frame_counter;
71         FLAC__bool abort_flag;
72         FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
73
74         struct {
75                 FLAC__bool needs_fixup;
76                 unsigned riff_offset; /* or FORM offset for AIFF */
77                 unsigned data_offset; /* or SSND offset for AIFF */
78                 unsigned frames_offset; /* AIFF only */
79         } wave_chunk_size_fixup;
80
81         FLAC__bool is_big_endian;
82         FLAC__bool is_unsigned_samples;
83         FLAC__uint64 total_samples;
84         unsigned bps;
85         unsigned channels;
86         unsigned sample_rate;
87
88         union {
89                 union {
90                         FLAC__FileDecoder *file;
91                 } flac;
92 #ifdef FLAC__HAS_OGG
93                 union {
94                         OggFLAC__FileDecoder *file;
95                 } ogg;
96 #endif
97         } decoder;
98
99         FILE *fout;
100 } DecoderSession;
101
102
103 static FLAC__bool is_big_endian_host_;
104
105
106 /*
107  * local routines
108  */
109 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool verbose, FLAC__bool silent, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, 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, const char *infilename, const char *outfilename);
110 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
111 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, decode_options_t decode_options, const char *infilename);
112 static FLAC__bool DecoderSession_process(DecoderSession *d);
113 static int DecoderSession_finish_ok(DecoderSession *d);
114 static int DecoderSession_finish_error(DecoderSession *d);
115 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input, FLAC__bool silent);
116 static FLAC__bool write_necessary_headers(DecoderSession *decoder_session);
117 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
118 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
119 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
120 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
121 static FLAC__bool write_sane_extended(FILE *f, unsigned val);
122 static FLAC__bool fixup_wave_chunk_size(const char *outfilename, FLAC__bool is_wave_out, unsigned riff_offset, unsigned data_offset, unsigned frames_offset, FLAC__uint32 total_samples, unsigned channels, unsigned bps, FLAC__bool silent);
123 /*
124  * We use 'void *' so that we can use the same callbacks for the
125  * FLAC__StreamDecoder and FLAC__FileDecoder.  The 'decoder' argument is
126  * actually never used in the callbacks.
127  */
128 static FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
129 static void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
130 static void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
131 static void print_error_with_state(const DecoderSession *d, const char *message);
132 static void print_stats(const DecoderSession *decoder_session);
133
134
135 /*
136  * public routines
137  */
138 int flac__decode_aiff(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
139 {
140         DecoderSession decoder_session;
141
142         if(!
143                 DecoderSession_construct(
144                         &decoder_session,
145 #ifdef FLAC__HAS_OGG
146                         options.common.is_ogg,
147 #else
148                         /*is_ogg=*/false,
149 #endif
150                         options.common.verbose,
151                         options.common.silent,
152                         /*is_aiff_out=*/true,
153                         /*is_wave_out=*/false,
154                         options.common.continue_through_decode_errors,
155                         options.common.replaygain_synthesis_spec,
156                         analysis_mode,
157                         aopts,
158                         &options.common.skip_specification,
159                         &options.common.until_specification,
160                         options.common.has_cue_specification? &options.common.cue_specification : 0,
161                         infilename,
162                         outfilename
163                 )
164         )
165                 return 1;
166
167         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
168                 return DecoderSession_finish_error(&decoder_session);
169
170         if(!DecoderSession_process(&decoder_session))
171                 return DecoderSession_finish_error(&decoder_session);
172
173         return DecoderSession_finish_ok(&decoder_session);
174 }
175
176 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
177 {
178         DecoderSession decoder_session;
179
180         if(!
181                 DecoderSession_construct(
182                         &decoder_session,
183 #ifdef FLAC__HAS_OGG
184                         options.common.is_ogg,
185 #else
186                         /*is_ogg=*/false,
187 #endif
188                         options.common.verbose,
189                         options.common.silent,
190                         /*is_aiff_out=*/false,
191                         /*is_wave_out=*/true,
192                         options.common.continue_through_decode_errors,
193                         options.common.replaygain_synthesis_spec,
194                         analysis_mode,
195                         aopts,
196                         &options.common.skip_specification,
197                         &options.common.until_specification,
198                         options.common.has_cue_specification? &options.common.cue_specification : 0,
199                         infilename,
200                         outfilename
201                 )
202         )
203                 return 1;
204
205         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
206                 return DecoderSession_finish_error(&decoder_session);
207
208         if(!DecoderSession_process(&decoder_session))
209                 return DecoderSession_finish_error(&decoder_session);
210
211         return DecoderSession_finish_ok(&decoder_session);
212 }
213
214 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
215 {
216         DecoderSession decoder_session;
217
218         decoder_session.is_big_endian = options.is_big_endian;
219         decoder_session.is_unsigned_samples = options.is_unsigned_samples;
220
221         if(!
222                 DecoderSession_construct(
223                         &decoder_session,
224 #ifdef FLAC__HAS_OGG
225                         options.common.is_ogg,
226 #else
227                         /*is_ogg=*/false,
228 #endif
229                         options.common.verbose,
230                         options.common.silent,
231                         /*is_aiff_out=*/false,
232                         /*is_wave_out=*/false,
233                         options.common.continue_through_decode_errors,
234                         options.common.replaygain_synthesis_spec,
235                         analysis_mode,
236                         aopts,
237                         &options.common.skip_specification,
238                         &options.common.until_specification,
239                         options.common.has_cue_specification? &options.common.cue_specification : 0,
240                         infilename,
241                         outfilename
242                 )
243         )
244                 return 1;
245
246         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
247                 return DecoderSession_finish_error(&decoder_session);
248
249         if(!DecoderSession_process(&decoder_session))
250                 return DecoderSession_finish_error(&decoder_session);
251
252         return DecoderSession_finish_ok(&decoder_session);
253 }
254
255 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool verbose, FLAC__bool silent, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, 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, const char *infilename, const char *outfilename)
256 {
257 #ifdef FLAC__HAS_OGG
258         d->is_ogg = is_ogg;
259 #else
260         (void)is_ogg;
261 #endif
262
263         d->verbose = verbose;
264         d->silent = silent;
265         d->is_aiff_out = is_aiff_out;
266         d->is_wave_out = is_wave_out;
267         d->continue_through_decode_errors = continue_through_decode_errors;
268         d->replaygain.spec = replaygain_synthesis_spec;
269         d->replaygain.apply = false;
270         d->replaygain.scale = 0.0;
271         /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
272         d->test_only = (0 == outfilename);
273         d->analysis_mode = analysis_mode;
274         d->aopts = aopts;
275         d->skip_specification = skip_specification;
276         d->until_specification = until_specification;
277         d->cue_specification = cue_specification;
278
279         d->inbasefilename = grabbag__file_get_basename(infilename);
280         d->outfilename = outfilename;
281
282         d->samples_processed = 0;
283         d->frame_counter = 0;
284         d->abort_flag = false;
285         d->aborting_due_to_until = false;
286
287         d->wave_chunk_size_fixup.needs_fixup = false;
288
289         d->decoder.flac.file = 0;
290 #ifdef FLAC__HAS_OGG
291         d->decoder.ogg.file = 0;
292 #endif
293
294         d->fout = 0; /* initialized with an open file later if necessary */
295
296         FLAC__ASSERT(!(d->test_only && d->analysis_mode));
297
298         if(!d->test_only) {
299                 if(0 == strcmp(outfilename, "-")) {
300                         d->fout = grabbag__file_get_binary_stdout();
301                 }
302                 else {
303                         if(0 == (d->fout = fopen(outfilename, "wb"))) {
304                                 if(!d->silent) fprintf(stderr, "%s: ERROR: can't open output file %s\n", d->inbasefilename, outfilename);
305                                 DecoderSession_destroy(d, /*error_occurred=*/true);
306                                 return false;
307                         }
308                 }
309         }
310
311         if(analysis_mode)
312                 flac__analyze_init(aopts);
313
314         return true;
315 }
316
317 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
318 {
319         if(0 != d->fout && d->fout != stdout) {
320                 fclose(d->fout);
321                 if(error_occurred)
322                         unlink(d->outfilename);
323         }
324 }
325
326 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, decode_options_t decode_options, const char *infilename)
327 {
328         FLAC__uint32 test = 1;
329
330         is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
331
332 #ifdef FLAC__HAS_OGG
333         if(decoder_session->is_ogg) {
334                 decoder_session->decoder.ogg.file = OggFLAC__file_decoder_new();
335
336                 if(0 == decoder_session->decoder.ogg.file) {
337                         if(!decoder_session->silent) fprintf(stderr, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
338                         return false;
339                 }
340
341                 OggFLAC__file_decoder_set_md5_checking(decoder_session->decoder.ogg.file, true);
342                 OggFLAC__file_decoder_set_filename(decoder_session->decoder.ogg.file, infilename);
343                 if(!decode_options.use_first_serial_number)
344                         OggFLAC__file_decoder_set_serial_number(decoder_session->decoder.ogg.file, decode_options.serial_number);
345                 if (0 != decoder_session->cue_specification)
346                         OggFLAC__file_decoder_set_metadata_respond(decoder_session->decoder.ogg.file, FLAC__METADATA_TYPE_CUESHEET);
347                 if (decoder_session->replaygain.spec.apply)
348                         OggFLAC__file_decoder_set_metadata_respond(decoder_session->decoder.ogg.file, FLAC__METADATA_TYPE_VORBIS_COMMENT);
349
350                 /*
351                  * The three ugly casts here are to 'downcast' the 'void *' argument of
352                  * the callback down to 'OggFLAC__FileDecoder *'.  In C++ this would be
353                  * unnecessary but here the cast makes the C compiler happy.
354                  */
355                 OggFLAC__file_decoder_set_write_callback(decoder_session->decoder.ogg.file, (FLAC__StreamDecoderWriteStatus (*)(const OggFLAC__FileDecoder *, const FLAC__Frame *, const FLAC__int32 * const [], void *))write_callback);
356                 OggFLAC__file_decoder_set_metadata_callback(decoder_session->decoder.ogg.file, (void (*)(const OggFLAC__FileDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
357                 OggFLAC__file_decoder_set_error_callback(decoder_session->decoder.ogg.file, (void (*)(const OggFLAC__FileDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
358                 OggFLAC__file_decoder_set_client_data(decoder_session->decoder.ogg.file, decoder_session);
359
360                 if(OggFLAC__file_decoder_init(decoder_session->decoder.ogg.file) != OggFLAC__FILE_DECODER_OK) {
361                         print_error_with_state(decoder_session, "ERROR initializing decoder");
362                         return false;
363                 }
364         }
365         else
366 #else
367         (void)decode_options;
368 #endif
369         {
370                 decoder_session->decoder.flac.file = FLAC__file_decoder_new();
371
372                 if(0 == decoder_session->decoder.flac.file) {
373                         if(!decoder_session->silent) fprintf(stderr, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
374                         return false;
375                 }
376
377                 FLAC__file_decoder_set_md5_checking(decoder_session->decoder.flac.file, true);
378                 FLAC__file_decoder_set_filename(decoder_session->decoder.flac.file, infilename);
379                 if (0 != decoder_session->cue_specification)
380                         FLAC__file_decoder_set_metadata_respond(decoder_session->decoder.flac.file, FLAC__METADATA_TYPE_CUESHEET);
381                 if (decoder_session->replaygain.spec.apply)
382                         FLAC__file_decoder_set_metadata_respond(decoder_session->decoder.flac.file, FLAC__METADATA_TYPE_VORBIS_COMMENT);
383                 /*
384                  * The three ugly casts here are to 'downcast' the 'void *' argument of
385                  * the callback down to 'FLAC__FileDecoder *'.
386                  */
387                 FLAC__file_decoder_set_write_callback(decoder_session->decoder.flac.file, (FLAC__StreamDecoderWriteStatus (*)(const FLAC__FileDecoder *, const FLAC__Frame *, const FLAC__int32 * const [], void *))write_callback);
388                 FLAC__file_decoder_set_metadata_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
389                 FLAC__file_decoder_set_error_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
390                 FLAC__file_decoder_set_client_data(decoder_session->decoder.flac.file, decoder_session);
391
392                 if(FLAC__file_decoder_init(decoder_session->decoder.flac.file) != FLAC__FILE_DECODER_OK) {
393                         print_error_with_state(decoder_session, "ERROR initializing decoder");
394                         return false;
395                 }
396         }
397
398         return true;
399 }
400
401 FLAC__bool DecoderSession_process(DecoderSession *d)
402 {
403 #ifdef FLAC__HAS_OGG
404         if(d->is_ogg) {
405                 if(!OggFLAC__file_decoder_process_until_end_of_metadata(d->decoder.ogg.file)) {
406                         if(d->verbose) fprintf(stderr, "\n");
407                         print_error_with_state(d, "ERROR while decoding metadata");
408                         return false;
409                 }
410                 if(OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_OK && OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_END_OF_FILE) {
411                         if(d->verbose) fprintf(stderr, "\n");
412                         print_error_with_state(d, "ERROR during metadata decoding");
413                         return false;
414                 }
415         }
416         else
417 #endif
418         {
419                 if(!FLAC__file_decoder_process_until_end_of_metadata(d->decoder.flac.file)) {
420                         if(d->verbose) fprintf(stderr, "\n");
421                         print_error_with_state(d, "ERROR while decoding metadata");
422                         return false;
423                 }
424                 if(FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_END_OF_FILE) {
425                         if(d->verbose) fprintf(stderr, "\n");
426                         print_error_with_state(d, "ERROR during metadata decoding");
427                         return false;
428                 }
429         }
430         if(d->abort_flag)
431                 return false;
432
433         /* write the WAVE/AIFF headers if necessary */
434         if(!write_necessary_headers(d)) {
435                 d->abort_flag = true;
436                 return false;
437         }
438
439         if(d->skip_specification->value.samples > 0) {
440                 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
441
442 #ifdef FLAC__HAS_OGG
443                 if(d->is_ogg) {
444                         if(!OggFLAC__file_decoder_seek_absolute(d->decoder.ogg.file, skip)) {
445                                 print_error_with_state(d, "ERROR seeking while skipping bytes");
446                                 return false;
447                         }
448                         if(!OggFLAC__file_decoder_process_until_end_of_file(d->decoder.ogg.file) && !d->aborting_due_to_until) {
449                                 if(d->verbose) fprintf(stderr, "\n");
450                                 print_error_with_state(d, "ERROR while decoding frames");
451                                 return false;
452                         }
453                         if(OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_OK && OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_END_OF_FILE && !d->aborting_due_to_until) {
454                                 if(d->verbose) fprintf(stderr, "\n");
455                                 print_error_with_state(d, "ERROR during decoding");
456                                 return false;
457                         }
458                 }
459                 else
460 #endif
461                 {
462                         if(!FLAC__file_decoder_seek_absolute(d->decoder.flac.file, skip)) {
463                                 print_error_with_state(d, "ERROR seeking while skipping bytes");
464                                 return false;
465                         }
466                         if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file) && !d->aborting_due_to_until) {
467                                 if(d->verbose) fprintf(stderr, "\n");
468                                 print_error_with_state(d, "ERROR while decoding frames");
469                                 return false;
470                         }
471                         if(FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_END_OF_FILE && !d->aborting_due_to_until) {
472                                 if(d->verbose) fprintf(stderr, "\n");
473                                 print_error_with_state(d, "ERROR during decoding");
474                                 return false;
475                         }
476                 }
477         }
478         else {
479 #ifdef FLAC__HAS_OGG
480                 if(d->is_ogg) {
481                         if(!OggFLAC__file_decoder_process_until_end_of_file(d->decoder.ogg.file) && !d->aborting_due_to_until) {
482                                 if(d->verbose) fprintf(stderr, "\n");
483                                 print_error_with_state(d, "ERROR while decoding data");
484                                 return false;
485                         }
486                         if(OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_OK && OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_END_OF_FILE && !d->aborting_due_to_until) {
487                                 if(d->verbose) fprintf(stderr, "\n");
488                                 print_error_with_state(d, "ERROR during decoding");
489                                 return false;
490                         }
491                 }
492                 else
493 #endif
494                 {
495                         if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file) && !d->aborting_due_to_until) {
496                                 if(d->verbose) fprintf(stderr, "\n");
497                                 print_error_with_state(d, "ERROR while decoding data");
498                                 return false;
499                         }
500                         if(FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_END_OF_FILE && !d->aborting_due_to_until) {
501                                 if(d->verbose) fprintf(stderr, "\n");
502                                 print_error_with_state(d, "ERROR during decoding");
503                                 return false;
504                         }
505                 }
506         }
507
508         if(d->is_aiff_out && ((d->total_samples * d->channels * ((d->bps+7)/8)) & 1)) {
509                 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
510                         print_error_with_state(d, "ERROR writing pad byte to AIFF SSND chunk");
511                         return false;
512                 }
513         }
514
515         return true;
516 }
517
518 int DecoderSession_finish_ok(DecoderSession *d)
519 {
520         FLAC__bool md5_failure = false;
521
522 #ifdef FLAC__HAS_OGG
523         if(d->is_ogg) {
524                 if(d->decoder.ogg.file) {
525                         md5_failure = !OggFLAC__file_decoder_finish(d->decoder.ogg.file) && !d->aborting_due_to_until;
526                         print_stats(d);
527                         OggFLAC__file_decoder_delete(d->decoder.ogg.file);
528                 }
529         }
530         else
531 #endif
532         {
533                 if(d->decoder.flac.file) {
534                         md5_failure = !FLAC__file_decoder_finish(d->decoder.flac.file) && !d->aborting_due_to_until;
535                         print_stats(d);
536                         FLAC__file_decoder_delete(d->decoder.flac.file);
537                 }
538         }
539         if(d->analysis_mode)
540                 flac__analyze_finish(d->aopts);
541         if(md5_failure) {
542                 if(!d->silent) fprintf(stderr, "\r%s: WARNING, MD5 signature mismatch\n", d->inbasefilename);
543         }
544         else {
545                 if(d->verbose) fprintf(stderr, "\r%s: %s         \n", d->inbasefilename, d->test_only? "ok           ":d->analysis_mode?"done           ":"done");
546         }
547         DecoderSession_destroy(d, /*error_occurred=*/false);
548         if((d->is_wave_out || d->is_aiff_out) && d->wave_chunk_size_fixup.needs_fixup)
549                 if(!fixup_wave_chunk_size(d->outfilename, d->is_wave_out, d->wave_chunk_size_fixup.riff_offset, d->wave_chunk_size_fixup.data_offset, d->wave_chunk_size_fixup.frames_offset, (FLAC__uint32)d->samples_processed, d->channels, d->bps, d->silent))
550                         return 1;
551         return 0;
552 }
553
554 int DecoderSession_finish_error(DecoderSession *d)
555 {
556 #ifdef FLAC__HAS_OGG
557         if(d->is_ogg) {
558                 if(d->decoder.ogg.file) {
559                         OggFLAC__file_decoder_finish(d->decoder.ogg.file);
560                         OggFLAC__file_decoder_delete(d->decoder.ogg.file);
561                 }
562         }
563         else
564 #endif
565         {
566                 if(d->decoder.flac.file) {
567                         FLAC__file_decoder_finish(d->decoder.flac.file);
568                         FLAC__file_decoder_delete(d->decoder.flac.file);
569                 }
570         }
571         if(d->analysis_mode)
572                 flac__analyze_finish(d->aopts);
573         DecoderSession_destroy(d, /*error_occurred=*/true);
574         return 1;
575 }
576
577 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input, FLAC__bool silent)
578 {
579         /* convert from mm:ss.sss to sample number if necessary */
580         flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
581
582         /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
583         if(spec->is_relative && spec->value.samples == 0) {
584                 spec->is_relative = false;
585                 return true;
586         }
587
588         /* in any other case the total samples in the input must be known */
589         if(total_samples_in_input == 0) {
590                 if(!silent) fprintf(stderr, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
591                 return false;
592         }
593
594         FLAC__ASSERT(spec->value_is_samples);
595
596         /* convert relative specifications to absolute */
597         if(spec->is_relative) {
598                 if(spec->value.samples <= 0)
599                         spec->value.samples += (FLAC__int64)total_samples_in_input;
600                 else
601                         spec->value.samples += skip;
602                 spec->is_relative = false;
603         }
604
605         /* error check */
606         if(spec->value.samples < 0) {
607                 if(!silent) fprintf(stderr, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
608                 return false;
609         }
610         if((FLAC__uint64)spec->value.samples <= skip) {
611                 if(!silent) fprintf(stderr, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
612                 return false;
613         }
614         if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
615                 if(!silent) fprintf(stderr, "%s: ERROR, --until value is after end of input\n", inbasefilename);
616                 return false;
617         }
618
619         return true;
620 }
621
622 FLAC__bool write_necessary_headers(DecoderSession *decoder_session)
623 {
624         /* write the WAVE/AIFF headers if necessary */
625         if(!decoder_session->analysis_mode && !decoder_session->test_only && (decoder_session->is_wave_out || decoder_session->is_aiff_out)) {
626                 const char *fmt_desc = decoder_session->is_wave_out? "WAVE" : "AIFF";
627                 FLAC__uint64 data_size = decoder_session->total_samples * decoder_session->channels * ((decoder_session->bps+7)/8);
628                 if(decoder_session->total_samples == 0) {
629                         if(decoder_session->fout == stdout) {
630                                 if(!decoder_session->silent) fprintf(stderr, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
631                                 if(!decoder_session->silent) fprintf(stderr, "             Generated %s file will have a data chunk size of 0.  Try\n", fmt_desc);
632                                 if(!decoder_session->silent) fprintf(stderr, "             decoding directly to a file instead.\n");
633                         }
634                         else {
635                                 decoder_session->wave_chunk_size_fixup.needs_fixup = true;
636                         }
637                 }
638                 if(data_size >= 0xFFFFFFDC) {
639                         if(!decoder_session->silent) fprintf(stderr, "%s: ERROR: stream is too big to fit in a single %s file chunk\n", decoder_session->inbasefilename, fmt_desc);
640                         return false;
641                 }
642                 if(decoder_session->is_wave_out) {
643                         if(flac__utils_fwrite("RIFF", 1, 4, decoder_session->fout) != 4)
644                                 return false;
645
646                         if(decoder_session->wave_chunk_size_fixup.needs_fixup)
647                                 decoder_session->wave_chunk_size_fixup.riff_offset = ftell(decoder_session->fout);
648
649                         if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)(data_size+36))) /* filesize-8 */
650                                 return false;
651
652                         if(flac__utils_fwrite("WAVEfmt ", 1, 8, decoder_session->fout) != 8)
653                                 return false;
654
655                         if(flac__utils_fwrite("\020\000\000\000", 1, 4, decoder_session->fout) != 4) /* chunk size = 16 */
656                                 return false;
657
658                         if(flac__utils_fwrite("\001\000", 1, 2, decoder_session->fout) != 2) /* compression code == 1 */
659                                 return false;
660
661                         if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels)))
662                                 return false;
663
664                         if(!write_little_endian_uint32(decoder_session->fout, decoder_session->sample_rate))
665                                 return false;
666
667                         if(!write_little_endian_uint32(decoder_session->fout, decoder_session->sample_rate * decoder_session->channels * ((decoder_session->bps+7) / 8))) /* @@@ or is it (sample_rate*channels*bps) / 8 ??? */
668                                 return false;
669
670                         if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels * ((decoder_session->bps+7) / 8)))) /* block align */
671                                 return false;
672
673                         if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->bps))) /* bits per sample */
674                                 return false;
675
676                         if(flac__utils_fwrite("data", 1, 4, decoder_session->fout) != 4)
677                                 return false;
678
679                         if(decoder_session->wave_chunk_size_fixup.needs_fixup)
680                                 decoder_session->wave_chunk_size_fixup.data_offset = ftell(decoder_session->fout);
681
682                         if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)data_size)) /* data size */
683                                 return false;
684                 }
685                 else {
686                         const FLAC__uint32 aligned_data_size = (FLAC__uint32)((data_size+1) & (~1U));
687
688                         if(flac__utils_fwrite("FORM", 1, 4, decoder_session->fout) != 4)
689                                 return false;
690
691                         if(decoder_session->wave_chunk_size_fixup.needs_fixup)
692                                 decoder_session->wave_chunk_size_fixup.riff_offset = ftell(decoder_session->fout);
693
694                         if(!write_big_endian_uint32(decoder_session->fout, (FLAC__uint32)(aligned_data_size+46))) /* filesize-8 */
695                                 return false;
696
697                         if(flac__utils_fwrite("AIFFCOMM", 1, 8, decoder_session->fout) != 8)
698                                 return false;
699
700                         if(flac__utils_fwrite("\000\000\000\022", 1, 4, decoder_session->fout) != 4) /* chunk size = 18 */
701                                 return false;
702
703                         if(!write_big_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels)))
704                                 return false;
705
706                         if(decoder_session->wave_chunk_size_fixup.needs_fixup)
707                                 decoder_session->wave_chunk_size_fixup.frames_offset = ftell(decoder_session->fout);
708
709                         if(!write_big_endian_uint32(decoder_session->fout, (FLAC__uint32)decoder_session->total_samples))
710                                 return false;
711
712                         if(!write_big_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->bps)))
713                                 return false;
714
715                         if(!write_sane_extended(decoder_session->fout, decoder_session->sample_rate))
716                                 return false;
717
718                         if(flac__utils_fwrite("SSND", 1, 4, decoder_session->fout) != 4)
719                                 return false;
720
721                         if(decoder_session->wave_chunk_size_fixup.needs_fixup)
722                                 decoder_session->wave_chunk_size_fixup.data_offset = ftell(decoder_session->fout);
723
724                         if(!write_big_endian_uint32(decoder_session->fout, (FLAC__uint32)data_size+8)) /* data size */
725                                 return false;
726
727                         if(!write_big_endian_uint32(decoder_session->fout, 0/*offset*/))
728                                 return false;
729
730                         if(!write_big_endian_uint32(decoder_session->fout, 0/*block_size*/))
731                                 return false;
732                 }
733         }
734
735         return true;
736 }
737
738 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
739 {
740         FLAC__byte *b = (FLAC__byte*)(&val);
741         if(is_big_endian_host_) {
742                 FLAC__byte tmp;
743                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
744         }
745         return flac__utils_fwrite(b, 1, 2, f) == 2;
746 }
747
748 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
749 {
750         FLAC__byte *b = (FLAC__byte*)(&val);
751         if(is_big_endian_host_) {
752                 FLAC__byte tmp;
753                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
754                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
755         }
756         return flac__utils_fwrite(b, 1, 4, f) == 4;
757 }
758
759 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
760 {
761         FLAC__byte *b = (FLAC__byte*)(&val);
762         if(!is_big_endian_host_) {
763                 FLAC__byte tmp;
764                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
765         }
766         return flac__utils_fwrite(b, 1, 2, f) == 2;
767 }
768
769 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
770 {
771         FLAC__byte *b = (FLAC__byte*)(&val);
772         if(!is_big_endian_host_) {
773                 FLAC__byte tmp;
774                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
775                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
776         }
777         return flac__utils_fwrite(b, 1, 4, f) == 4;
778 }
779
780 FLAC__bool write_sane_extended(FILE *f, unsigned val)
781         /* Write to 'f' a SANE extended representation of 'val'.  Return false if
782         * the write succeeds; return true otherwise.
783         *
784         * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
785         * of exponent, and 64 bits of significand (mantissa).  Unlike most IEEE-754
786         * representations, it does not imply a 1 above the MSB of the significand.
787         *
788         * Preconditions:
789         *  val!=0U
790         */
791 {
792         unsigned int shift, exponent;
793
794         FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
795
796         for(shift= 0U; (val>>(31-shift))==0U; ++shift)
797                 ;
798         val<<= shift;
799         exponent= 63U-(shift+32U); /* add 32 for unused second word */
800
801         if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
802                 return false;
803         if(!write_big_endian_uint32(f, val))
804                 return false;
805         if(!write_big_endian_uint32(f, 0)) /* unused second word */
806                 return false;
807
808         return true;
809 }
810
811 FLAC__bool fixup_wave_chunk_size(const char *outfilename, FLAC__bool is_wave_out, unsigned riff_offset, unsigned data_offset, unsigned frames_offset, FLAC__uint32 total_samples, unsigned channels, unsigned bps, FLAC__bool silent)
812 {
813         const char *fmt_desc = (is_wave_out? "WAVE" : "AIFF");
814         FLAC__bool (*write_it)(FILE *, FLAC__uint32) = (is_wave_out? write_little_endian_uint32 : write_big_endian_uint32);
815         FILE *f = fopen(outfilename, "r+b");
816         FLAC__uint32 data_size, aligned_data_size;
817
818         if(0 == f) {
819                 if(!silent) fprintf(stderr, "ERROR, couldn't open file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
820                 return false;
821         }
822
823         data_size = aligned_data_size = total_samples * channels * ((bps+7)/8);
824         if(!is_wave_out && (aligned_data_size & 1))
825                 aligned_data_size++;
826
827         if(fseek(f, riff_offset, SEEK_SET) < 0) {
828                 if(!silent) fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
829                 fclose(f);
830                 return false;
831         }
832         if(!write_it(f, aligned_data_size + (is_wave_out? 36 : 46))) {
833                 if(!silent) fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
834                 fclose(f);
835                 return false;
836         }
837         if(!is_wave_out) {
838                 if(fseek(f, frames_offset, SEEK_SET) < 0) {
839                         if(!silent) fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
840                         fclose(f);
841                         return false;
842                 }
843                 if(!write_it(f, total_samples)) {
844                         if(!silent) fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
845                         fclose(f);
846                         return false;
847                 }
848         }
849         if(fseek(f, data_offset, SEEK_SET) < 0) {
850                 if(!silent) fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
851                 fclose(f);
852                 return false;
853         }
854         if(!write_it(f, data_size + (is_wave_out? 0 : 8))) {
855                 if(!silent) fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up %s chunk size\n", outfilename, fmt_desc);
856                 fclose(f);
857                 return false;
858         }
859         fclose(f);
860         return true;
861 }
862
863 FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
864 {
865         DecoderSession *decoder_session = (DecoderSession*)client_data;
866         FILE *fout = decoder_session->fout;
867         const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
868         FLAC__bool is_big_endian = (decoder_session->is_aiff_out? true : (decoder_session->is_wave_out? false : decoder_session->is_big_endian));
869         FLAC__bool is_unsigned_samples = (decoder_session->is_aiff_out? false : (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples));
870         unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
871         static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
872         FLAC__uint8  *u8buffer  = (FLAC__uint8  *)s8buffer;
873         FLAC__int16  *s16buffer = (FLAC__int16  *)s8buffer;
874         FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
875         FLAC__int32  *s32buffer = (FLAC__int32  *)s8buffer;
876         FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
877
878         (void)decoder;
879
880         if(decoder_session->abort_flag)
881                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
882
883         if(bps != decoder_session->bps) {
884                 if(!decoder_session->silent) fprintf(stderr, "%s: ERROR, bits-per-sample is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, bps, decoder_session->bps);
885                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
886         }
887         if(channels != decoder_session->channels) {
888                 if(!decoder_session->silent) fprintf(stderr, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
889                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
890         }
891         if(frame->header.sample_rate != decoder_session->sample_rate) {
892                 if(!decoder_session->silent) fprintf(stderr, "%s: ERROR, sample rate is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
893                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
894         }
895
896         /*
897          * limit the number of samples to accept based on --until
898          */
899         FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
900         FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
901         FLAC__ASSERT(!decoder_session->until_specification->is_relative);
902         FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
903         if(decoder_session->until_specification->value.samples > 0) {
904                 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
905                 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
906                 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
907                 FLAC__ASSERT(until >= input_samples_passed);
908                 if(input_samples_passed + wide_samples > until)
909                         wide_samples = (unsigned)(until - input_samples_passed);
910                 if (wide_samples == 0) {
911                         decoder_session->abort_flag = true;
912                         decoder_session->aborting_due_to_until = true;
913                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
914                 }
915         }
916
917         if(wide_samples > 0) {
918                 decoder_session->samples_processed += wide_samples;
919                 decoder_session->frame_counter++;
920
921                 if(decoder_session->verbose && !(decoder_session->frame_counter & 0x3f))
922                         print_stats(decoder_session);
923
924                 if(decoder_session->analysis_mode) {
925                         flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->aopts, fout);
926                 }
927                 else if(!decoder_session->test_only) {
928                         if (decoder_session->replaygain.apply) {
929                                 const size_t n = FLAC__replaygain_synthesis__apply_gain(
930                                         u8buffer,
931                                         !is_big_endian,
932                                         is_unsigned_samples,
933                                         buffer,
934                                         wide_samples,
935                                         channels,
936                                         bps, /* source_bps */
937                                         bps, /* target_bps */
938                                         decoder_session->replaygain.scale,
939                                         decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
940                                         decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
941                                         &decoder_session->replaygain.dither_context
942                                 );
943                                 if(flac__utils_fwrite(u8buffer, 1, n, fout) != n)
944                                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
945                         }
946                         else if(bps == 8) {
947                                 if(is_unsigned_samples) {
948                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
949                                                 for(channel = 0; channel < channels; channel++, sample++)
950                                                         u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
951                                 }
952                                 else {
953                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
954                                                 for(channel = 0; channel < channels; channel++, sample++)
955                                                         s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
956                                 }
957                                 if(flac__utils_fwrite(u8buffer, 1, sample, fout) != sample)
958                                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
959                         }
960                         else if(bps == 16) {
961                                 if(is_unsigned_samples) {
962                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
963                                                 for(channel = 0; channel < channels; channel++, sample++)
964                                                         u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
965                                 }
966                                 else {
967                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
968                                                 for(channel = 0; channel < channels; channel++, sample++)
969                                                         s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
970                                 }
971                                 if(is_big_endian != is_big_endian_host_) {
972                                         unsigned char tmp;
973                                         const unsigned bytes = sample * 2;
974                                         for(byte = 0; byte < bytes; byte += 2) {
975                                                 tmp = u8buffer[byte];
976                                                 u8buffer[byte] = u8buffer[byte+1];
977                                                 u8buffer[byte+1] = tmp;
978                                         }
979                                 }
980                                 if(flac__utils_fwrite(u16buffer, 2, sample, fout) != sample)
981                                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
982                         }
983                         else if(bps == 24) {
984                                 if(is_unsigned_samples) {
985                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
986                                                 for(channel = 0; channel < channels; channel++, sample++)
987                                                         u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
988                                 }
989                                 else {
990                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
991                                                 for(channel = 0; channel < channels; channel++, sample++)
992                                                         s32buffer[sample] = buffer[channel][wide_sample];
993                                 }
994                                 if(is_big_endian != is_big_endian_host_) {
995                                         unsigned char tmp;
996                                         const unsigned bytes = sample * 4;
997                                         for(byte = 0; byte < bytes; byte += 4) {
998                                                 tmp = u8buffer[byte];
999                                                 u8buffer[byte] = u8buffer[byte+3];
1000                                                 u8buffer[byte+3] = tmp;
1001                                                 tmp = u8buffer[byte+1];
1002                                                 u8buffer[byte+1] = u8buffer[byte+2];
1003                                                 u8buffer[byte+2] = tmp;
1004                                         }
1005                                 }
1006                                 if(is_big_endian) {
1007                                         unsigned lbyte;
1008                                         const unsigned bytes = sample * 4;
1009                                         for(lbyte = byte = 0; byte < bytes; ) {
1010                                                 byte++;
1011                                                 u8buffer[lbyte++] = u8buffer[byte++];
1012                                                 u8buffer[lbyte++] = u8buffer[byte++];
1013                                                 u8buffer[lbyte++] = u8buffer[byte++];
1014                                         }
1015                                 }
1016                                 else {
1017                                         unsigned lbyte;
1018                                         const unsigned bytes = sample * 4;
1019                                         for(lbyte = byte = 0; byte < bytes; ) {
1020                                                 u8buffer[lbyte++] = u8buffer[byte++];
1021                                                 u8buffer[lbyte++] = u8buffer[byte++];
1022                                                 u8buffer[lbyte++] = u8buffer[byte++];
1023                                                 byte++;
1024                                         }
1025                                 }
1026                                 if(flac__utils_fwrite(u8buffer, 3, sample, fout) != sample)
1027                                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1028                         }
1029                         else {
1030                                 FLAC__ASSERT(0);
1031                         }
1032                 }
1033         }
1034         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1035 }
1036
1037 void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1038 {
1039         DecoderSession *decoder_session = (DecoderSession*)client_data;
1040         (void)decoder;
1041         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
1042                 FLAC__uint64 skip, until;
1043                 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1044                 decoder_session->channels = metadata->data.stream_info.channels;
1045                 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1046
1047                 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
1048                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1049                 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1050
1051                 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1052                 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1053                         if(!decoder_session->silent) fprintf(stderr, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1054                         decoder_session->abort_flag = true;
1055                         return;
1056                 }
1057                 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1058                         if(!decoder_session->silent) fprintf(stderr, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1059                         decoder_session->abort_flag = true;
1060                         return;
1061                 }
1062                 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1063                 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1064
1065                 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1066                 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples, decoder_session->silent)) {
1067                         decoder_session->abort_flag = true;
1068                         return;
1069                 }
1070                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1071                 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1072
1073                 if(until > 0) {
1074                         FLAC__ASSERT(decoder_session->total_samples != 0);
1075                         FLAC__ASSERT(0 == decoder_session->cue_specification);
1076                         decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1077                 }
1078
1079                 if(decoder_session->bps != 8 && decoder_session->bps != 16 && decoder_session->bps != 24) {
1080                         if(!decoder_session->silent) fprintf(stderr, "%s: ERROR: bits per sample is not 8/16/24\n", decoder_session->inbasefilename);
1081                         decoder_session->abort_flag = true;
1082                         return;
1083                 }
1084         }
1085         else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1086                 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1087                 if(decoder_session->total_samples == 0) {
1088                         if(!decoder_session->silent) fprintf(stderr, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1089                         decoder_session->abort_flag = true;
1090                         return;
1091                 }
1092
1093                 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);
1094
1095                 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1096                 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1097
1098                 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1099                 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1100
1101                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1102                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1103                 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1104                 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1105
1106                 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1107         }
1108         else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1109                 if (decoder_session->replaygain.spec.apply) {
1110                         double gain, peak;
1111                         if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, &gain, &peak))) {
1112                                 if(!decoder_session->silent) fprintf(stderr, "%s: WARNING: can't get %s ReplayGain tag\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track");
1113                         }
1114                         else {
1115                                 const char *ls[] = { "no", "peak", "hard" };
1116                                 const char *ns[] = { "no", "low", "medium", "high" };
1117                                 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1118                                 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1119                                 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1120                                 if(!decoder_session->silent) fprintf(stderr, "%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]);
1121                                 if(!decoder_session->silent) fprintf(stderr, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1122                         }
1123                 }
1124         }
1125 }
1126
1127 void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1128 {
1129         DecoderSession *decoder_session = (DecoderSession*)client_data;
1130         (void)decoder;
1131         if(!decoder_session->silent) fprintf(stderr, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1132         if(!decoder_session->continue_through_decode_errors)
1133                 decoder_session->abort_flag = true;
1134 }
1135
1136 void print_error_with_state(const DecoderSession *d, const char *message)
1137 {
1138         const int ilen = strlen(d->inbasefilename) + 1;
1139
1140         if(d->silent)
1141                 return;
1142
1143         fprintf(stderr, "\n%s: %s\n", d->inbasefilename, message);
1144
1145 #ifdef FLAC__HAS_OGG
1146         if(d->is_ogg) {
1147                 const OggFLAC__FileDecoderState ofd_state = OggFLAC__file_decoder_get_state(d->decoder.ogg.file);
1148                 if(ofd_state != OggFLAC__FILE_DECODER_SEEKABLE_STREAM_DECODER_ERROR) {
1149                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ofd_state, OggFLAC__FileDecoderStateString[ofd_state]);
1150                 }
1151                 else {
1152                         const OggFLAC__SeekableStreamDecoderState ossd_state = OggFLAC__file_decoder_get_seekable_stream_decoder_state(d->decoder.ogg.file);
1153                         if(ossd_state != OggFLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR) {
1154                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ossd_state, OggFLAC__SeekableStreamDecoderStateString[ossd_state]);
1155                         }
1156                         else {
1157                                 const OggFLAC__StreamDecoderState osd_state = OggFLAC__file_decoder_get_state(d->decoder.ogg.file);
1158                                 if(osd_state != OggFLAC__STREAM_DECODER_FLAC_STREAM_DECODER_ERROR) {
1159                                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)osd_state, OggFLAC__StreamDecoderStateString[osd_state]);
1160                                 }
1161                                 else {
1162                                         const FLAC__StreamDecoderState fsd_state = OggFLAC__file_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.file);
1163                                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1164                                 }
1165                         }
1166                 }
1167         }
1168         else
1169 #endif
1170         {
1171                 const FLAC__FileDecoderState ffd_state = FLAC__file_decoder_get_state(d->decoder.flac.file);
1172                 if(ffd_state != FLAC__FILE_DECODER_SEEKABLE_STREAM_DECODER_ERROR) {
1173                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ffd_state, FLAC__FileDecoderStateString[ffd_state]);
1174                 }
1175                 else {
1176                         const FLAC__SeekableStreamDecoderState fssd_state = FLAC__file_decoder_get_seekable_stream_decoder_state(d->decoder.flac.file);
1177                         if(fssd_state != FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR) {
1178                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fssd_state, FLAC__SeekableStreamDecoderStateString[fssd_state]);
1179                         }
1180                         else {
1181                                 const FLAC__StreamDecoderState fsd_state = FLAC__file_decoder_get_stream_decoder_state(d->decoder.flac.file);
1182                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1183                         }
1184                 }
1185         }
1186 }
1187
1188 void print_stats(const DecoderSession *decoder_session)
1189 {
1190         if(decoder_session->verbose) {
1191 #if defined _MSC_VER || defined __MINGW32__
1192                 /* with VC++ you have to spoon feed it the casting */
1193                 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1194 #else
1195                 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1196 #endif
1197                 if(decoder_session->total_samples > 0) {
1198                         fprintf(stderr, "\r%s: %s%u%% complete",
1199                                 decoder_session->inbasefilename,
1200                                 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1201                                 (unsigned)floor(progress + 0.5)
1202                         );
1203                 }
1204                 else {
1205                         fprintf(stderr, "\r%s: %s %u samples",
1206                                 decoder_session->inbasefilename,
1207                                 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1208                                 (unsigned)decoder_session->samples_processed
1209                         );
1210                 }
1211         }
1212 }