minor syntax
[platform/upstream/flac.git] / src / flac / decode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006  Josh Coalson
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17  */
18
19 #if HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #if defined _WIN32 && !defined __CYGWIN__
24 /* where MSVC puts unlink() */
25 # include <io.h>
26 #else
27 # include <unistd.h>
28 #endif
29 #if defined _MSC_VER || defined __MINGW32__
30 #include <sys/types.h> /* for off_t */
31 #if _MSC_VER <= 1200 /* @@@ [2G limit] */
32 #define fseeko fseek
33 #define ftello ftell
34 #endif
35 #endif
36 #include <errno.h>
37 #include <math.h> /* for floor() */
38 #include <stdio.h> /* for FILE etc. */
39 #include <string.h> /* for strcmp(), strerror() */
40 #include "FLAC/all.h"
41 #include "share/grabbag.h"
42 #include "share/replaygain_synthesis.h"
43 #include "decode.h"
44
45 typedef struct {
46 #ifdef FLAC__HAS_OGG
47         FLAC__bool is_ogg;
48 #endif
49
50         FLAC__bool is_aiff_out;
51         FLAC__bool is_wave_out;
52         FLAC__bool continue_through_decode_errors;
53         FLAC__bool channel_map_none;
54
55         struct {
56                 replaygain_synthesis_spec_t spec;
57                 FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */
58                 double scale;
59                 DitherContext dither_context;
60         } replaygain;
61
62         FLAC__bool test_only;
63         FLAC__bool analysis_mode;
64         analysis_options aopts;
65         utils__SkipUntilSpecification *skip_specification;
66         utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
67         utils__CueSpecification *cue_specification;
68
69         const char *inbasefilename;
70         const char *outfilename;
71
72         FLAC__uint64 samples_processed;
73         unsigned frame_counter;
74         FLAC__bool abort_flag;
75         FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
76         FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */
77
78         FLAC__bool iff_headers_need_fixup;
79
80         FLAC__bool is_big_endian;
81         FLAC__bool is_unsigned_samples;
82         FLAC__bool got_stream_info;
83         FLAC__uint64 total_samples;
84         unsigned bps;
85         unsigned channels;
86         unsigned sample_rate;
87         FLAC__uint32 channel_mask;
88
89         FLAC__StreamDecoder *decoder;
90
91         FILE *fout;
92 } DecoderSession;
93
94
95 static FLAC__bool is_big_endian_host_;
96
97
98 /*
99  * local routines
100  */
101 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, FLAC__bool channel_map_none, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, const char *infilename, const char *outfilename);
102 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
103 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, decode_options_t decode_options, const char *infilename);
104 static FLAC__bool DecoderSession_process(DecoderSession *d);
105 static int DecoderSession_finish_ok(DecoderSession *d);
106 static int DecoderSession_finish_error(DecoderSession *d);
107 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
108 static FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples);
109 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
110 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
111 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
112 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
113 static FLAC__bool write_sane_extended(FILE *f, unsigned val);
114 static FLAC__bool fixup_iff_headers(DecoderSession *d);
115 static FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
116 static void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
117 static void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
118 static void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status);
119 static void print_error_with_state(const DecoderSession *d, const char *message);
120 static void print_stats(const DecoderSession *decoder_session);
121
122
123 /*
124  * public routines
125  */
126 int flac__decode_aiff(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
127 {
128         DecoderSession decoder_session;
129
130         if(!
131                 DecoderSession_construct(
132                         &decoder_session,
133 #ifdef FLAC__HAS_OGG
134                         options.common.is_ogg,
135 #else
136                         /*is_ogg=*/false,
137 #endif
138                         /*is_aiff_out=*/true,
139                         /*is_wave_out=*/false,
140                         options.common.continue_through_decode_errors,
141                         options.common.channel_map_none,
142                         options.common.replaygain_synthesis_spec,
143                         analysis_mode,
144                         aopts,
145                         &options.common.skip_specification,
146                         &options.common.until_specification,
147                         options.common.has_cue_specification? &options.common.cue_specification : 0,
148                         infilename,
149                         outfilename
150                 )
151         )
152                 return 1;
153
154         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
155                 return DecoderSession_finish_error(&decoder_session);
156
157         if(!DecoderSession_process(&decoder_session))
158                 return DecoderSession_finish_error(&decoder_session);
159
160         return DecoderSession_finish_ok(&decoder_session);
161 }
162
163 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
164 {
165         DecoderSession decoder_session;
166
167         if(!
168                 DecoderSession_construct(
169                         &decoder_session,
170 #ifdef FLAC__HAS_OGG
171                         options.common.is_ogg,
172 #else
173                         /*is_ogg=*/false,
174 #endif
175                         /*is_aiff_out=*/false,
176                         /*is_wave_out=*/true,
177                         options.common.continue_through_decode_errors,
178                         options.common.channel_map_none,
179                         options.common.replaygain_synthesis_spec,
180                         analysis_mode,
181                         aopts,
182                         &options.common.skip_specification,
183                         &options.common.until_specification,
184                         options.common.has_cue_specification? &options.common.cue_specification : 0,
185                         infilename,
186                         outfilename
187                 )
188         )
189                 return 1;
190
191         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
192                 return DecoderSession_finish_error(&decoder_session);
193
194         if(!DecoderSession_process(&decoder_session))
195                 return DecoderSession_finish_error(&decoder_session);
196
197         return DecoderSession_finish_ok(&decoder_session);
198 }
199
200 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
201 {
202         DecoderSession decoder_session;
203
204         decoder_session.is_big_endian = options.is_big_endian;
205         decoder_session.is_unsigned_samples = options.is_unsigned_samples;
206
207         if(!
208                 DecoderSession_construct(
209                         &decoder_session,
210 #ifdef FLAC__HAS_OGG
211                         options.common.is_ogg,
212 #else
213                         /*is_ogg=*/false,
214 #endif
215                         /*is_aiff_out=*/false,
216                         /*is_wave_out=*/false,
217                         options.common.continue_through_decode_errors,
218                         options.common.channel_map_none,
219                         options.common.replaygain_synthesis_spec,
220                         analysis_mode,
221                         aopts,
222                         &options.common.skip_specification,
223                         &options.common.until_specification,
224                         options.common.has_cue_specification? &options.common.cue_specification : 0,
225                         infilename,
226                         outfilename
227                 )
228         )
229                 return 1;
230
231         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
232                 return DecoderSession_finish_error(&decoder_session);
233
234         if(!DecoderSession_process(&decoder_session))
235                 return DecoderSession_finish_error(&decoder_session);
236
237         return DecoderSession_finish_ok(&decoder_session);
238 }
239
240 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, FLAC__bool channel_map_none, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, const char *infilename, const char *outfilename)
241 {
242 #ifdef FLAC__HAS_OGG
243         d->is_ogg = is_ogg;
244 #else
245         (void)is_ogg;
246 #endif
247
248         d->is_aiff_out = is_aiff_out;
249         d->is_wave_out = is_wave_out;
250         d->continue_through_decode_errors = continue_through_decode_errors;
251         d->channel_map_none = channel_map_none;
252         d->replaygain.spec = replaygain_synthesis_spec;
253         d->replaygain.apply = false;
254         d->replaygain.scale = 0.0;
255         /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
256         d->test_only = (0 == outfilename);
257         d->analysis_mode = analysis_mode;
258         d->aopts = aopts;
259         d->skip_specification = skip_specification;
260         d->until_specification = until_specification;
261         d->cue_specification = cue_specification;
262
263         d->inbasefilename = grabbag__file_get_basename(infilename);
264         d->outfilename = outfilename;
265
266         d->samples_processed = 0;
267         d->frame_counter = 0;
268         d->abort_flag = false;
269         d->aborting_due_to_until = false;
270         d->aborting_due_to_unparseable = false;
271
272         d->iff_headers_need_fixup = false;
273
274         d->total_samples = 0;
275         d->got_stream_info = false;
276         d->bps = 0;
277         d->channels = 0;
278         d->sample_rate = 0;
279         d->channel_mask = 0;
280
281         d->decoder = 0;
282
283         d->fout = 0; /* initialized with an open file later if necessary */
284
285         FLAC__ASSERT(!(d->test_only && d->analysis_mode));
286
287         if(!d->test_only) {
288                 if(0 == strcmp(outfilename, "-")) {
289                         d->fout = grabbag__file_get_binary_stdout();
290                 }
291                 else {
292                         if(0 == (d->fout = fopen(outfilename, "wb"))) {
293                                 flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
294                                 DecoderSession_destroy(d, /*error_occurred=*/true);
295                                 return false;
296                         }
297                 }
298         }
299
300         if(analysis_mode)
301                 flac__analyze_init(aopts);
302
303         return true;
304 }
305
306 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
307 {
308         if(0 != d->fout && d->fout != stdout) {
309                 fclose(d->fout);
310                 if(error_occurred)
311                         unlink(d->outfilename);
312         }
313 }
314
315 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, decode_options_t decode_options, const char *infilename)
316 {
317         FLAC__StreamDecoderInitStatus init_status;
318         FLAC__uint32 test = 1;
319
320         is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
321
322         decoder_session->decoder = FLAC__stream_decoder_new();
323
324         if(0 == decoder_session->decoder) {
325                 flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
326                 return false;
327         }
328
329         FLAC__stream_decoder_set_md5_checking(decoder_session->decoder, true);
330         if (0 != decoder_session->cue_specification)
331                 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_CUESHEET);
332         if (decoder_session->replaygain.spec.apply)
333                 FLAC__stream_decoder_set_metadata_respond(decoder_session->decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
334
335 #ifdef FLAC__HAS_OGG
336         if(decoder_session->is_ogg) {
337                 if(!decode_options.use_first_serial_number)
338                         FLAC__stream_decoder_set_ogg_serial_number(decoder_session->decoder, decode_options.serial_number);
339                 init_status = FLAC__stream_decoder_init_ogg_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
340         }
341         else
342 #else
343         (void)decode_options;
344 #endif
345         {
346                 init_status = FLAC__stream_decoder_init_file(decoder_session->decoder, strcmp(infilename, "-")? infilename : 0, write_callback, metadata_callback, error_callback, /*client_data=*/decoder_session);
347         }
348
349         if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
350                 print_error_with_init_status(decoder_session, "ERROR initializing decoder", init_status);
351                 return false;
352         }
353
354         return true;
355 }
356
357 FLAC__bool DecoderSession_process(DecoderSession *d)
358 {
359         if(!FLAC__stream_decoder_process_until_end_of_metadata(d->decoder)) {
360                 flac__utils_printf(stderr, 2, "\n");
361                 print_error_with_state(d, "ERROR while decoding metadata");
362                 return false;
363         }
364         if(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM) {
365                 flac__utils_printf(stderr, 2, "\n");
366                 print_error_with_state(d, "ERROR during metadata decoding");
367                 if(!d->continue_through_decode_errors)
368                         return false;
369         }
370
371         if(d->abort_flag)
372                 return false;
373
374         /* set channel mapping */
375         if(!d->channel_map_none) {
376                 /* currently FLAC order matches SMPTE/WAVEFORMATEXTENSIBLE order, so no reordering is necessary; see encode.c */
377                 /* only the channel mask must be set if it was not already picked up from the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag */
378                 if(d->channels == 1) {
379                         if(d->channel_mask == 0)
380                                 d->channel_mask = 0x0001;
381                 }
382                 else if(d->channels == 2) {
383                         if(d->channel_mask == 0)
384                                 d->channel_mask = 0x0003;
385                 }
386                 else if(d->channels == 3) {
387                         if(d->channel_mask == 0)
388                                 d->channel_mask = 0x0007;
389                 }
390                 else if(d->channels == 4) {
391                         if(d->channel_mask == 0)
392                                 d->channel_mask = 0x0033;
393                 }
394                 else if(d->channels == 5) {
395                         if(d->channel_mask == 0)
396                                 d->channel_mask = 0x0607;
397                 }
398                 else if(d->channels == 6) {
399                         if(d->channel_mask == 0)
400                                 d->channel_mask = 0x060f;
401                 }
402         }
403
404         /* write the WAVE/AIFF headers if necessary */
405         if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out)) {
406                 if(!write_iff_headers(d->fout, d, d->total_samples)) {
407                         d->abort_flag = true;
408                         return false;
409                 }
410         }
411
412         if(d->skip_specification->value.samples > 0) {
413                 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
414
415                 if(!FLAC__stream_decoder_seek_absolute(d->decoder, skip)) {
416                         print_error_with_state(d, "ERROR seeking while skipping bytes");
417                         return false;
418                 }
419         }
420         if(!FLAC__stream_decoder_process_until_end_of_stream(d->decoder) && !d->aborting_due_to_until) {
421                 flac__utils_printf(stderr, 2, "\n");
422                 print_error_with_state(d, "ERROR while decoding data");
423                 if(!d->continue_through_decode_errors)
424                         return false;
425         }
426         if(FLAC__stream_decoder_get_state(d->decoder) > FLAC__STREAM_DECODER_END_OF_STREAM && !d->aborting_due_to_until) {
427                 flac__utils_printf(stderr, 2, "\n");
428                 print_error_with_state(d, "ERROR during decoding");
429                 return false;
430         }
431
432         if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out) && ((d->total_samples * d->channels * ((d->bps+7)/8)) & 1)) {
433                 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
434                         print_error_with_state(d, d->is_wave_out?
435                                 "ERROR writing pad byte to WAVE data chunk" :
436                                 "ERROR writing pad byte to AIFF SSND chunk"
437                         );
438                         return false;
439                 }
440         }
441
442         return true;
443 }
444
445 int DecoderSession_finish_ok(DecoderSession *d)
446 {
447         FLAC__bool ok = true, md5_failure = false;
448
449         if(d->decoder) {
450                 md5_failure = !FLAC__stream_decoder_finish(d->decoder) && !d->aborting_due_to_until;
451                 print_stats(d);
452                 FLAC__stream_decoder_delete(d->decoder);
453         }
454         if(d->analysis_mode)
455                 flac__analyze_finish(d->aopts);
456         if(md5_failure) {
457                 flac__utils_printf(stderr, 1, "\r%s: ERROR, MD5 signature mismatch\n", d->inbasefilename);
458                 ok = d->continue_through_decode_errors;
459         }
460         else if(!d->got_stream_info) {
461                 flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since there was no STREAMINFO\n", d->inbasefilename);
462         }
463         else {
464                 flac__utils_printf(stderr, 2, "\r%s: %s         \n", d->inbasefilename, d->test_only? "ok           ":d->analysis_mode?"done           ":"done");
465         }
466         DecoderSession_destroy(d, /*error_occurred=*/!ok);
467         if((d->is_wave_out || d->is_aiff_out) && (d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))))
468                 if(!fixup_iff_headers(d))
469                         return 1;
470         return ok? 0 : 1;
471 }
472
473 int DecoderSession_finish_error(DecoderSession *d)
474 {
475         if(d->decoder) {
476                 (void)FLAC__stream_decoder_finish(d->decoder);
477                 FLAC__stream_decoder_delete(d->decoder);
478         }
479         if(d->analysis_mode)
480                 flac__analyze_finish(d->aopts);
481         DecoderSession_destroy(d, /*error_occurred=*/true);
482         return 1;
483 }
484
485 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
486 {
487         /* convert from mm:ss.sss to sample number if necessary */
488         flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
489
490         /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
491         if(spec->is_relative && spec->value.samples == 0) {
492                 spec->is_relative = false;
493                 return true;
494         }
495
496         /* in any other case the total samples in the input must be known */
497         if(total_samples_in_input == 0) {
498                 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
499                 return false;
500         }
501
502         FLAC__ASSERT(spec->value_is_samples);
503
504         /* convert relative specifications to absolute */
505         if(spec->is_relative) {
506                 if(spec->value.samples <= 0)
507                         spec->value.samples += (FLAC__int64)total_samples_in_input;
508                 else
509                         spec->value.samples += skip;
510                 spec->is_relative = false;
511         }
512
513         /* error check */
514         if(spec->value.samples < 0) {
515                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
516                 return false;
517         }
518         if((FLAC__uint64)spec->value.samples <= skip) {
519                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
520                 return false;
521         }
522         if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
523                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
524                 return false;
525         }
526
527         return true;
528 }
529
530 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
531 {
532         const char *fmt_desc = decoder_session->is_wave_out? "WAVE" : "AIFF";
533         const FLAC__bool is_waveformatextensible = decoder_session->is_wave_out && (decoder_session->channel_mask == 2 || decoder_session->channel_mask > 3 || decoder_session->bps%8 || decoder_session->channels > 2);
534         FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
535         const FLAC__uint32 aligned_data_size = (FLAC__uint32)((data_size+1) & (~1U)); /* we'll check for overflow later */
536         if(samples == 0) {
537                 if(f == stdout) {
538                         flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
539                         flac__utils_printf(stderr, 1, "             Generated %s file will have a data chunk size of 0.  Try\n", fmt_desc);
540                         flac__utils_printf(stderr, 1, "             decoding directly to a file instead.\n");
541                 }
542                 else {
543                         decoder_session->iff_headers_need_fixup = true;
544                 }
545         }
546         if(data_size >= 0xFFFFFFDC) {
547                 flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file chunk\n", decoder_session->inbasefilename, fmt_desc);
548                 return false;
549         }
550         if(decoder_session->is_wave_out) {
551                 if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
552                         return false;
553
554                 if(!write_little_endian_uint32(f, aligned_data_size+(is_waveformatextensible?60:36))) /* filesize-8 */
555                         return false;
556
557                 if(flac__utils_fwrite("WAVEfmt ", 1, 8, f) != 8)
558                         return false;
559
560                 if(!write_little_endian_uint32(f, is_waveformatextensible? 40 : 16)) /* chunk size */
561                         return false;
562
563                 if(!write_little_endian_uint16(f, (FLAC__uint16)(is_waveformatextensible? 65534 : 1))) /* compression code */
564                         return false;
565
566                 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
567                         return false;
568
569                 if(!write_little_endian_uint32(f, decoder_session->sample_rate))
570                         return false;
571
572                 if(!write_little_endian_uint32(f, decoder_session->sample_rate * decoder_session->channels * ((decoder_session->bps+7) / 8)))
573                         return false;
574
575                 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels * ((decoder_session->bps+7) / 8)))) /* block align */
576                         return false;
577
578                 if(!write_little_endian_uint16(f, (FLAC__uint16)(((decoder_session->bps+7)/8)*8))) /* bits per sample */
579                         return false;
580
581                 if(is_waveformatextensible) {
582                         if(!write_little_endian_uint16(f, (FLAC__uint16)22)) /* cbSize */
583                                 return false;
584
585                         if(!write_little_endian_uint16(f, (FLAC__uint16)decoder_session->bps)) /* validBitsPerSample */
586                                 return false;
587
588                         if(!write_little_endian_uint32(f, decoder_session->channel_mask))
589                                 return false;
590
591                         /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */
592                         if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f) != 16)
593                                 return false;
594                 }
595
596                 if(flac__utils_fwrite("data", 1, 4, f) != 4)
597                         return false;
598
599                 if(!write_little_endian_uint32(f, (FLAC__uint32)data_size)) /* data size */
600                         return false;
601         }
602         else {
603                 if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
604                         return false;
605
606                 if(!write_big_endian_uint32(f, aligned_data_size+46)) /* filesize-8 */
607                         return false;
608
609                 if(flac__utils_fwrite("AIFFCOMM", 1, 8, f) != 8)
610                         return false;
611
612                 if(flac__utils_fwrite("\000\000\000\022", 1, 4, f) != 4) /* chunk size = 18 */
613                         return false;
614
615                 if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
616                         return false;
617
618                 if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
619                         return false;
620
621                 if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->bps)))
622                         return false;
623
624                 if(!write_sane_extended(f, decoder_session->sample_rate))
625                         return false;
626
627                 if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
628                         return false;
629
630                 if(!write_big_endian_uint32(f, (FLAC__uint32)data_size+8)) /* data size */
631                         return false;
632
633                 if(!write_big_endian_uint32(f, 0/*offset*/))
634                         return false;
635
636                 if(!write_big_endian_uint32(f, 0/*block_size*/))
637                         return false;
638         }
639
640         return true;
641 }
642
643 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
644 {
645         FLAC__byte *b = (FLAC__byte*)(&val);
646         if(is_big_endian_host_) {
647                 FLAC__byte tmp;
648                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
649         }
650         return flac__utils_fwrite(b, 1, 2, f) == 2;
651 }
652
653 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
654 {
655         FLAC__byte *b = (FLAC__byte*)(&val);
656         if(is_big_endian_host_) {
657                 FLAC__byte tmp;
658                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
659                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
660         }
661         return flac__utils_fwrite(b, 1, 4, f) == 4;
662 }
663
664 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
665 {
666         FLAC__byte *b = (FLAC__byte*)(&val);
667         if(!is_big_endian_host_) {
668                 FLAC__byte tmp;
669                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
670         }
671         return flac__utils_fwrite(b, 1, 2, f) == 2;
672 }
673
674 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
675 {
676         FLAC__byte *b = (FLAC__byte*)(&val);
677         if(!is_big_endian_host_) {
678                 FLAC__byte tmp;
679                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
680                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
681         }
682         return flac__utils_fwrite(b, 1, 4, f) == 4;
683 }
684
685 FLAC__bool write_sane_extended(FILE *f, unsigned val)
686         /* Write to 'f' a SANE extended representation of 'val'.  Return false if
687         * the write succeeds; return true otherwise.
688         *
689         * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
690         * of exponent, and 64 bits of significand (mantissa).  Unlike most IEEE-754
691         * representations, it does not imply a 1 above the MSB of the significand.
692         *
693         * Preconditions:
694         *  val!=0U
695         */
696 {
697         unsigned int shift, exponent;
698
699         FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
700
701         for(shift= 0U; (val>>(31-shift))==0U; ++shift)
702                 ;
703         val<<= shift;
704         exponent= 63U-(shift+32U); /* add 32 for unused second word */
705
706         if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
707                 return false;
708         if(!write_big_endian_uint32(f, val))
709                 return false;
710         if(!write_big_endian_uint32(f, 0)) /* unused second word */
711                 return false;
712
713         return true;
714 }
715
716 FLAC__bool fixup_iff_headers(DecoderSession *d)
717 {
718         const char *fmt_desc = (d->is_wave_out? "WAVE" : "AIFF");
719         FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
720
721         if(0 == f) {
722                 flac__utils_printf(stderr, 1, "ERROR, couldn't open file %s while fixing up %s chunk size: %s\n", d->outfilename, fmt_desc, strerror(errno));
723                 return false;
724         }
725
726         if(!write_iff_headers(f, d, d->samples_processed)) {
727                 fclose(f);
728                 return false;
729         }
730
731         fclose(f);
732         return true;
733 }
734
735 FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
736 {
737         DecoderSession *decoder_session = (DecoderSession*)client_data;
738         FILE *fout = decoder_session->fout;
739         const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
740         const unsigned shift = ((decoder_session->is_wave_out || decoder_session->is_aiff_out) && (bps%8)? 8-(bps%8): 0);
741         FLAC__bool is_big_endian = (decoder_session->is_aiff_out? true : (decoder_session->is_wave_out? false : decoder_session->is_big_endian));
742         FLAC__bool is_unsigned_samples = (decoder_session->is_aiff_out? false : (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples));
743         unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
744         static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
745         FLAC__uint8  *u8buffer  = (FLAC__uint8  *)s8buffer;
746         FLAC__int16  *s16buffer = (FLAC__int16  *)s8buffer;
747         FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
748         FLAC__int32  *s32buffer = (FLAC__int32  *)s8buffer;
749         FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
750         size_t bytes_to_write = 0;
751
752         (void)decoder;
753
754         if(decoder_session->abort_flag)
755                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
756
757         /* sanity-check the bits-per-sample */
758         if(decoder_session->bps) {
759                 if(bps != decoder_session->bps) {
760                         if(decoder_session->got_stream_info)
761                                 flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, bps, decoder_session->bps);
762                         else
763                                 flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, bps, decoder_session->bps);
764                         if(!decoder_session->continue_through_decode_errors)
765                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
766                 }
767         }
768         else {
769                 /* must not have gotten STREAMINFO, save the bps from the frame header */
770                 FLAC__ASSERT(!decoder_session->got_stream_info);
771                 decoder_session->bps = bps;
772         }
773
774         /* sanity-check the #channels */
775         if(decoder_session->channels) {
776                 if(channels != decoder_session->channels) {
777                         if(decoder_session->got_stream_info)
778                                 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
779                         else
780                                 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, channels, decoder_session->channels);
781                         if(!decoder_session->continue_through_decode_errors)
782                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
783                 }
784         }
785         else {
786                 /* must not have gotten STREAMINFO, save the #channels from the frame header */
787                 FLAC__ASSERT(!decoder_session->got_stream_info);
788                 decoder_session->channels = channels;
789         }
790
791         /* sanity-check the sample rate */
792         if(decoder_session->sample_rate) {
793                 if(frame->header.sample_rate != decoder_session->sample_rate) {
794                         if(decoder_session->got_stream_info)
795                                 flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
796                         else
797                                 flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
798                         if(!decoder_session->continue_through_decode_errors)
799                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
800                 }
801         }
802         else {
803                 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
804                 FLAC__ASSERT(!decoder_session->got_stream_info);
805                 decoder_session->sample_rate = frame->header.sample_rate;
806         }
807
808         /*
809          * limit the number of samples to accept based on --until
810          */
811         FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
812         /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
813         if(decoder_session->skip_specification->is_relative) {
814                 if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
815                         decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
816                 else {
817                         flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --skip because the total sample count was not found in the metadata\n", decoder_session->inbasefilename);
818                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
819                 }
820         }
821         if(decoder_session->until_specification->is_relative) {
822                 if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
823                         decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
824                 else {
825                         flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until because the total sample count was not found in the metadata\n", decoder_session->inbasefilename);
826                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
827                 }
828         }
829         FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
830         FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
831         if(decoder_session->until_specification->value.samples > 0) {
832                 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
833                 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
834                 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
835                 FLAC__ASSERT(until >= input_samples_passed);
836                 if(input_samples_passed + wide_samples > until)
837                         wide_samples = (unsigned)(until - input_samples_passed);
838                 if (wide_samples == 0) {
839                         decoder_session->abort_flag = true;
840                         decoder_session->aborting_due_to_until = true;
841                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
842                 }
843         }
844
845         if(wide_samples > 0) {
846                 decoder_session->samples_processed += wide_samples;
847                 decoder_session->frame_counter++;
848
849                 if(!(decoder_session->frame_counter & 0x3f))
850                         print_stats(decoder_session);
851
852                 if(decoder_session->analysis_mode) {
853                         flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->aopts, fout);
854                 }
855                 else if(!decoder_session->test_only) {
856                         if(shift && !decoder_session->replaygain.apply) {
857                                 for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
858                                         for(channel = 0; channel < channels; channel++)
859                                                 ((FLAC__int32**)buffer)[channel][wide_sample] <<= shift;/*@@@@@@un-const'ing the buffer is hacky but safe*/
860                         }
861                         if(decoder_session->replaygain.apply) {
862                                 bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
863                                         u8buffer,
864                                         !is_big_endian,
865                                         is_unsigned_samples,
866                                         buffer,
867                                         wide_samples,
868                                         channels,
869                                         bps, /* source_bps */
870                                         bps+shift, /* target_bps */
871                                         decoder_session->replaygain.scale,
872                                         decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
873                                         decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
874                                         &decoder_session->replaygain.dither_context
875                                 );
876                         }
877                         else if(bps+shift == 8) {
878                                 if(is_unsigned_samples) {
879                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
880                                                 for(channel = 0; channel < channels; channel++, sample++)
881                                                         u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
882                                 }
883                                 else {
884                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
885                                                 for(channel = 0; channel < channels; channel++, sample++)
886                                                         s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
887                                 }
888                                 bytes_to_write = sample;
889                         }
890                         else if(bps+shift == 16) {
891                                 if(is_unsigned_samples) {
892                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
893                                                 for(channel = 0; channel < channels; channel++, sample++)
894                                                         u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
895                                 }
896                                 else {
897                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
898                                                 for(channel = 0; channel < channels; channel++, sample++)
899                                                         s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
900                                 }
901                                 if(is_big_endian != is_big_endian_host_) {
902                                         unsigned char tmp;
903                                         const unsigned bytes = sample * 2;
904                                         for(byte = 0; byte < bytes; byte += 2) {
905                                                 tmp = u8buffer[byte];
906                                                 u8buffer[byte] = u8buffer[byte+1];
907                                                 u8buffer[byte+1] = tmp;
908                                         }
909                                 }
910                                 bytes_to_write = 2 * sample;
911                         }
912                         else if(bps+shift == 24) {
913                                 if(is_unsigned_samples) {
914                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
915                                                 for(channel = 0; channel < channels; channel++, sample++)
916                                                         u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
917                                 }
918                                 else {
919                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
920                                                 for(channel = 0; channel < channels; channel++, sample++)
921                                                         s32buffer[sample] = buffer[channel][wide_sample];
922                                 }
923                                 if(is_big_endian != is_big_endian_host_) {
924                                         unsigned char tmp;
925                                         const unsigned bytes = sample * 4;
926                                         for(byte = 0; byte < bytes; byte += 4) {
927                                                 tmp = u8buffer[byte];
928                                                 u8buffer[byte] = u8buffer[byte+3];
929                                                 u8buffer[byte+3] = tmp;
930                                                 tmp = u8buffer[byte+1];
931                                                 u8buffer[byte+1] = u8buffer[byte+2];
932                                                 u8buffer[byte+2] = tmp;
933                                         }
934                                 }
935                                 if(is_big_endian) {
936                                         unsigned lbyte;
937                                         const unsigned bytes = sample * 4;
938                                         for(lbyte = byte = 0; byte < bytes; ) {
939                                                 byte++;
940                                                 u8buffer[lbyte++] = u8buffer[byte++];
941                                                 u8buffer[lbyte++] = u8buffer[byte++];
942                                                 u8buffer[lbyte++] = u8buffer[byte++];
943                                         }
944                                 }
945                                 else {
946                                         unsigned lbyte;
947                                         const unsigned bytes = sample * 4;
948                                         for(lbyte = byte = 0; byte < bytes; ) {
949                                                 u8buffer[lbyte++] = u8buffer[byte++];
950                                                 u8buffer[lbyte++] = u8buffer[byte++];
951                                                 u8buffer[lbyte++] = u8buffer[byte++];
952                                                 byte++;
953                                         }
954                                 }
955                                 bytes_to_write = 3 * sample;
956                         }
957                         else {
958                                 FLAC__ASSERT(0);
959                                 /* double protection */
960                                 decoder_session->abort_flag = true;
961                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
962                         }
963                 }
964         }
965         if(bytes_to_write > 0) {
966                 if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
967                         /* if a pipe closed when writing to stdout, we let it go without an error message */
968                         if(errno == EPIPE && decoder_session->fout == stdout)
969                                 decoder_session->aborting_due_to_until = true;
970                         decoder_session->abort_flag = true;
971                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
972                 }
973         }
974         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
975 }
976
977 void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
978 {
979         DecoderSession *decoder_session = (DecoderSession*)client_data;
980         (void)decoder;
981         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
982                 FLAC__uint64 skip, until;
983                 decoder_session->got_stream_info = true;
984                 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
985                 decoder_session->channels = metadata->data.stream_info.channels;
986                 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
987
988                 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
989                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
990                 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
991
992                 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
993                 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
994                         flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
995                         decoder_session->abort_flag = true;
996                         return;
997                 }
998                 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
999                         flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1000                         decoder_session->abort_flag = true;
1001                         return;
1002                 }
1003                 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1004                 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1005
1006                 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1007                 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1008                         decoder_session->abort_flag = true;
1009                         return;
1010                 }
1011                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1012                 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1013
1014                 if(until > 0) {
1015                         FLAC__ASSERT(decoder_session->total_samples != 0);
1016                         FLAC__ASSERT(0 == decoder_session->cue_specification);
1017                         decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1018                 }
1019
1020                 if(decoder_session->bps < 4 || decoder_session->bps > 24) {
1021                         flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is %u, must be 4-24\n", decoder_session->inbasefilename, decoder_session->bps);
1022                         decoder_session->abort_flag = true;
1023                         return;
1024                 }
1025         }
1026         else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1027                 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1028                 if(decoder_session->total_samples == 0) {
1029                         flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1030                         decoder_session->abort_flag = true;
1031                         return;
1032                 }
1033
1034                 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);
1035
1036                 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1037                 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1038
1039                 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1040                 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1041
1042                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1043                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1044                 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1045                 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1046
1047                 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1048         }
1049         else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1050                 if (decoder_session->replaygain.spec.apply) {
1051                         double reference, gain, peak;
1052                         if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &reference, &gain, &peak))) {
1053                                 flac__utils_printf(stderr, 1, "%s: WARNING: can't get %s (or even %s) ReplayGain tags\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", decoder_session->replaygain.spec.use_album_gain? "track":"album");
1054                         }
1055                         else {
1056                                 const char *ls[] = { "no", "peak", "hard" };
1057                                 const char *ns[] = { "no", "low", "medium", "high" };
1058                                 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1059                                 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1060                                 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1061                                 flac__utils_printf(stderr, 1, "%s: INFO: applying %s ReplayGain (gain=%0.2fdB+preamp=%0.1fdB, %s noise shaping, %s limiting) to output\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", gain, decoder_session->replaygain.spec.preamp, ns[decoder_session->replaygain.spec.noise_shaping], ls[decoder_session->replaygain.spec.limiter]);
1062                                 flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1063                         }
1064                 }
1065                 (void)flac__utils_get_channel_mask_tag(metadata, &decoder_session->channel_mask);
1066         }
1067 }
1068
1069 void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1070 {
1071         DecoderSession *decoder_session = (DecoderSession*)client_data;
1072         (void)decoder;
1073         flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1074         if(!decoder_session->continue_through_decode_errors) {
1075                 decoder_session->abort_flag = true;
1076                 if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1077                         decoder_session->aborting_due_to_unparseable = true;
1078         }
1079 }
1080
1081 void print_error_with_init_status(const DecoderSession *d, const char *message, FLAC__StreamDecoderInitStatus init_status)
1082 {
1083         const int ilen = strlen(d->inbasefilename) + 1;
1084
1085         flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1086
1087         flac__utils_printf(stderr, 1, "%*s init status = %s\n", ilen, "", FLAC__StreamDecoderInitStatusString[init_status]);
1088
1089         /* print out some more info for some errors: */
1090         if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE) {
1091                 flac__utils_printf(stderr, 1,
1092                         "\n"
1093                         "An error occurred opening the input file; it is likely that it does not exist\n"
1094                         "or is not readable.\n"
1095                 );
1096         }
1097 }
1098
1099 void print_error_with_state(const DecoderSession *d, const char *message)
1100 {
1101         const int ilen = strlen(d->inbasefilename) + 1;
1102
1103         flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1104         flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", FLAC__stream_decoder_get_resolved_state_string(d->decoder));
1105
1106         /* print out some more info for some errors: */
1107         if (d->aborting_due_to_unparseable) {
1108                 flac__utils_printf(stderr, 1,
1109                         "\n"
1110                         "The FLAC stream may have been created by a more advanced encoder.  Try\n"
1111                         "  metaflac --show-vendor-tag %s\n"
1112                         "If the version number is greater than %s, this decoder is probably\n"
1113                         "not able to decode the file.  If the version number is not, the file\n"
1114                         "may be corrupted, or you may have found a bug.  In this case please\n"
1115                         "submit a bug report to\n"
1116                         "    http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
1117                         "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1118                         d->inbasefilename, FLAC__VERSION_STRING
1119                 );
1120         }
1121 }
1122
1123 void print_stats(const DecoderSession *decoder_session)
1124 {
1125         if(flac__utils_verbosity_ >= 2) {
1126 #if defined _MSC_VER || defined __MINGW32__
1127                 /* with MSVC you have to spoon feed it the casting */
1128                 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1129 #else
1130                 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1131 #endif
1132                 if(decoder_session->total_samples > 0) {
1133                         fprintf(stderr, "\r%s: %s%u%% complete",
1134                                 decoder_session->inbasefilename,
1135                                 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1136                                 (unsigned)floor(progress + 0.5)
1137                         );
1138                 }
1139                 else {
1140                         fprintf(stderr, "\r%s: %s %u samples",
1141                                 decoder_session->inbasefilename,
1142                                 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1143                                 (unsigned)decoder_session->samples_processed
1144                         );
1145                 }
1146         }
1147 }