1 /* grabbag - Convenience lib for various routines common to several tools
2 * Copyright (C) 2002,2003,2004,2005,2006,2007 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
23 #include "share/grabbag.h"
24 #include "share/replaygain_analysis.h"
25 #include "flac/assert.h"
26 #include "flac/metadata.h"
27 #include "flac/stream_decoder.h"
33 #if defined _MSC_VER || defined __MINGW32__
34 #include <io.h> /* for chmod() */
36 #include <sys/stat.h> /* for stat(), maybe chmod() */
41 #define local_min(a,b) ((a)<(b)?(a):(b))
46 #define local_max(a,b) ((a)>(b)?(a):(b))
48 static const char *reference_format_ = "%s=%2.1f dB";
49 static const char *gain_format_ = "%s=%+2.2f dB";
50 static const char *peak_format_ = "%s=%1.8f";
52 static double album_peak_, title_peak_;
54 const unsigned GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED = 190;
56 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 29 + 1 + 8 +
57 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
58 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12 +
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
63 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS = (const FLAC__byte * const)"REPLAYGAIN_REFERENCE_LOUDNESS";
64 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN = (const FLAC__byte * const)"REPLAYGAIN_TRACK_GAIN";
65 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK = (const FLAC__byte * const)"REPLAYGAIN_TRACK_PEAK";
66 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_GAIN";
67 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_PEAK";
70 static FLAC__bool get_file_stats_(const char *filename, struct stat *stats)
72 FLAC__ASSERT(0 != filename);
73 FLAC__ASSERT(0 != stats);
74 return (0 == stat(filename, stats));
77 static void set_file_stats_(const char *filename, struct stat *stats)
79 FLAC__ASSERT(0 != filename);
80 FLAC__ASSERT(0 != stats);
83 static FLAC__bool append_tag_(FLAC__StreamMetadata *block, const char *format, const FLAC__byte *name, float value)
87 FLAC__StreamMetadata_VorbisComment_Entry entry;
89 FLAC__ASSERT(0 != block);
90 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
91 FLAC__ASSERT(0 != format);
92 FLAC__ASSERT(0 != name);
94 buffer[sizeof(buffer)-1] = '\0';
96 * We need to save the old locale and switch to "C" because the locale
97 * influences the formatting of %f and we want it a certain way.
99 saved_locale = strdup(setlocale(LC_ALL, 0));
100 if (0 == saved_locale)
102 setlocale(LC_ALL, "C");
103 #if defined _MSC_VER || defined __MINGW32__
104 _snprintf(buffer, sizeof(buffer)-1, format, name, value);
106 snprintf(buffer, sizeof(buffer)-1, 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 static const unsigned valid_sample_rates[] = {
130 static const unsigned n_valid_sample_rates = sizeof(valid_sample_rates) / sizeof(valid_sample_rates[0]);
134 for(i = 0; i < n_valid_sample_rates; i++)
135 if(sample_frequency == valid_sample_rates[i])
140 FLAC__bool grabbag__replaygain_init(unsigned sample_frequency)
142 title_peak_ = album_peak_ = 0.0;
143 return InitGainAnalysis((long)sample_frequency) == INIT_GAIN_ANALYSIS_OK;
146 FLAC__bool grabbag__replaygain_analyze(const FLAC__int32 * const input[], FLAC__bool is_stereo, unsigned bps, unsigned samples)
148 /* using a small buffer improves data locality; we'd like it to fit easily in the dcache */
149 static Float_t lbuffer[2048], rbuffer[2048];
150 static const unsigned nbuffer = sizeof(lbuffer) / sizeof(lbuffer[0]);
151 FLAC__int32 block_peak = 0, s;
154 FLAC__ASSERT(bps >= 4 && bps <= FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE);
155 FLAC__ASSERT(FLAC__MIN_BITS_PER_SAMPLE == 4);
157 * We use abs() on a FLAC__int32 which is undefined for the most negative value.
158 * If the reference codec ever handles 32bps we will have to write a special
161 FLAC__ASSERT(FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE < 32);
167 const unsigned n = local_min(samples, nbuffer);
168 for(i = 0; i < n; i++, j++) {
170 lbuffer[i] = (Float_t)s;
172 block_peak = local_max(block_peak, s);
175 rbuffer[i] = (Float_t)s;
177 block_peak = local_max(block_peak, s);
180 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
187 const unsigned n = local_min(samples, nbuffer);
188 for(i = 0; i < n; i++, j++) {
190 lbuffer[i] = (Float_t)s;
192 block_peak = local_max(block_peak, s);
195 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
200 else { /* bps must be < 32 according to above assertion */
201 const double scale = (
203 (double)1. / (double)(1u << (bps - 16)) :
204 (double)(1u << (16 - bps))
210 const unsigned n = local_min(samples, nbuffer);
211 for(i = 0; i < n; i++, j++) {
213 lbuffer[i] = (Float_t)(scale * (double)s);
215 block_peak = local_max(block_peak, s);
218 rbuffer[i] = (Float_t)(scale * (double)s);
220 block_peak = local_max(block_peak, s);
223 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
230 const unsigned n = local_min(samples, nbuffer);
231 for(i = 0; i < n; i++, j++) {
233 lbuffer[i] = (Float_t)(scale * (double)s);
235 block_peak = local_max(block_peak, s);
238 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
245 const double peak_scale = (double)(1u << (bps - 1));
246 double peak = (double)block_peak / peak_scale;
247 if(peak > title_peak_)
249 if(peak > album_peak_)
256 void grabbag__replaygain_get_album(float *gain, float *peak)
258 *gain = (float)GetAlbumGain();
259 *peak = (float)album_peak_;
263 void grabbag__replaygain_get_title(float *gain, float *peak)
265 *gain = (float)GetTitleGain();
266 *peak = (float)title_peak_;
273 unsigned bits_per_sample;
274 unsigned sample_rate;
278 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
280 DecoderInstance *instance = (DecoderInstance*)client_data;
281 const unsigned bits_per_sample = frame->header.bits_per_sample;
282 const unsigned channels = frame->header.channels;
283 const unsigned sample_rate = frame->header.sample_rate;
284 const unsigned samples = frame->header.blocksize;
290 (channels == 2 || channels == 1) &&
291 bits_per_sample == instance->bits_per_sample &&
292 channels == instance->channels &&
293 sample_rate == instance->sample_rate
295 instance->error = !grabbag__replaygain_analyze(buffer, channels==2, bits_per_sample, samples);
298 instance->error = true;
302 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
304 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
307 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
309 DecoderInstance *instance = (DecoderInstance*)client_data;
313 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
314 instance->bits_per_sample = metadata->data.stream_info.bits_per_sample;
315 instance->channels = metadata->data.stream_info.channels;
316 instance->sample_rate = metadata->data.stream_info.sample_rate;
318 if(instance->channels != 1 && instance->channels != 2) {
319 instance->error = true;
323 if(!grabbag__replaygain_is_valid_sample_frequency(instance->sample_rate)) {
324 instance->error = true;
330 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
332 DecoderInstance *instance = (DecoderInstance*)client_data;
334 (void)decoder, (void)status;
336 instance->error = true;
339 const char *grabbag__replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak)
341 DecoderInstance instance;
342 FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
345 return "memory allocation error";
347 instance.error = false;
349 /* It does these three by default but lets be explicit: */
350 FLAC__stream_decoder_set_md5_checking(decoder, false);
351 FLAC__stream_decoder_set_metadata_ignore_all(decoder);
352 FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
354 if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &instance) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
355 FLAC__stream_decoder_delete(decoder);
356 return "initializing decoder";
359 if(!FLAC__stream_decoder_process_until_end_of_stream(decoder) || instance.error) {
360 FLAC__stream_decoder_delete(decoder);
361 return "decoding file";
364 FLAC__stream_decoder_delete(decoder);
366 grabbag__replaygain_get_title(title_gain, title_peak);
371 const char *grabbag__replaygain_store_to_vorbiscomment(FLAC__StreamMetadata *block, float album_gain, float album_peak, float title_gain, float title_peak)
375 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block)))
378 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak)))
381 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak)))
387 const char *grabbag__replaygain_store_to_vorbiscomment_reference(FLAC__StreamMetadata *block)
389 FLAC__ASSERT(0 != block);
390 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
392 if(FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS) < 0)
393 return "memory allocation error";
395 if(!append_tag_(block, reference_format_, GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS, ReplayGainReferenceLoudness))
396 return "memory allocation error";
401 const char *grabbag__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata *block, float album_gain, float album_peak)
403 FLAC__ASSERT(0 != block);
404 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
407 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN) < 0 ||
408 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK) < 0
410 return "memory allocation error";
413 !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN, album_gain) ||
414 !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK, album_peak)
416 return "memory allocation error";
421 const char *grabbag__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata *block, float title_gain, float title_peak)
423 FLAC__ASSERT(0 != block);
424 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
427 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN) < 0 ||
428 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK) < 0
430 return "memory allocation error";
433 !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN, title_gain) ||
434 !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK, title_peak)
436 return "memory allocation error";
441 static const char *store_to_file_pre_(const char *filename, FLAC__Metadata_Chain **chain, FLAC__StreamMetadata **block)
443 FLAC__Metadata_Iterator *iterator;
445 FLAC__bool found_vc_block = false;
447 if(0 == (*chain = FLAC__metadata_chain_new()))
448 return "memory allocation error";
450 if(!FLAC__metadata_chain_read(*chain, filename)) {
451 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
452 FLAC__metadata_chain_delete(*chain);
456 if(0 == (iterator = FLAC__metadata_iterator_new())) {
457 FLAC__metadata_chain_delete(*chain);
458 return "memory allocation error";
461 FLAC__metadata_iterator_init(iterator, *chain);
464 *block = FLAC__metadata_iterator_get_block(iterator);
465 if((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
466 found_vc_block = true;
467 } while(!found_vc_block && FLAC__metadata_iterator_next(iterator));
469 if(!found_vc_block) {
470 /* create a new block */
471 *block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
473 FLAC__metadata_chain_delete(*chain);
474 FLAC__metadata_iterator_delete(iterator);
475 return "memory allocation error";
477 while(FLAC__metadata_iterator_next(iterator))
479 if(!FLAC__metadata_iterator_insert_block_after(iterator, *block)) {
480 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
481 FLAC__metadata_chain_delete(*chain);
482 FLAC__metadata_iterator_delete(iterator);
485 /* iterator is left pointing to new block */
486 FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == *block);
489 FLAC__metadata_iterator_delete(iterator);
491 FLAC__ASSERT(0 != *block);
492 FLAC__ASSERT((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
497 static const char *store_to_file_post_(const char *filename, FLAC__Metadata_Chain *chain, FLAC__bool preserve_modtime)
500 const FLAC__bool have_stats = get_file_stats_(filename, &stats);
502 (void)grabbag__file_change_stats(filename, /*read_only=*/false);
504 FLAC__metadata_chain_sort_padding(chain);
505 if(!FLAC__metadata_chain_write(chain, /*use_padding=*/true, preserve_modtime)) {
506 FLAC__metadata_chain_delete(chain);
507 return FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)];
510 FLAC__metadata_chain_delete(chain);
513 set_file_stats_(filename, &stats);
518 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)
520 FLAC__Metadata_Chain *chain;
521 FLAC__StreamMetadata *block;
524 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
527 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment(block, album_gain, album_peak, title_gain, title_peak))) {
528 FLAC__metadata_chain_delete(chain);
532 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
538 const char *grabbag__replaygain_store_to_file_reference(const char *filename, FLAC__bool preserve_modtime)
540 FLAC__Metadata_Chain *chain;
541 FLAC__StreamMetadata *block;
544 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
547 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block))) {
548 FLAC__metadata_chain_delete(chain);
552 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
558 const char *grabbag__replaygain_store_to_file_album(const char *filename, float album_gain, float album_peak, FLAC__bool preserve_modtime)
560 FLAC__Metadata_Chain *chain;
561 FLAC__StreamMetadata *block;
564 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
567 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak))) {
568 FLAC__metadata_chain_delete(chain);
572 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
578 const char *grabbag__replaygain_store_to_file_title(const char *filename, float title_gain, float title_peak, FLAC__bool preserve_modtime)
580 FLAC__Metadata_Chain *chain;
581 FLAC__StreamMetadata *block;
584 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
587 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak))) {
588 FLAC__metadata_chain_delete(chain);
592 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
598 static FLAC__bool parse_double_(const FLAC__StreamMetadata_VorbisComment_Entry *entry, double *val)
604 FLAC__ASSERT(0 != entry);
605 FLAC__ASSERT(0 != val);
607 p = (const char *)entry->entry;
612 memset(s, 0, sizeof(s)-1);
613 strncpy(s, q, local_min(sizeof(s)-1, entry->length - (q-p)));
623 FLAC__bool grabbag__replaygain_load_from_vorbiscomment(const FLAC__StreamMetadata *block, FLAC__bool album_mode, FLAC__bool strict, double *reference, double *gain, double *peak)
625 int reference_offset, gain_offset, peak_offset;
627 FLAC__ASSERT(0 != block);
628 FLAC__ASSERT(0 != reference);
629 FLAC__ASSERT(0 != gain);
630 FLAC__ASSERT(0 != peak);
631 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
633 /* Default to current level until overridden by a detected tag; this
634 * will always be true until we change replaygain_analysis.c
636 *reference = ReplayGainReferenceLoudness;
638 if(0 <= (reference_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS)))
639 (void)parse_double_(block->data.vorbis_comment.comments + reference_offset, reference);
641 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))))
642 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
643 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))))
644 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
646 if(!parse_double_(block->data.vorbis_comment.comments + gain_offset, gain))
647 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
648 if(!parse_double_(block->data.vorbis_comment.comments + peak_offset, peak))
649 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
654 double grabbag__replaygain_compute_scale_factor(double peak, double gain, double preamp, FLAC__bool prevent_clipping)
657 FLAC__ASSERT(peak >= 0.0);
659 scale = (float) pow(10.0, gain * 0.05);
660 if(prevent_clipping && peak > 0.0) {
661 const double max_scale = (float)(1.0 / peak);
662 if(scale > max_scale)