1 /* grabbag - Convenience lib for various routines common to several tools
2 * Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009 Josh Coalson
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #if defined _MSC_VER || defined __MINGW32__
29 #include <io.h> /* for chmod() */
31 #include <sys/stat.h> /* for stat(), maybe chmod() */
33 #include "FLAC/assert.h"
34 #include "FLAC/metadata.h"
35 #include "FLAC/stream_decoder.h"
36 #include "share/grabbag.h"
37 #include "share/replaygain_analysis.h"
38 #include "share/safe_str.h"
43 #define local_min(a,b) ((a)<(b)?(a):(b))
48 #define local_max(a,b) ((a)>(b)?(a):(b))
50 static const char *reference_format_ = "%s=%2.1f dB";
51 static const char *gain_format_ = "%s=%+2.2f dB";
52 static const char *peak_format_ = "%s=%1.8f";
54 static double album_peak_, title_peak_;
56 const unsigned GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED = 190;
58 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 29 + 1 + 8 +
59 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
60 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12 +
61 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
62 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12
65 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS = (const FLAC__byte * const)"REPLAYGAIN_REFERENCE_LOUDNESS";
66 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN = (const FLAC__byte * const)"REPLAYGAIN_TRACK_GAIN";
67 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK = (const FLAC__byte * const)"REPLAYGAIN_TRACK_PEAK";
68 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_GAIN";
69 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_PEAK";
72 static FLAC__bool get_file_stats_(const char *filename, struct stat *stats)
74 FLAC__ASSERT(0 != filename);
75 FLAC__ASSERT(0 != stats);
76 return (0 == stat(filename, stats));
79 static void set_file_stats_(const char *filename, struct stat *stats)
81 FLAC__ASSERT(0 != filename);
82 FLAC__ASSERT(0 != stats);
84 (void)chmod(filename, stats->st_mode);
87 static FLAC__bool append_tag_(FLAC__StreamMetadata *block, const char *format, const FLAC__byte *name, float value)
91 FLAC__StreamMetadata_VorbisComment_Entry entry;
93 FLAC__ASSERT(0 != block);
94 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
95 FLAC__ASSERT(0 != format);
96 FLAC__ASSERT(0 != name);
98 buffer[sizeof(buffer)-1] = '\0';
100 * We need to save the old locale and switch to "C" because the locale
101 * influences the formatting of %f and we want it a certain way.
103 saved_locale = strdup(setlocale(LC_ALL, 0));
104 if (0 == saved_locale)
106 setlocale(LC_ALL, "C");
107 flac_snprintf(buffer, sizeof(buffer), format, name, value);
108 setlocale(LC_ALL, saved_locale);
111 entry.entry = (FLAC__byte *)buffer;
112 entry.length = strlen(buffer);
114 return FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true);
117 FLAC__bool grabbag__replaygain_is_valid_sample_frequency(unsigned sample_frequency)
119 return ValidGainFrequency( sample_frequency );
122 FLAC__bool grabbag__replaygain_init(unsigned sample_frequency)
124 title_peak_ = album_peak_ = 0.0;
125 return InitGainAnalysis((long)sample_frequency) == INIT_GAIN_ANALYSIS_OK;
128 FLAC__bool grabbag__replaygain_analyze(const FLAC__int32 * const input[], FLAC__bool is_stereo, unsigned bps, unsigned samples)
130 /* using a small buffer improves data locality; we'd like it to fit easily in the dcache */
131 static Float_t lbuffer[2048], rbuffer[2048];
132 static const unsigned nbuffer = sizeof(lbuffer) / sizeof(lbuffer[0]);
133 FLAC__int32 block_peak = 0, s;
136 FLAC__ASSERT(bps >= 4 && bps <= FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE);
137 FLAC__ASSERT(FLAC__MIN_BITS_PER_SAMPLE == 4);
139 * We use abs() on a FLAC__int32 which is undefined for the most negative value.
140 * If the reference codec ever handles 32bps we will have to write a special
143 FLAC__ASSERT(FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE < 32);
149 const unsigned n = local_min(samples, nbuffer);
150 for(i = 0; i < n; i++, j++) {
152 lbuffer[i] = (Float_t)s;
154 block_peak = local_max(block_peak, s);
157 rbuffer[i] = (Float_t)s;
159 block_peak = local_max(block_peak, s);
162 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
169 const unsigned n = local_min(samples, nbuffer);
170 for(i = 0; i < n; i++, j++) {
172 lbuffer[i] = (Float_t)s;
174 block_peak = local_max(block_peak, s);
177 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
182 else { /* bps must be < 32 according to above assertion */
183 const double scale = (
185 (double)1. / (double)(1u << (bps - 16)) :
186 (double)(1u << (16 - bps))
192 const unsigned n = local_min(samples, nbuffer);
193 for(i = 0; i < n; i++, j++) {
195 lbuffer[i] = (Float_t)(scale * (double)s);
197 block_peak = local_max(block_peak, s);
200 rbuffer[i] = (Float_t)(scale * (double)s);
202 block_peak = local_max(block_peak, s);
205 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
212 const unsigned n = local_min(samples, nbuffer);
213 for(i = 0; i < n; i++, j++) {
215 lbuffer[i] = (Float_t)(scale * (double)s);
217 block_peak = local_max(block_peak, s);
220 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
227 const double peak_scale = (double)(1u << (bps - 1));
228 double peak = (double)block_peak / peak_scale;
229 if(peak > title_peak_)
231 if(peak > album_peak_)
238 void grabbag__replaygain_get_album(float *gain, float *peak)
240 *gain = (float)GetAlbumGain();
241 *peak = (float)album_peak_;
245 void grabbag__replaygain_get_title(float *gain, float *peak)
247 *gain = (float)GetTitleGain();
248 *peak = (float)title_peak_;
255 unsigned bits_per_sample;
256 unsigned sample_rate;
260 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
262 DecoderInstance *instance = (DecoderInstance*)client_data;
263 const unsigned bits_per_sample = frame->header.bits_per_sample;
264 const unsigned channels = frame->header.channels;
265 const unsigned sample_rate = frame->header.sample_rate;
266 const unsigned samples = frame->header.blocksize;
272 (channels == 2 || channels == 1) &&
273 bits_per_sample == instance->bits_per_sample &&
274 channels == instance->channels &&
275 sample_rate == instance->sample_rate
277 instance->error = !grabbag__replaygain_analyze(buffer, channels==2, bits_per_sample, samples);
280 instance->error = true;
284 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
286 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
289 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
291 DecoderInstance *instance = (DecoderInstance*)client_data;
295 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
296 instance->bits_per_sample = metadata->data.stream_info.bits_per_sample;
297 instance->channels = metadata->data.stream_info.channels;
298 instance->sample_rate = metadata->data.stream_info.sample_rate;
300 if(instance->channels != 1 && instance->channels != 2) {
301 instance->error = true;
305 if(!grabbag__replaygain_is_valid_sample_frequency(instance->sample_rate)) {
306 instance->error = true;
312 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
314 DecoderInstance *instance = (DecoderInstance*)client_data;
316 (void)decoder, (void)status;
318 instance->error = true;
321 const char *grabbag__replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak)
323 DecoderInstance instance;
324 FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
327 return "memory allocation error";
329 instance.error = false;
331 /* It does these three by default but lets be explicit: */
332 FLAC__stream_decoder_set_md5_checking(decoder, false);
333 FLAC__stream_decoder_set_metadata_ignore_all(decoder);
334 FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
336 if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &instance) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
337 FLAC__stream_decoder_delete(decoder);
338 return "initializing decoder";
341 if(!FLAC__stream_decoder_process_until_end_of_stream(decoder) || instance.error) {
342 FLAC__stream_decoder_delete(decoder);
343 return "decoding file";
346 FLAC__stream_decoder_delete(decoder);
348 grabbag__replaygain_get_title(title_gain, title_peak);
353 const char *grabbag__replaygain_store_to_vorbiscomment(FLAC__StreamMetadata *block, float album_gain, float album_peak, float title_gain, float title_peak)
357 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block)))
360 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak)))
363 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak)))
369 const char *grabbag__replaygain_store_to_vorbiscomment_reference(FLAC__StreamMetadata *block)
371 FLAC__ASSERT(0 != block);
372 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
374 if(FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS) < 0)
375 return "memory allocation error";
377 if(!append_tag_(block, reference_format_, GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS, ReplayGainReferenceLoudness))
378 return "memory allocation error";
383 const char *grabbag__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata *block, float album_gain, float album_peak)
385 FLAC__ASSERT(0 != block);
386 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
389 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN) < 0 ||
390 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK) < 0
392 return "memory allocation error";
395 !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN, album_gain) ||
396 !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK, album_peak)
398 return "memory allocation error";
403 const char *grabbag__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata *block, float title_gain, float title_peak)
405 FLAC__ASSERT(0 != block);
406 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
409 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN) < 0 ||
410 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK) < 0
412 return "memory allocation error";
415 !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN, title_gain) ||
416 !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK, title_peak)
418 return "memory allocation error";
423 static const char *store_to_file_pre_(const char *filename, FLAC__Metadata_Chain **chain, FLAC__StreamMetadata **block)
425 FLAC__Metadata_Iterator *iterator;
427 FLAC__bool found_vc_block = false;
429 if(0 == (*chain = FLAC__metadata_chain_new()))
430 return "memory allocation error";
432 if(!FLAC__metadata_chain_read(*chain, filename)) {
433 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
434 FLAC__metadata_chain_delete(*chain);
438 if(0 == (iterator = FLAC__metadata_iterator_new())) {
439 FLAC__metadata_chain_delete(*chain);
440 return "memory allocation error";
443 FLAC__metadata_iterator_init(iterator, *chain);
446 *block = FLAC__metadata_iterator_get_block(iterator);
447 if((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
448 found_vc_block = true;
449 } while(!found_vc_block && FLAC__metadata_iterator_next(iterator));
451 if(!found_vc_block) {
452 /* create a new block */
453 *block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
455 FLAC__metadata_chain_delete(*chain);
456 FLAC__metadata_iterator_delete(iterator);
457 return "memory allocation error";
459 while(FLAC__metadata_iterator_next(iterator))
461 if(!FLAC__metadata_iterator_insert_block_after(iterator, *block)) {
462 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
463 FLAC__metadata_chain_delete(*chain);
464 FLAC__metadata_iterator_delete(iterator);
467 /* iterator is left pointing to new block */
468 FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == *block);
471 FLAC__metadata_iterator_delete(iterator);
473 FLAC__ASSERT(0 != *block);
474 FLAC__ASSERT((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
479 static const char *store_to_file_post_(const char *filename, FLAC__Metadata_Chain *chain, FLAC__bool preserve_modtime)
482 const FLAC__bool have_stats = get_file_stats_(filename, &stats);
484 (void)grabbag__file_change_stats(filename, /*read_only=*/false);
486 FLAC__metadata_chain_sort_padding(chain);
487 if(!FLAC__metadata_chain_write(chain, /*use_padding=*/true, preserve_modtime)) {
489 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)];
490 FLAC__metadata_chain_delete(chain);
494 FLAC__metadata_chain_delete(chain);
497 set_file_stats_(filename, &stats);
502 const char *grabbag__replaygain_store_to_file(const char *filename, float album_gain, float album_peak, float title_gain, float title_peak, FLAC__bool preserve_modtime)
504 FLAC__Metadata_Chain *chain;
505 FLAC__StreamMetadata *block;
508 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
511 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment(block, album_gain, album_peak, title_gain, title_peak))) {
512 FLAC__metadata_chain_delete(chain);
516 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
522 const char *grabbag__replaygain_store_to_file_reference(const char *filename, FLAC__bool preserve_modtime)
524 FLAC__Metadata_Chain *chain;
525 FLAC__StreamMetadata *block;
528 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
531 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block))) {
532 FLAC__metadata_chain_delete(chain);
536 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
542 const char *grabbag__replaygain_store_to_file_album(const char *filename, float album_gain, float album_peak, FLAC__bool preserve_modtime)
544 FLAC__Metadata_Chain *chain;
545 FLAC__StreamMetadata *block;
548 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
551 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak))) {
552 FLAC__metadata_chain_delete(chain);
556 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
562 const char *grabbag__replaygain_store_to_file_title(const char *filename, float title_gain, float title_peak, FLAC__bool preserve_modtime)
564 FLAC__Metadata_Chain *chain;
565 FLAC__StreamMetadata *block;
568 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
571 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak))) {
572 FLAC__metadata_chain_delete(chain);
576 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
582 static FLAC__bool parse_double_(const FLAC__StreamMetadata_VorbisComment_Entry *entry, double *val)
588 FLAC__ASSERT(0 != entry);
589 FLAC__ASSERT(0 != val);
591 p = (const char *)entry->entry;
596 safe_strncpy(s, q, local_min(sizeof(s), (size_t) (entry->length - (q-p))));
606 FLAC__bool grabbag__replaygain_load_from_vorbiscomment(const FLAC__StreamMetadata *block, FLAC__bool album_mode, FLAC__bool strict, double *reference, double *gain, double *peak)
608 int reference_offset, gain_offset, peak_offset;
610 FLAC__ASSERT(0 != block);
611 FLAC__ASSERT(0 != reference);
612 FLAC__ASSERT(0 != gain);
613 FLAC__ASSERT(0 != peak);
614 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
616 /* Default to current level until overridden by a detected tag; this
617 * will always be true until we change replaygain_analysis.c
619 *reference = ReplayGainReferenceLoudness;
621 if(0 <= (reference_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS)))
622 (void)parse_double_(block->data.vorbis_comment.comments + reference_offset, reference);
624 if(0 > (gain_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)(album_mode? GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN : GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN))))
625 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
626 if(0 > (peak_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)(album_mode? GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK : GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK))))
627 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
629 if(!parse_double_(block->data.vorbis_comment.comments + gain_offset, gain))
630 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
631 if(!parse_double_(block->data.vorbis_comment.comments + peak_offset, peak))
632 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
637 double grabbag__replaygain_compute_scale_factor(double peak, double gain, double preamp, FLAC__bool prevent_clipping)
640 FLAC__ASSERT(peak >= 0.0);
642 scale = (float) pow(10.0, gain * 0.05);
643 if(prevent_clipping && peak > 0.0) {
644 const double max_scale = (float)(1.0 / peak);
645 if(scale > max_scale)