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