1 /* flac - Command-line FLAC encoder/decoder
2 * Copyright (C) 2000-2009 Josh Coalson
3 * Copyright (C) 2011-2016 Xiph.Org Foundation
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.
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.
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.
25 #include <math.h> /* for floor() */
26 #include <stdio.h> /* for FILE etc. */
27 #include <string.h> /* for strcmp(), strerror() */
29 #include "share/grabbag.h"
30 #include "share/replaygain_synthesis.h"
31 #include "share/compat.h"
37 FLAC__bool use_first_serial_number
;
42 FLAC__bool treat_warnings_as_errors
;
43 FLAC__bool continue_through_decode_errors
;
44 FLAC__bool channel_map_none
;
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 */
50 DitherContext dither_context
;
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
;
60 const char *inbasefilename
;
61 const char *infilename
;
62 const char *outfilename
;
64 FLAC__uint64 samples_processed
;
65 uint32_t 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 */
71 FLAC__bool iff_headers_need_fixup
;
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
;
81 FLAC__uint32 channel_mask
;
83 /* these are used only in analyze mode */
84 FLAC__uint64 decode_position
;
86 FLAC__StreamDecoder
*decoder
;
90 foreign_metadata_t
*foreign_metadata
; /* NULL unless --keep-foreign-metadata requested */
91 FLAC__off_t fm_offset1
, fm_offset2
, fm_offset3
;
95 static FLAC__bool is_big_endian_host_
;
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
, uint32_t 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
, uint32_t bps
, uint32_t channels
, uint32_t sample_rate
, FLAC__uint32 channel_mask
);
110 static FLAC__bool
write_aiff_form_comm_chunk(FILE *f
, FLAC__uint64 samples
, uint32_t bps
, uint32_t channels
, uint32_t 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
, uint32_t 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
);
129 int flac__decode_file(const char *infilename
, const char *outfilename
, FLAC__bool analysis_mode
, analysis_options aopts
, decode_options_t options
)
131 DecoderSession decoder_session
;
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
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
;
148 DecoderSession_construct(
152 options
.use_first_serial_number
,
153 options
.serial_number
,
156 /*use_first_serial_number=*/false,
160 options
.treat_warnings_as_errors
,
161 options
.continue_through_decode_errors
,
162 options
.channel_map_none
,
163 options
.replaygain_synthesis_spec
,
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
,
177 if(!DecoderSession_init_decoder(&decoder_session
, infilename
))
178 return DecoderSession_finish_error(&decoder_session
);
180 if(!DecoderSession_process(&decoder_session
))
181 return DecoderSession_finish_error(&decoder_session
);
183 return DecoderSession_finish_ok(&decoder_session
);
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
)
190 d
->use_first_serial_number
= use_first_serial_number
;
191 d
->serial_number
= serial_number
;
194 (void)use_first_serial_number
;
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
;
209 d
->skip_specification
= skip_specification
;
210 d
->until_specification
= until_specification
;
211 d
->cue_specification
= cue_specification
;
213 d
->inbasefilename
= grabbag__file_get_basename(infilename
);
214 d
->infilename
= infilename
;
215 d
->outfilename
= outfilename
;
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;
224 d
->iff_headers_need_fixup
= false;
226 d
->total_samples
= 0;
227 d
->got_stream_info
= false;
228 d
->has_md5sum
= false;
234 d
->decode_position
= 0;
238 d
->fout
= 0; /* initialized with an open file later if necessary */
240 d
->foreign_metadata
= foreign_metadata
;
242 FLAC__ASSERT(!(d
->test_only
&& d
->analysis_mode
));
245 if(0 == strcmp(outfilename
, "-")) {
246 d
->fout
= grabbag__file_get_binary_stdout();
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);
258 flac__analyze_init(aopts
);
263 void DecoderSession_destroy(DecoderSession
*d
, FLAC__bool error_occurred
)
265 if(0 != d
->fout
&& d
->fout
!= stdout
) {
266 #if defined _WIN32 && !defined __CYGWIN__
267 if(!error_occurred
) {
268 FLAC__off_t written_size
= ftello(d
->fout
);
269 if(written_size
> 0) {
270 HANDLE fh
= CreateFile_utf8(d
->outfilename
, GENERIC_READ
|GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
271 if(fh
!= INVALID_HANDLE_VALUE
) {
272 if(GetFileType(fh
) == FILE_TYPE_DISK
) {
274 size
.QuadPart
= written_size
;
275 if(SetFilePointerEx(fh
, size
, NULL
, FILE_CURRENT
)) /* correct the file size */
285 flac_unlink(d
->outfilename
);
289 FLAC__bool
DecoderSession_init_decoder(DecoderSession
*decoder_session
, const char *infilename
)
291 FLAC__StreamDecoderInitStatus init_status
;
292 FLAC__uint32 test
= 1;
294 is_big_endian_host_
= (*((FLAC__byte
*)(&test
)))? false : true;
296 if(!decoder_session
->analysis_mode
&& !decoder_session
->test_only
&& decoder_session
->foreign_metadata
) {
298 if(!flac__foreign_metadata_read_from_flac(decoder_session
->foreign_metadata
, infilename
, &error
)) {
299 flac__utils_printf(stderr
, 1, "%s: ERROR reading foreign metadata: %s\n", decoder_session
->inbasefilename
, error
);
304 decoder_session
->decoder
= FLAC__stream_decoder_new();
306 if(0 == decoder_session
->decoder
) {
307 flac__utils_printf(stderr
, 1, "%s: ERROR creating the decoder instance\n", decoder_session
->inbasefilename
);
311 FLAC__stream_decoder_set_md5_checking(decoder_session
->decoder
, true);
312 if (0 != decoder_session
->cue_specification
)
313 FLAC__stream_decoder_set_metadata_respond(decoder_session
->decoder
, FLAC__METADATA_TYPE_CUESHEET
);
314 if (decoder_session
->replaygain
.spec
.apply
|| !decoder_session
->channel_map_none
)
315 FLAC__stream_decoder_set_metadata_respond(decoder_session
->decoder
, FLAC__METADATA_TYPE_VORBIS_COMMENT
);
318 if(decoder_session
->is_ogg
) {
319 if(!decoder_session
->use_first_serial_number
)
320 FLAC__stream_decoder_set_ogg_serial_number(decoder_session
->decoder
, decoder_session
->serial_number
);
321 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
);
326 init_status
= FLAC__stream_decoder_init_file(decoder_session
->decoder
, strcmp(infilename
, "-")? infilename
: 0, write_callback
, metadata_callback
, error_callback
, /*client_data=*/decoder_session
);
329 if(init_status
!= FLAC__STREAM_DECODER_INIT_STATUS_OK
) {
330 print_error_with_init_status(decoder_session
, "ERROR initializing decoder", init_status
);
337 FLAC__bool
DecoderSession_process(DecoderSession
*d
)
339 if(!FLAC__stream_decoder_process_until_end_of_metadata(d
->decoder
)) {
340 flac__utils_printf(stderr
, 2, "\n");
341 print_error_with_state(d
, "ERROR while decoding metadata");
344 if(FLAC__stream_decoder_get_state(d
->decoder
) > FLAC__STREAM_DECODER_END_OF_STREAM
) {
345 flac__utils_printf(stderr
, 2, "\n");
346 print_error_with_state(d
, "ERROR during metadata decoding");
347 if(!d
->continue_through_decode_errors
)
354 /* set channel mapping */
355 /* currently FLAC order matches SMPTE/WAVEFORMATEXTENSIBLE order, so no reordering is necessary; see encode.c */
356 /* only the channel mask must be set if it was not already picked up from the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag */
357 if(!d
->channel_map_none
&& d
->channel_mask
== 0) {
358 if(d
->channels
== 1) {
359 d
->channel_mask
= 0x0004;
361 else if(d
->channels
== 2) {
362 d
->channel_mask
= 0x0003;
364 else if(d
->channels
== 3) {
365 d
->channel_mask
= 0x0007;
367 else if(d
->channels
== 4) {
368 d
->channel_mask
= 0x0033;
370 else if(d
->channels
== 5) {
371 d
->channel_mask
= 0x0607;
373 else if(d
->channels
== 6) {
374 d
->channel_mask
= 0x060f;
376 else if(d
->channels
== 7) {
377 d
->channel_mask
= 0x070f;
379 else if(d
->channels
== 8) {
380 d
->channel_mask
= 0x063f;
384 #if defined _WIN32 && !defined __CYGWIN__
385 if(!d
->analysis_mode
&& !d
->test_only
&& d
->total_samples
> 0 && d
->fout
!= stdout
) {
386 HANDLE fh
= CreateFile_utf8(d
->outfilename
, GENERIC_READ
|GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
387 if(fh
!= INVALID_HANDLE_VALUE
) {
388 if (GetFileType(fh
) == FILE_TYPE_DISK
) {
390 size
.QuadPart
= d
->total_samples
* d
->channels
* ((d
->bps
+7)/8);
391 if(d
->format
!= FORMAT_RAW
) {
392 size
.QuadPart
+= 512;
393 if(d
->foreign_metadata
) {
395 for(i
= d
->format
==FORMAT_RF64
?2:1; i
< d
->foreign_metadata
->num_blocks
; i
++) {
396 if(i
!= d
->foreign_metadata
->format_block
&& i
!= d
->foreign_metadata
->audio_block
)
397 size
.QuadPart
+= d
->foreign_metadata
->blocks
[i
].size
;
402 if(SetFilePointerEx(fh
, size
, NULL
, FILE_CURRENT
)) /* tell filesystem the expected filesize to eliminate fragmentation */
410 /* write the WAVE/AIFF headers if necessary */
411 if(!d
->analysis_mode
&& !d
->test_only
&& d
->format
!= FORMAT_RAW
) {
412 if(!write_iff_headers(d
->fout
, d
, d
->total_samples
)) {
413 d
->abort_flag
= true;
418 if(d
->skip_specification
->value
.samples
> 0) {
419 const FLAC__uint64 skip
= (FLAC__uint64
)d
->skip_specification
->value
.samples
;
421 if(!FLAC__stream_decoder_seek_absolute(d
->decoder
, skip
)) {
422 print_error_with_state(d
, "ERROR seeking while skipping bytes");
426 if(!FLAC__stream_decoder_process_until_end_of_stream(d
->decoder
) && !d
->aborting_due_to_until
) {
427 flac__utils_printf(stderr
, 2, "\n");
428 print_error_with_state(d
, "ERROR while decoding data");
429 if(!d
->continue_through_decode_errors
)
433 (d
->abort_flag
&& !(d
->aborting_due_to_until
|| d
->continue_through_decode_errors
)) ||
434 (FLAC__stream_decoder_get_state(d
->decoder
) > FLAC__STREAM_DECODER_END_OF_STREAM
&& !d
->aborting_due_to_until
)
436 flac__utils_printf(stderr
, 2, "\n");
437 print_error_with_state(d
, "ERROR during decoding");
441 /* write padding bytes for alignment if necessary */
442 if(!d
->analysis_mode
&& !d
->test_only
&& d
->format
!= FORMAT_RAW
) {
443 const FLAC__uint64 data_size
= d
->total_samples
* d
->channels
* ((d
->bps
+7)/8);
445 if(d
->format
!= FORMAT_WAVE64
) {
446 padding
= (uint32_t)(data_size
& 1);
449 /* 8-byte alignment for Wave64 */
450 padding
= (8 - (uint32_t)(data_size
& 7)) & 7;
452 for( ; padding
> 0; --padding
) {
453 if(flac__utils_fwrite("\000", 1, 1, d
->fout
) != 1) {
454 print_error_with_state(
456 d
->format
== FORMAT_WAVE
? "ERROR writing pad byte to WAVE data chunk" :
457 d
->format
== FORMAT_WAVE64
? "ERROR writing pad bytes to WAVE64 data chunk" :
458 d
->format
== FORMAT_RF64
? "ERROR writing pad byte to RF64 data chunk" :
459 "ERROR writing pad byte to AIFF SSND chunk"
469 int DecoderSession_finish_ok(DecoderSession
*d
)
471 FLAC__bool ok
= true, md5_failure
= false;
474 md5_failure
= !FLAC__stream_decoder_finish(d
->decoder
) && !d
->aborting_due_to_until
;
476 FLAC__stream_decoder_delete(d
->decoder
);
479 flac__analyze_finish(d
->aopts
);
481 stats_print_name(1, d
->inbasefilename
);
482 flac__utils_printf(stderr
, 1, "ERROR, MD5 signature mismatch\n");
483 ok
= d
->continue_through_decode_errors
;
486 if(!d
->got_stream_info
) {
487 stats_print_name(1, d
->inbasefilename
);
488 flac__utils_printf(stderr
, 1, "WARNING, cannot check MD5 signature since there was no STREAMINFO\n");
489 ok
= !d
->treat_warnings_as_errors
;
491 else if(!d
->has_md5sum
) {
492 stats_print_name(1, d
->inbasefilename
);
493 flac__utils_printf(stderr
, 1, "WARNING, cannot check MD5 signature since it was unset in the STREAMINFO\n");
494 ok
= !d
->treat_warnings_as_errors
;
496 stats_print_name(2, d
->inbasefilename
);
497 flac__utils_printf(stderr
, 2, "%s \n", d
->test_only
? "ok ":d
->analysis_mode
?"done ":"done");
499 DecoderSession_destroy(d
, /*error_occurred=*/!ok
);
500 if(!d
->analysis_mode
&& !d
->test_only
&& d
->format
!= FORMAT_RAW
) {
501 if(d
->iff_headers_need_fixup
|| (!d
->got_stream_info
&& strcmp(d
->outfilename
, "-"))) {
502 if(!fixup_iff_headers(d
))
505 if(d
->foreign_metadata
) {
507 if(!flac__foreign_metadata_write_to_iff(d
->foreign_metadata
, d
->infilename
, d
->outfilename
, d
->fm_offset1
, d
->fm_offset2
, d
->fm_offset3
, &error
)) {
508 flac__utils_printf(stderr
, 1, "ERROR updating foreign metadata from %s to %s: %s\n", d
->infilename
, d
->outfilename
, error
);
516 int DecoderSession_finish_error(DecoderSession
*d
)
519 (void)FLAC__stream_decoder_finish(d
->decoder
);
520 FLAC__stream_decoder_delete(d
->decoder
);
523 flac__analyze_finish(d
->aopts
);
524 DecoderSession_destroy(d
, /*error_occurred=*/true);
528 FLAC__bool
canonicalize_until_specification(utils__SkipUntilSpecification
*spec
, const char *inbasefilename
, uint32_t sample_rate
, FLAC__uint64 skip
, FLAC__uint64 total_samples_in_input
)
530 /* convert from mm:ss.sss to sample number if necessary */
531 flac__utils_canonicalize_skip_until_specification(spec
, sample_rate
);
533 /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
534 if(spec
->is_relative
&& spec
->value
.samples
== 0) {
535 spec
->is_relative
= false;
539 /* in any other case the total samples in the input must be known */
540 if(total_samples_in_input
== 0) {
541 flac__utils_printf(stderr
, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename
);
545 FLAC__ASSERT(spec
->value_is_samples
);
547 /* convert relative specifications to absolute */
548 if(spec
->is_relative
) {
549 if(spec
->value
.samples
<= 0)
550 spec
->value
.samples
+= (FLAC__int64
)total_samples_in_input
;
552 spec
->value
.samples
+= skip
;
553 spec
->is_relative
= false;
557 if(spec
->value
.samples
< 0) {
558 flac__utils_printf(stderr
, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename
);
561 if((FLAC__uint64
)spec
->value
.samples
<= skip
) {
562 flac__utils_printf(stderr
, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename
);
565 if((FLAC__uint64
)spec
->value
.samples
> total_samples_in_input
) {
566 flac__utils_printf(stderr
, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename
);
573 FLAC__bool
write_iff_headers(FILE *f
, DecoderSession
*decoder_session
, FLAC__uint64 samples
)
575 const FileFormat format
= decoder_session
->format
;
576 const char *fmt_desc
=
577 format
==FORMAT_WAVE
? "WAVE" :
578 format
==FORMAT_WAVE64
? "Wave64" :
579 format
==FORMAT_RF64
? "RF64" :
581 const FLAC__bool is_waveformatextensible
=
582 (format
== FORMAT_WAVE
|| format
== FORMAT_WAVE64
|| format
== FORMAT_RF64
) &&
584 (decoder_session
->channel_mask
!= 0 && decoder_session
->channel_mask
!= 0x0004 && decoder_session
->channel_mask
!= 0x0003) ||
585 (decoder_session
->bps
!= 8 && decoder_session
->bps
!= 16) ||
586 decoder_session
->channels
> 2
588 const FLAC__uint64 data_size
= samples
* decoder_session
->channels
* ((decoder_session
->bps
+7)/8);
589 const FLAC__uint64 aligned_data_size
=
590 format
== FORMAT_WAVE64
?
591 (data_size
+7) & (~(FLAC__uint64
)7) :
592 (data_size
+1) & (~(FLAC__uint64
)1);
594 FLAC__uint64 iff_size
;
595 uint32_t foreign_metadata_size
= 0; /* size of all non-audio non-fmt/COMM foreign metadata chunks */
596 foreign_metadata_t
*fm
= decoder_session
->foreign_metadata
;
600 format
== FORMAT_WAVE
||
601 format
== FORMAT_WAVE64
||
602 format
== FORMAT_RF64
||
603 format
== FORMAT_AIFF
||
604 format
== FORMAT_AIFF_C
609 flac__utils_printf(stderr
, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session
->inbasefilename
, fmt_desc
);
610 flac__utils_printf(stderr
, 1, " Generated %s file will have a data chunk size of 0. Try\n", fmt_desc
);
611 flac__utils_printf(stderr
, 1, " decoding directly to a file instead.\n");
612 if(decoder_session
->treat_warnings_as_errors
)
616 decoder_session
->iff_headers_need_fixup
= true;
621 FLAC__ASSERT(fm
->format_block
);
622 FLAC__ASSERT(fm
->audio_block
);
623 FLAC__ASSERT(fm
->format_block
< fm
->audio_block
);
624 /* calc foreign metadata size; we always skip the first chunk, ds64 chunk, format chunk, and sound chunk since we write our own */
625 for(i
= format
==FORMAT_RF64
?2:1; i
< fm
->num_blocks
; i
++) {
626 if(i
!= fm
->format_block
&& i
!= fm
->audio_block
)
627 foreign_metadata_size
+= fm
->blocks
[i
].size
;
633 else if(format
== FORMAT_WAVE
|| format
== FORMAT_RF64
)
634 /* 4 for WAVE form bytes */
635 /* +{36,0} for ds64 chunk */
636 /* +8+{40,16} for fmt chunk header and body */
637 /* +8 for data chunk header */
638 iff_size
= 4 + (format
==FORMAT_RF64
?36:0) + 8+(is_waveformatextensible
?40:16) + 8 + foreign_metadata_size
+ aligned_data_size
;
639 else if(format
== FORMAT_WAVE64
)
640 /* 16+8 for RIFF GUID and size field */
641 /* +16 for WAVE GUID */
642 /* +16+8+{40,16} for fmt chunk header (GUID and size field) and body */
643 /* +16+8 for data chunk header (GUID and size field) */
644 iff_size
= 16+8 + 16 + 16+8+(is_waveformatextensible
?40:16) + 16+8 + foreign_metadata_size
+ aligned_data_size
;
646 iff_size
= 46 + foreign_metadata_size
+ aligned_data_size
;
648 if(format
!= FORMAT_WAVE64
&& format
!= FORMAT_RF64
&& iff_size
>= 0xFFFFFFF4) {
649 flac__utils_printf(stderr
, 1, "%s: ERROR: stream is too big to fit in a single %s file\n", decoder_session
->inbasefilename
, fmt_desc
);
653 if(format
== FORMAT_WAVE
|| format
== FORMAT_WAVE64
|| format
== FORMAT_RF64
) {
657 if(flac__utils_fwrite("RIFF", 1, 4, f
) != 4)
659 if(!write_little_endian_uint32(f
, (FLAC__uint32
)iff_size
)) /* filesize-8 */
661 if(flac__utils_fwrite("WAVE", 1, 4, f
) != 4)
665 /* RIFF GUID 66666972-912E-11CF-A5D6-28DB04C10000 */
666 if(flac__utils_fwrite("\x72\x69\x66\x66\x2E\x91\xCF\x11\xA5\xD6\x28\xDB\x04\xC1\x00\x00", 1, 16, f
) != 16)
668 if(!write_little_endian_uint64(f
, iff_size
))
670 /* WAVE GUID 65766177-ACF3-11D3-8CD1-00C04F8EDB8A */
671 if(flac__utils_fwrite("\x77\x61\x76\x65\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f
) != 16)
675 if(flac__utils_fwrite("RF64", 1, 4, f
) != 4)
677 if(!write_little_endian_uint32(f
, 0xffffffff))
679 if(flac__utils_fwrite("WAVE", 1, 4, f
) != 4)
686 /* ds64 chunk for RF64 */
687 if(format
== FORMAT_RF64
) {
688 if(flac__utils_fwrite("ds64", 1, 4, f
) != 4)
691 if(!write_little_endian_uint32(f
, 28)) /* chunk size */
694 if(!write_little_endian_uint64(f
, iff_size
))
697 if(!write_little_endian_uint64(f
, data_size
))
700 if(!write_little_endian_uint64(f
, samples
)) /*@@@@@@ correct? */
703 if(!write_little_endian_uint32(f
, 0)) /* table size */
707 decoder_session
->fm_offset1
= ftello(f
);
710 /* seek forward to {allocate} or {skip over already-written chunks} before "fmt " */
711 for(i
= format
==FORMAT_RF64
?2:1; i
< fm
->format_block
; i
++) {
712 if(fseeko(f
, fm
->blocks
[i
].size
, SEEK_CUR
) < 0) {
713 flac__utils_printf(stderr
, 1, "%s: ERROR: allocating/skipping foreign metadata before \"fmt \"\n", decoder_session
->inbasefilename
);
719 if(format
!= FORMAT_WAVE64
) {
720 if(flac__utils_fwrite("fmt ", 1, 4, f
) != 4)
722 if(!write_little_endian_uint32(f
, is_waveformatextensible
? 40 : 16)) /* chunk size */
726 /* fmt GUID 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A */
727 if(flac__utils_fwrite("\x66\x6D\x74\x20\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f
) != 16)
729 /* chunk size (+16+8 for GUID and size fields) */
730 if(!write_little_endian_uint64(f
, 16+8+(is_waveformatextensible
?40:16)))
734 if(!write_riff_wave_fmt_chunk_body(f
, is_waveformatextensible
, decoder_session
->bps
, decoder_session
->channels
, decoder_session
->sample_rate
, decoder_session
->channel_mask
))
737 decoder_session
->fm_offset2
= ftello(f
);
740 /* seek forward to {allocate} or {skip over already-written chunks} after "fmt " but before "data" */
741 for(i
= fm
->format_block
+1; i
< fm
->audio_block
; i
++) {
742 if(fseeko(f
, fm
->blocks
[i
].size
, SEEK_CUR
) < 0) {
743 flac__utils_printf(stderr
, 1, "%s: ERROR: allocating/skipping foreign metadata after \"fmt \"\n", decoder_session
->inbasefilename
);
749 if(format
!= FORMAT_WAVE64
) {
750 if(flac__utils_fwrite("data", 1, 4, f
) != 4)
752 if(!write_little_endian_uint32(f
, format
==FORMAT_RF64
? 0xffffffff : (FLAC__uint32
)data_size
))
756 /* data GUID 61746164-ACF3-11D3-8CD1-00C04F8EDB8A */
757 if(flac__utils_fwrite("\x64\x61\x74\x61\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 1, 16, f
) != 16)
759 /* +16+8 for GUID and size fields */
760 if(!write_little_endian_uint64(f
, 16+8 + data_size
))
764 decoder_session
->fm_offset3
= ftello(f
) + aligned_data_size
;
767 if(flac__utils_fwrite("FORM", 1, 4, f
) != 4)
770 if(!write_big_endian_uint32(f
, (FLAC__uint32
)iff_size
)) /* filesize-8 */
773 if(flac__utils_fwrite("AIFF", 1, 4, f
) != 4)
776 decoder_session
->fm_offset1
= ftello(f
);
779 /* seek forward to {allocate} or {skip over already-written chunks} before "COMM" */
780 for(i
= 1; i
< fm
->format_block
; i
++) {
781 if(fseeko(f
, fm
->blocks
[i
].size
, SEEK_CUR
) < 0) {
782 flac__utils_printf(stderr
, 1, "%s: ERROR: allocating/skipping foreign metadata before \"COMM\"\n", decoder_session
->inbasefilename
);
788 if(!write_aiff_form_comm_chunk(f
, samples
, decoder_session
->bps
, decoder_session
->channels
, decoder_session
->sample_rate
))
791 decoder_session
->fm_offset2
= ftello(f
);
794 /* seek forward to {allocate} or {skip over already-written chunks} after "COMM" but before "SSND" */
795 for(i
= fm
->format_block
+1; i
< fm
->audio_block
; i
++) {
796 if(fseeko(f
, fm
->blocks
[i
].size
, SEEK_CUR
) < 0) {
797 flac__utils_printf(stderr
, 1, "%s: ERROR: allocating/skipping foreign metadata after \"COMM\"\n", decoder_session
->inbasefilename
);
803 if(flac__utils_fwrite("SSND", 1, 4, f
) != 4)
806 if(!write_big_endian_uint32(f
, (FLAC__uint32
)data_size
+ 8)) /* data size */
809 if(!write_big_endian_uint32(f
, 0/*offset_size*/))
812 if(!write_big_endian_uint32(f
, 0/*block_size*/))
815 decoder_session
->fm_offset3
= ftello(f
) + aligned_data_size
;
821 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
)
823 if(!write_little_endian_uint16(f
, (FLAC__uint16
)(is_waveformatextensible
? 65534 : 1))) /* compression code */
826 if(!write_little_endian_uint16(f
, (FLAC__uint16
)channels
))
829 if(!write_little_endian_uint32(f
, sample_rate
))
832 if(!write_little_endian_uint32(f
, sample_rate
* channels
* ((bps
+7) / 8)))
835 if(!write_little_endian_uint16(f
, (FLAC__uint16
)(channels
* ((bps
+7) / 8)))) /* block align */
838 if(!write_little_endian_uint16(f
, (FLAC__uint16
)(((bps
+7)/8)*8))) /* bits per sample */
841 if(is_waveformatextensible
) {
842 if(!write_little_endian_uint16(f
, (FLAC__uint16
)22)) /* cbSize */
845 if(!write_little_endian_uint16(f
, (FLAC__uint16
)bps
)) /* validBitsPerSample */
848 if(!write_little_endian_uint32(f
, channel_mask
))
851 /* GUID = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}} */
852 if(flac__utils_fwrite("\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71", 1, 16, f
) != 16)
859 FLAC__bool
write_aiff_form_comm_chunk(FILE *f
, FLAC__uint64 samples
, uint32_t bps
, uint32_t channels
, uint32_t sample_rate
)
861 FLAC__ASSERT(samples
<= 0xffffffff);
863 if(flac__utils_fwrite("COMM", 1, 4, f
) != 4)
866 if(!write_big_endian_uint32(f
, 18)) /* chunk size = 18 */
869 if(!write_big_endian_uint16(f
, (FLAC__uint16
)channels
))
872 if(!write_big_endian_uint32(f
, (FLAC__uint32
)samples
))
875 if(!write_big_endian_uint16(f
, (FLAC__uint16
)bps
))
878 if(!write_sane_extended(f
, sample_rate
))
884 FLAC__bool
write_little_endian_uint16(FILE *f
, FLAC__uint16 val
)
886 FLAC__byte
*b
= (FLAC__byte
*)(&val
);
887 if(is_big_endian_host_
) {
889 tmp
= b
[1]; b
[1] = b
[0]; b
[0] = tmp
;
891 return flac__utils_fwrite(b
, 1, 2, f
) == 2;
894 FLAC__bool
write_little_endian_uint32(FILE *f
, FLAC__uint32 val
)
896 FLAC__byte
*b
= (FLAC__byte
*)(&val
);
897 if(is_big_endian_host_
) {
899 tmp
= b
[3]; b
[3] = b
[0]; b
[0] = tmp
;
900 tmp
= b
[2]; b
[2] = b
[1]; b
[1] = tmp
;
902 return flac__utils_fwrite(b
, 1, 4, f
) == 4;
905 FLAC__bool
write_little_endian_uint64(FILE *f
, FLAC__uint64 val
)
907 FLAC__byte
*b
= (FLAC__byte
*)(&val
);
908 if(is_big_endian_host_
) {
910 tmp
= b
[7]; b
[7] = b
[0]; b
[0] = tmp
;
911 tmp
= b
[6]; b
[6] = b
[1]; b
[1] = tmp
;
912 tmp
= b
[5]; b
[5] = b
[2]; b
[2] = tmp
;
913 tmp
= b
[4]; b
[4] = b
[3]; b
[3] = tmp
;
915 return flac__utils_fwrite(b
, 1, 8, f
) == 8;
918 FLAC__bool
write_big_endian_uint16(FILE *f
, FLAC__uint16 val
)
920 FLAC__byte
*b
= (FLAC__byte
*)(&val
);
921 if(!is_big_endian_host_
) {
923 tmp
= b
[1]; b
[1] = b
[0]; b
[0] = tmp
;
925 return flac__utils_fwrite(b
, 1, 2, f
) == 2;
928 FLAC__bool
write_big_endian_uint32(FILE *f
, FLAC__uint32 val
)
930 FLAC__byte
*b
= (FLAC__byte
*)(&val
);
931 if(!is_big_endian_host_
) {
933 tmp
= b
[3]; b
[3] = b
[0]; b
[0] = tmp
;
934 tmp
= b
[2]; b
[2] = b
[1]; b
[1] = tmp
;
936 return flac__utils_fwrite(b
, 1, 4, f
) == 4;
939 FLAC__bool
write_sane_extended(FILE *f
, uint32_t val
)
940 /* Write to 'f' a SANE extended representation of 'val'. Return false if
941 * the write succeeds; return true otherwise.
943 * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
944 * of exponent, and 64 bits of significand (mantissa). Unlike most IEEE-754
945 * representations, it does not imply a 1 above the MSB of the significand.
951 uint32_t shift
, exponent
;
953 FLAC__ASSERT(val
!=0U); /* handling 0 would require a special case */
955 for(shift
= 0U; (val
>>(31-shift
))==0U; ++shift
)
958 exponent
= 63U-(shift
+32U); /* add 32 for unused second word */
960 if(!write_big_endian_uint16(f
, (FLAC__uint16
)(exponent
+0x3FFF)))
962 if(!write_big_endian_uint32(f
, val
))
964 if(!write_big_endian_uint32(f
, 0)) /* unused second word */
970 FLAC__bool
fixup_iff_headers(DecoderSession
*d
)
972 const char *fmt_desc
=
973 d
->format
==FORMAT_WAVE
? "WAVE" :
974 d
->format
==FORMAT_WAVE64
? "Wave64" :
975 d
->format
==FORMAT_RF64
? "RF64" :
977 FILE *f
= flac_fopen(d
->outfilename
, "r+b"); /* stream is positioned at beginning of file */
980 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
));
984 if(!write_iff_headers(f
, d
, d
->samples_processed
)) {
993 FLAC__StreamDecoderWriteStatus
write_callback(const FLAC__StreamDecoder
*decoder
, const FLAC__Frame
*frame
, const FLAC__int32
* const buffer
[], void *client_data
)
995 DecoderSession
*decoder_session
= (DecoderSession
*)client_data
;
996 FILE *fout
= decoder_session
->fout
;
997 const uint32_t bps
= frame
->header
.bits_per_sample
, channels
= frame
->header
.channels
;
998 const uint32_t shift
= (decoder_session
->format
!= FORMAT_RAW
&& (bps
%8))? 8-(bps
%8): 0;
999 FLAC__bool is_big_endian
= (
1000 decoder_session
->format
== FORMAT_AIFF
|| decoder_session
->format
== FORMAT_AIFF_C
? true : (
1001 decoder_session
->format
== FORMAT_WAVE
|| decoder_session
->format
== FORMAT_WAVE64
|| decoder_session
->format
== FORMAT_RF64
? false :
1002 decoder_session
->is_big_endian
1004 FLAC__bool is_unsigned_samples
= (
1005 decoder_session
->format
== FORMAT_AIFF
|| decoder_session
->format
== FORMAT_AIFF_C
? false : (
1006 decoder_session
->format
== FORMAT_WAVE
|| decoder_session
->format
== FORMAT_WAVE64
|| decoder_session
->format
== FORMAT_RF64
? bps
<=8 :
1007 decoder_session
->is_unsigned_samples
1009 uint32_t wide_samples
= frame
->header
.blocksize
, wide_sample
, sample
, channel
;
1010 uint32_t frame_bytes
= 0;
1013 { /* The arrays defined within this union are all the same size. */
1014 FLAC__int8 s8buffer
[FLAC__MAX_BLOCK_SIZE
* FLAC__MAX_CHANNELS
* sizeof(FLAC__int32
)]; /* WATCHOUT: can be up to 2 megs */
1015 FLAC__uint8 u8buffer
[FLAC__MAX_BLOCK_SIZE
* FLAC__MAX_CHANNELS
* sizeof(FLAC__int32
)];
1016 FLAC__int16 s16buffer
[FLAC__MAX_BLOCK_SIZE
* FLAC__MAX_CHANNELS
* sizeof(FLAC__int16
)];
1017 FLAC__uint16 u16buffer
[FLAC__MAX_BLOCK_SIZE
* FLAC__MAX_CHANNELS
* sizeof(FLAC__int16
)];
1018 FLAC__int32 s32buffer
[FLAC__MAX_BLOCK_SIZE
* FLAC__MAX_CHANNELS
];
1019 FLAC__uint32 u32buffer
[FLAC__MAX_BLOCK_SIZE
* FLAC__MAX_CHANNELS
];
1022 size_t bytes_to_write
= 0;
1026 if(decoder_session
->abort_flag
)
1027 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
;
1029 /* sanity-check the bits-per-sample */
1030 if(decoder_session
->bps
) {
1031 if(bps
!= decoder_session
->bps
) {
1032 if(decoder_session
->got_stream_info
)
1033 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
);
1035 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
);
1036 if(!decoder_session
->continue_through_decode_errors
)
1037 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
;
1041 /* must not have gotten STREAMINFO, save the bps from the frame header */
1042 FLAC__ASSERT(!decoder_session
->got_stream_info
);
1043 decoder_session
->bps
= bps
;
1046 /* sanity-check the #channels */
1047 if(decoder_session
->channels
) {
1048 if(channels
!= decoder_session
->channels
) {
1049 if(decoder_session
->got_stream_info
)
1050 flac__utils_printf(stderr
, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session
->inbasefilename
, channels
, decoder_session
->channels
);
1052 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
);
1053 if(!decoder_session
->continue_through_decode_errors
)
1054 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
;
1058 /* must not have gotten STREAMINFO, save the #channels from the frame header */
1059 FLAC__ASSERT(!decoder_session
->got_stream_info
);
1060 decoder_session
->channels
= channels
;
1063 /* sanity-check the sample rate */
1064 if(decoder_session
->sample_rate
) {
1065 if(frame
->header
.sample_rate
!= decoder_session
->sample_rate
) {
1066 if(decoder_session
->got_stream_info
)
1067 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
);
1069 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
);
1070 if(!decoder_session
->continue_through_decode_errors
)
1071 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
;
1075 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
1076 FLAC__ASSERT(!decoder_session
->got_stream_info
);
1077 decoder_session
->sample_rate
= frame
->header
.sample_rate
;
1081 * limit the number of samples to accept based on --until
1083 FLAC__ASSERT(!decoder_session
->skip_specification
->is_relative
);
1084 /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
1085 if(decoder_session
->skip_specification
->is_relative
) {
1086 if(decoder_session
->skip_specification
->value
.samples
== 0) /* special case for when no --skip was given */
1087 decoder_session
->skip_specification
->is_relative
= false; /* convert to our meaning of beginning-of-stream */
1089 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
);
1090 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
;
1093 if(decoder_session
->until_specification
->is_relative
) {
1094 if(decoder_session
->until_specification
->value
.samples
== 0) /* special case for when no --until was given */
1095 decoder_session
->until_specification
->is_relative
= false; /* convert to our meaning of end-of-stream */
1097 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
);
1098 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
;
1101 FLAC__ASSERT(decoder_session
->skip_specification
->value
.samples
>= 0);
1102 FLAC__ASSERT(decoder_session
->until_specification
->value
.samples
>= 0);
1103 if(decoder_session
->until_specification
->value
.samples
> 0) {
1104 const FLAC__uint64 skip
= (FLAC__uint64
)decoder_session
->skip_specification
->value
.samples
;
1105 const FLAC__uint64 until
= (FLAC__uint64
)decoder_session
->until_specification
->value
.samples
;
1106 const FLAC__uint64 input_samples_passed
= skip
+ decoder_session
->samples_processed
;
1107 FLAC__ASSERT(until
>= input_samples_passed
);
1108 if(input_samples_passed
+ wide_samples
> until
)
1109 wide_samples
= (uint32_t)(until
- input_samples_passed
);
1110 if (wide_samples
== 0) {
1111 decoder_session
->abort_flag
= true;
1112 decoder_session
->aborting_due_to_until
= true;
1113 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
;
1117 if(decoder_session
->analysis_mode
) {
1119 FLAC__stream_decoder_get_decode_position(decoder_session
->decoder
, &dpos
);
1120 frame_bytes
= (uint32_t)(dpos
-decoder_session
->decode_position
);
1121 decoder_session
->decode_position
= dpos
;
1124 if(wide_samples
> 0) {
1125 decoder_session
->samples_processed
+= wide_samples
;
1126 decoder_session
->frame_counter
++;
1128 if(!(decoder_session
->frame_counter
& 0x1ff))
1129 print_stats(decoder_session
);
1131 if(decoder_session
->analysis_mode
) {
1132 flac__analyze_frame(frame
, decoder_session
->frame_counter
-1, decoder_session
->decode_position
-frame_bytes
, frame_bytes
, decoder_session
->aopts
, fout
);
1134 else if(!decoder_session
->test_only
) {
1135 if(shift
&& !decoder_session
->replaygain
.apply
) {
1136 for(wide_sample
= 0; wide_sample
< wide_samples
; wide_sample
++)
1137 for(channel
= 0; channel
< channels
; channel
++)
1138 ((uint32_t **)buffer
)[channel
][wide_sample
] <<= shift
;/*@@@@@@un-const'ing the buffer is hacky but safe*/
1140 if(decoder_session
->replaygain
.apply
) {
1141 bytes_to_write
= FLAC__replaygain_synthesis__apply_gain(
1144 is_unsigned_samples
,
1148 bps
, /* source_bps */
1149 bps
+shift
, /* target_bps */
1150 decoder_session
->replaygain
.scale
,
1151 decoder_session
->replaygain
.spec
.limiter
== RGSS_LIMIT__HARD
, /* hard_limit */
1152 decoder_session
->replaygain
.spec
.noise_shaping
!= NOISE_SHAPING_NONE
, /* do_dithering */
1153 &decoder_session
->replaygain
.dither_context
1156 /* first some special code for common cases */
1157 else if(is_big_endian
== is_big_endian_host_
&& !is_unsigned_samples
&& channels
== 2 && bps
+shift
== 16) {
1158 FLAC__int16
*buf1_
= ubuf
.s16buffer
+ 1;
1160 memcpy(ubuf
.s16buffer
, ((FLAC__byte
*)(buffer
[0]))+2, sizeof(FLAC__int32
) * wide_samples
- 2);
1162 memcpy(ubuf
.s16buffer
, buffer
[0], sizeof(FLAC__int32
) * wide_samples
);
1163 for(sample
= 0; sample
< wide_samples
; sample
++, buf1_
+=2)
1164 *buf1_
= (FLAC__int16
)buffer
[1][sample
];
1165 bytes_to_write
= 4 * sample
;
1167 else if(is_big_endian
== is_big_endian_host_
&& !is_unsigned_samples
&& channels
== 1 && bps
+shift
== 16) {
1168 FLAC__int16
*buf1_
= ubuf
.s16buffer
;
1169 for(sample
= 0; sample
< wide_samples
; sample
++)
1170 *buf1_
++ = (FLAC__int16
)buffer
[0][sample
];
1171 bytes_to_write
= 2 * sample
;
1173 /* generic code for the rest */
1174 else if(bps
+shift
== 16) {
1175 if(is_unsigned_samples
) {
1177 for(sample
= wide_sample
= 0; wide_sample
< wide_samples
; wide_sample
++) {
1178 ubuf
.u16buffer
[sample
++] = (FLAC__uint16
)(buffer
[0][wide_sample
] + 0x8000);
1179 ubuf
.u16buffer
[sample
++] = (FLAC__uint16
)(buffer
[1][wide_sample
] + 0x8000);
1182 else if(channels
== 1) {
1183 for(sample
= wide_sample
= 0; wide_sample
< wide_samples
; wide_sample
++)
1184 ubuf
.u16buffer
[sample
++] = (FLAC__uint16
)(buffer
[0][wide_sample
] + 0x8000);
1186 else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1187 for(sample
= wide_sample
= 0; wide_sample
< wide_samples
; wide_sample
++)
1188 for(channel
= 0; channel
< channels
; channel
++, sample
++)
1189 ubuf
.u16buffer
[sample
] = (FLAC__uint16
)(buffer
[channel
][wide_sample
] + 0x8000);
1194 for(sample
= wide_sample
= 0; wide_sample
< wide_samples
; wide_sample
++) {
1195 ubuf
.s16buffer
[sample
++] = (FLAC__int16
)(buffer
[0][wide_sample
]);
1196 ubuf
.s16buffer
[sample
++] = (FLAC__int16
)(buffer
[1][wide_sample
]);
1199 else if(channels
== 1) {
1200 for(sample
= wide_sample
= 0; wide_sample
< wide_samples
; wide_sample
++)
1201 ubuf
.s16buffer
[sample
++] = (FLAC__int16
)(buffer
[0][wide_sample
]);
1203 else { /* works for any 'channels' but above flavors are faster for 1 and 2 */
1204 for(sample
= wide_sample
= 0; wide_sample
< wide_samples
; wide_sample
++)
1205 for(channel
= 0; channel
< channels
; channel
++, sample
++)
1206 ubuf
.s16buffer
[sample
] = (FLAC__int16
)(buffer
[channel
][wide_sample
]);
1209 if(is_big_endian
!= is_big_endian_host_
) {
1211 const uint32_t bytes
= sample
* 2;
1213 for(b
= 0; b
< bytes
; b
+= 2) {
1214 tmp
= ubuf
.u8buffer
[b
];
1215 ubuf
.u8buffer
[b
] = ubuf
.u8buffer
[b
+1];
1216 ubuf
.u8buffer
[b
+1] = tmp
;
1219 bytes_to_write
= 2 * sample
;
1221 else if(bps
+shift
== 24) {
1222 if(is_unsigned_samples
) {
1223 for(sample
= wide_sample
= 0; wide_sample
< wide_samples
; wide_sample
++)
1224 for(channel
= 0; channel
< channels
; channel
++, sample
++)
1225 ubuf
.u32buffer
[sample
] = buffer
[channel
][wide_sample
] + 0x800000;
1228 for(sample
= wide_sample
= 0; wide_sample
< wide_samples
; wide_sample
++)
1229 for(channel
= 0; channel
< channels
; channel
++, sample
++)
1230 ubuf
.s32buffer
[sample
] = buffer
[channel
][wide_sample
];
1232 if(is_big_endian
!= is_big_endian_host_
) {
1234 const uint32_t bytes
= sample
* 4;
1236 for(b
= 0; b
< bytes
; b
+= 4) {
1237 tmp
= ubuf
.u8buffer
[b
];
1238 ubuf
.u8buffer
[b
] = ubuf
.u8buffer
[b
+3];
1239 ubuf
.u8buffer
[b
+3] = tmp
;
1240 tmp
= ubuf
.u8buffer
[b
+1];
1241 ubuf
.u8buffer
[b
+1] = ubuf
.u8buffer
[b
+2];
1242 ubuf
.u8buffer
[b
+2] = tmp
;
1247 const uint32_t bytes
= sample
* 4;
1248 for(lbyte
= b
= 0; b
< bytes
; ) {
1250 ubuf
.u8buffer
[lbyte
++] = ubuf
.u8buffer
[b
++];
1251 ubuf
.u8buffer
[lbyte
++] = ubuf
.u8buffer
[b
++];
1252 ubuf
.u8buffer
[lbyte
++] = ubuf
.u8buffer
[b
++];
1257 const uint32_t bytes
= sample
* 4;
1258 for(lbyte
= b
= 0; b
< bytes
; ) {
1259 ubuf
.u8buffer
[lbyte
++] = ubuf
.u8buffer
[b
++];
1260 ubuf
.u8buffer
[lbyte
++] = ubuf
.u8buffer
[b
++];
1261 ubuf
.u8buffer
[lbyte
++] = ubuf
.u8buffer
[b
++];
1265 bytes_to_write
= 3 * sample
;
1267 else if(bps
+shift
== 8) {
1268 if(is_unsigned_samples
) {
1269 for(sample
= wide_sample
= 0; wide_sample
< wide_samples
; wide_sample
++)
1270 for(channel
= 0; channel
< channels
; channel
++, sample
++)
1271 ubuf
.u8buffer
[sample
] = (FLAC__uint8
)(buffer
[channel
][wide_sample
] + 0x80);
1274 for(sample
= wide_sample
= 0; wide_sample
< wide_samples
; wide_sample
++)
1275 for(channel
= 0; channel
< channels
; channel
++, sample
++)
1276 ubuf
.s8buffer
[sample
] = (FLAC__int8
)(buffer
[channel
][wide_sample
]);
1278 bytes_to_write
= sample
;
1282 /* double protection */
1283 decoder_session
->abort_flag
= true;
1284 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
;
1288 if(bytes_to_write
> 0) {
1289 if(flac__utils_fwrite(ubuf
.u8buffer
, 1, bytes_to_write
, fout
) != bytes_to_write
) {
1290 /* if a pipe closed when writing to stdout, we let it go without an error message */
1291 if(errno
== EPIPE
&& decoder_session
->fout
== stdout
)
1292 decoder_session
->aborting_due_to_until
= true;
1293 decoder_session
->abort_flag
= true;
1294 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
;
1297 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE
;
1300 void metadata_callback(const FLAC__StreamDecoder
*decoder
, const FLAC__StreamMetadata
*metadata
, void *client_data
)
1302 DecoderSession
*decoder_session
= (DecoderSession
*)client_data
;
1304 if(decoder_session
->analysis_mode
)
1305 FLAC__stream_decoder_get_decode_position(decoder
, &decoder_session
->decode_position
);
1307 if(metadata
->type
== FLAC__METADATA_TYPE_STREAMINFO
) {
1308 FLAC__uint64 skip
, until
;
1309 decoder_session
->got_stream_info
= true;
1310 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);
1311 decoder_session
->bps
= metadata
->data
.stream_info
.bits_per_sample
;
1312 decoder_session
->channels
= metadata
->data
.stream_info
.channels
;
1313 decoder_session
->sample_rate
= metadata
->data
.stream_info
.sample_rate
;
1315 flac__utils_canonicalize_skip_until_specification(decoder_session
->skip_specification
, decoder_session
->sample_rate
);
1316 FLAC__ASSERT(decoder_session
->skip_specification
->value
.samples
>= 0);
1317 skip
= (FLAC__uint64
)decoder_session
->skip_specification
->value
.samples
;
1319 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1320 if(metadata
->data
.stream_info
.total_samples
> 0 && skip
>= metadata
->data
.stream_info
.total_samples
) {
1321 flac__utils_printf(stderr
, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session
->inbasefilename
);
1322 decoder_session
->abort_flag
= true;
1325 else if(metadata
->data
.stream_info
.total_samples
== 0 && skip
> 0) {
1326 flac__utils_printf(stderr
, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session
->inbasefilename
);
1327 decoder_session
->abort_flag
= true;
1330 FLAC__ASSERT(skip
== 0 || 0 == decoder_session
->cue_specification
);
1331 decoder_session
->total_samples
= metadata
->data
.stream_info
.total_samples
- skip
;
1333 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1334 if(!canonicalize_until_specification(decoder_session
->until_specification
, decoder_session
->inbasefilename
, decoder_session
->sample_rate
, skip
, metadata
->data
.stream_info
.total_samples
)) {
1335 decoder_session
->abort_flag
= true;
1338 FLAC__ASSERT(decoder_session
->until_specification
->value
.samples
>= 0);
1339 until
= (FLAC__uint64
)decoder_session
->until_specification
->value
.samples
;
1342 FLAC__ASSERT(decoder_session
->total_samples
!= 0);
1343 FLAC__ASSERT(0 == decoder_session
->cue_specification
);
1344 decoder_session
->total_samples
-= (metadata
->data
.stream_info
.total_samples
- until
);
1347 if(decoder_session
->format
== FORMAT_RAW
&& ((decoder_session
->bps
% 8) != 0 || decoder_session
->bps
< 4 || decoder_session
->bps
> 24)) {
1348 flac__utils_printf(stderr
, 1, "%s: ERROR: bits per sample is %u, must be 8/16/24 for raw format output\n", decoder_session
->inbasefilename
, decoder_session
->bps
);
1349 decoder_session
->abort_flag
= true;
1353 if(decoder_session
->bps
< 4 || decoder_session
->bps
> 24) {
1354 flac__utils_printf(stderr
, 1, "%s: ERROR: bits per sample is %u, must be 4-24\n", decoder_session
->inbasefilename
, decoder_session
->bps
);
1355 decoder_session
->abort_flag
= true;
1359 else if(metadata
->type
== FLAC__METADATA_TYPE_CUESHEET
) {
1360 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1361 if(decoder_session
->total_samples
== 0) {
1362 flac__utils_printf(stderr
, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session
->inbasefilename
);
1363 decoder_session
->abort_flag
= true;
1367 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
);
1369 FLAC__ASSERT(!decoder_session
->skip_specification
->is_relative
);
1370 FLAC__ASSERT(decoder_session
->skip_specification
->value_is_samples
);
1372 FLAC__ASSERT(!decoder_session
->until_specification
->is_relative
);
1373 FLAC__ASSERT(decoder_session
->until_specification
->value_is_samples
);
1375 FLAC__ASSERT(decoder_session
->skip_specification
->value
.samples
>= 0);
1376 FLAC__ASSERT(decoder_session
->until_specification
->value
.samples
>= 0);
1377 FLAC__ASSERT((FLAC__uint64
)decoder_session
->until_specification
->value
.samples
<= decoder_session
->total_samples
);
1378 FLAC__ASSERT(decoder_session
->skip_specification
->value
.samples
<= decoder_session
->until_specification
->value
.samples
);
1380 decoder_session
->total_samples
= decoder_session
->until_specification
->value
.samples
- decoder_session
->skip_specification
->value
.samples
;
1382 else if(metadata
->type
== FLAC__METADATA_TYPE_VORBIS_COMMENT
) {
1383 if (decoder_session
->replaygain
.spec
.apply
) {
1384 double reference
, gain
, peak
;
1385 if (!(decoder_session
->replaygain
.apply
= grabbag__replaygain_load_from_vorbiscomment(metadata
, decoder_session
->replaygain
.spec
.use_album_gain
, /*strict=*/false, &reference
, &gain
, &peak
))) {
1386 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");
1387 if(decoder_session
->treat_warnings_as_errors
) {
1388 decoder_session
->abort_flag
= true;
1393 const char *ls
[] = { "no", "peak", "hard" };
1394 const char *ns
[] = { "no", "low", "medium", "high" };
1395 decoder_session
->replaygain
.scale
= grabbag__replaygain_compute_scale_factor(peak
, gain
, decoder_session
->replaygain
.spec
.preamp
, decoder_session
->replaygain
.spec
.limiter
== RGSS_LIMIT__PEAK
);
1396 FLAC__ASSERT(decoder_session
->bps
> 0 && decoder_session
->bps
<= 32);
1397 FLAC__replaygain_synthesis__init_dither_context(&decoder_session
->replaygain
.dither_context
, decoder_session
->bps
, decoder_session
->replaygain
.spec
.noise_shaping
);
1398 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
]);
1399 flac__utils_printf(stderr
, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session
->inbasefilename
);
1400 /* don't check if(decoder_session->treat_warnings_as_errors) because the user explicitly asked for it */
1403 (void)flac__utils_get_channel_mask_tag(metadata
, &decoder_session
->channel_mask
);
1407 void error_callback(const FLAC__StreamDecoder
*decoder
, FLAC__StreamDecoderErrorStatus status
, void *client_data
)
1409 DecoderSession
*decoder_session
= (DecoderSession
*)client_data
;
1411 if(!decoder_session
->error_callback_suppress_messages
) {
1412 stats_print_name(1, decoder_session
->inbasefilename
);
1413 flac__utils_printf(stderr
, 1, "*** Got error code %d:%s\n", status
, FLAC__StreamDecoderErrorStatusString
[status
]);
1415 if(!decoder_session
->continue_through_decode_errors
) {
1416 /* if we got a sync error while looking for metadata, either it's not a FLAC file (more likely) or the file is corrupted */
1418 !decoder_session
->error_callback_suppress_messages
&&
1419 status
== FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC
&&
1420 FLAC__stream_decoder_get_state(decoder
) == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
1422 flac__utils_printf(stderr
, 1,
1424 "The input file is either not a FLAC file or is corrupted. If you are\n"
1425 "convinced it is a FLAC file, you can rerun the same command and add the\n"
1426 "-F parameter to try and recover as much as possible from the file.\n"
1428 decoder_session
->error_callback_suppress_messages
= true;
1430 else if(status
== FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
)
1431 decoder_session
->aborting_due_to_unparseable
= true;
1432 decoder_session
->abort_flag
= true;
1436 void print_error_with_init_status(const DecoderSession
*d
, const char *message
, FLAC__StreamDecoderInitStatus init_status
)
1438 const int ilen
= strlen(d
->inbasefilename
) + 1;
1440 flac__utils_printf(stderr
, 1, "\n%s: %s\n", d
->inbasefilename
, message
);
1442 flac__utils_printf(stderr
, 1, "%*s init status = %s\n", ilen
, "", FLAC__StreamDecoderInitStatusString
[init_status
]);
1444 /* print out some more info for some errors: */
1445 if (init_status
== FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE
) {
1446 flac__utils_printf(stderr
, 1,
1448 "An error occurred opening the input file; it is likely that it does not exist\n"
1449 "or is not readable.\n"
1454 void print_error_with_state(const DecoderSession
*d
, const char *message
)
1456 const int ilen
= strlen(d
->inbasefilename
) + 1;
1458 flac__utils_printf(stderr
, 1, "\n%s: %s\n", d
->inbasefilename
, message
);
1459 flac__utils_printf(stderr
, 1, "%*s state = %s\n", ilen
, "", FLAC__stream_decoder_get_resolved_state_string(d
->decoder
));
1461 /* print out some more info for some errors: */
1462 if (d
->aborting_due_to_unparseable
) {
1463 flac__utils_printf(stderr
, 1,
1465 "The FLAC stream may have been created by a more advanced encoder. Try\n"
1466 " metaflac --show-vendor-tag %s\n"
1467 "If the version number is greater than %s, this decoder is probably\n"
1468 "not able to decode the file. If the version number is not, the file\n"
1469 "may be corrupted, or you may have found a bug. In this case please\n"
1470 "submit a bug report to\n"
1471 " https://sourceforge.net/p/flac/bugs/\n"
1472 "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1473 d
->inbasefilename
, FLAC__VERSION_STRING
1478 void print_stats(const DecoderSession
*decoder_session
)
1480 if(flac__utils_verbosity_
>= 2) {
1481 const double progress
= (double)decoder_session
->samples_processed
/ (double)decoder_session
->total_samples
* 100.0;
1483 if(decoder_session
->total_samples
> 0) {
1484 if ((uint32_t)floor(progress
+ 0.5) == 100)
1487 stats_print_name(2, decoder_session
->inbasefilename
);
1488 stats_print_info(2, "%s%u%% complete",
1489 decoder_session
->test_only
? "testing, " : decoder_session
->analysis_mode
? "analyzing, " : "",
1490 (uint32_t)floor(progress
+ 0.5)
1494 stats_print_name(2, decoder_session
->inbasefilename
);
1495 stats_print_info(2, "%s %" PRIu64
" samples",
1496 decoder_session
->test_only
? "tested" : decoder_session
->analysis_mode
? "analyzed" : "wrote",
1497 decoder_session
->samples_processed