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