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