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
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);
82 (void)chmod(filename, stats->st_mode);
85 static FLAC__bool append_tag_(FLAC__StreamMetadata *block, const char *format, const FLAC__byte *name, float value)
89 FLAC__StreamMetadata_VorbisComment_Entry entry;
91 FLAC__ASSERT(0 != block);
92 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
93 FLAC__ASSERT(0 != format);
94 FLAC__ASSERT(0 != name);
96 buffer[sizeof(buffer)-1] = '\0';
98 * We need to save the old locale and switch to "C" because the locale
99 * influences the formatting of %f and we want it a certain way.
101 saved_locale = strdup(setlocale(LC_ALL, 0));
102 if (0 == saved_locale)
104 setlocale(LC_ALL, "C");
105 #if defined _MSC_VER || defined __MINGW32__
106 _snprintf(buffer, sizeof(buffer)-1, format, name, value);
108 snprintf(buffer, sizeof(buffer)-1, format, name, value);
110 setlocale(LC_ALL, saved_locale);
113 entry.entry = (FLAC__byte *)buffer;
114 entry.length = strlen(buffer);
116 return FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true);
119 FLAC__bool grabbag__replaygain_is_valid_sample_frequency(unsigned sample_frequency)
121 return ValidGainFrequency( sample_frequency );
124 FLAC__bool grabbag__replaygain_init(unsigned sample_frequency)
126 title_peak_ = album_peak_ = 0.0;
127 return InitGainAnalysis((long)sample_frequency) == INIT_GAIN_ANALYSIS_OK;
130 FLAC__bool grabbag__replaygain_analyze(const FLAC__int32 * const input[], FLAC__bool is_stereo, unsigned bps, unsigned samples)
132 /* using a small buffer improves data locality; we'd like it to fit easily in the dcache */
133 static Float_t lbuffer[2048], rbuffer[2048];
134 static const unsigned nbuffer = sizeof(lbuffer) / sizeof(lbuffer[0]);
135 FLAC__int32 block_peak = 0, s;
138 FLAC__ASSERT(bps >= 4 && bps <= FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE);
139 FLAC__ASSERT(FLAC__MIN_BITS_PER_SAMPLE == 4);
141 * We use abs() on a FLAC__int32 which is undefined for the most negative value.
142 * If the reference codec ever handles 32bps we will have to write a special
145 FLAC__ASSERT(FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE < 32);
151 const unsigned n = local_min(samples, nbuffer);
152 for(i = 0; i < n; i++, j++) {
154 lbuffer[i] = (Float_t)s;
156 block_peak = local_max(block_peak, s);
159 rbuffer[i] = (Float_t)s;
161 block_peak = local_max(block_peak, s);
164 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
171 const unsigned n = local_min(samples, nbuffer);
172 for(i = 0; i < n; i++, j++) {
174 lbuffer[i] = (Float_t)s;
176 block_peak = local_max(block_peak, s);
179 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
184 else { /* bps must be < 32 according to above assertion */
185 const double scale = (
187 (double)1. / (double)(1u << (bps - 16)) :
188 (double)(1u << (16 - bps))
194 const unsigned n = local_min(samples, nbuffer);
195 for(i = 0; i < n; i++, j++) {
197 lbuffer[i] = (Float_t)(scale * (double)s);
199 block_peak = local_max(block_peak, s);
202 rbuffer[i] = (Float_t)(scale * (double)s);
204 block_peak = local_max(block_peak, s);
207 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
214 const unsigned n = local_min(samples, nbuffer);
215 for(i = 0; i < n; i++, j++) {
217 lbuffer[i] = (Float_t)(scale * (double)s);
219 block_peak = local_max(block_peak, s);
222 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
229 const double peak_scale = (double)(1u << (bps - 1));
230 double peak = (double)block_peak / peak_scale;
231 if(peak > title_peak_)
233 if(peak > album_peak_)
240 void grabbag__replaygain_get_album(float *gain, float *peak)
242 *gain = (float)GetAlbumGain();
243 *peak = (float)album_peak_;
247 void grabbag__replaygain_get_title(float *gain, float *peak)
249 *gain = (float)GetTitleGain();
250 *peak = (float)title_peak_;
257 unsigned bits_per_sample;
258 unsigned sample_rate;
262 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
264 DecoderInstance *instance = (DecoderInstance*)client_data;
265 const unsigned bits_per_sample = frame->header.bits_per_sample;
266 const unsigned channels = frame->header.channels;
267 const unsigned sample_rate = frame->header.sample_rate;
268 const unsigned samples = frame->header.blocksize;
274 (channels == 2 || channels == 1) &&
275 bits_per_sample == instance->bits_per_sample &&
276 channels == instance->channels &&
277 sample_rate == instance->sample_rate
279 instance->error = !grabbag__replaygain_analyze(buffer, channels==2, bits_per_sample, samples);
282 instance->error = true;
286 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
288 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
291 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
293 DecoderInstance *instance = (DecoderInstance*)client_data;
297 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
298 instance->bits_per_sample = metadata->data.stream_info.bits_per_sample;
299 instance->channels = metadata->data.stream_info.channels;
300 instance->sample_rate = metadata->data.stream_info.sample_rate;
302 if(instance->channels != 1 && instance->channels != 2) {
303 instance->error = true;
307 if(!grabbag__replaygain_is_valid_sample_frequency(instance->sample_rate)) {
308 instance->error = true;
314 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
316 DecoderInstance *instance = (DecoderInstance*)client_data;
318 (void)decoder, (void)status;
320 instance->error = true;
323 const char *grabbag__replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak)
325 DecoderInstance instance;
326 FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
329 return "memory allocation error";
331 instance.error = false;
333 /* It does these three by default but lets be explicit: */
334 FLAC__stream_decoder_set_md5_checking(decoder, false);
335 FLAC__stream_decoder_set_metadata_ignore_all(decoder);
336 FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
338 if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &instance) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
339 FLAC__stream_decoder_delete(decoder);
340 return "initializing decoder";
343 if(!FLAC__stream_decoder_process_until_end_of_stream(decoder) || instance.error) {
344 FLAC__stream_decoder_delete(decoder);
345 return "decoding file";
348 FLAC__stream_decoder_delete(decoder);
350 grabbag__replaygain_get_title(title_gain, title_peak);
355 const char *grabbag__replaygain_store_to_vorbiscomment(FLAC__StreamMetadata *block, float album_gain, float album_peak, float title_gain, float title_peak)
359 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block)))
362 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak)))
365 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak)))
371 const char *grabbag__replaygain_store_to_vorbiscomment_reference(FLAC__StreamMetadata *block)
373 FLAC__ASSERT(0 != block);
374 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
376 if(FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS) < 0)
377 return "memory allocation error";
379 if(!append_tag_(block, reference_format_, GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS, ReplayGainReferenceLoudness))
380 return "memory allocation error";
385 const char *grabbag__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata *block, float album_gain, float album_peak)
387 FLAC__ASSERT(0 != block);
388 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
391 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN) < 0 ||
392 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK) < 0
394 return "memory allocation error";
397 !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN, album_gain) ||
398 !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK, album_peak)
400 return "memory allocation error";
405 const char *grabbag__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata *block, float title_gain, float title_peak)
407 FLAC__ASSERT(0 != block);
408 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
411 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN) < 0 ||
412 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK) < 0
414 return "memory allocation error";
417 !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN, title_gain) ||
418 !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK, title_peak)
420 return "memory allocation error";
425 static const char *store_to_file_pre_(const char *filename, FLAC__Metadata_Chain **chain, FLAC__StreamMetadata **block)
427 FLAC__Metadata_Iterator *iterator;
429 FLAC__bool found_vc_block = false;
431 if(0 == (*chain = FLAC__metadata_chain_new()))
432 return "memory allocation error";
434 if(!FLAC__metadata_chain_read(*chain, filename)) {
435 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
436 FLAC__metadata_chain_delete(*chain);
440 if(0 == (iterator = FLAC__metadata_iterator_new())) {
441 FLAC__metadata_chain_delete(*chain);
442 return "memory allocation error";
445 FLAC__metadata_iterator_init(iterator, *chain);
448 *block = FLAC__metadata_iterator_get_block(iterator);
449 if((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
450 found_vc_block = true;
451 } while(!found_vc_block && FLAC__metadata_iterator_next(iterator));
453 if(!found_vc_block) {
454 /* create a new block */
455 *block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
457 FLAC__metadata_chain_delete(*chain);
458 FLAC__metadata_iterator_delete(iterator);
459 return "memory allocation error";
461 while(FLAC__metadata_iterator_next(iterator))
463 if(!FLAC__metadata_iterator_insert_block_after(iterator, *block)) {
464 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
465 FLAC__metadata_chain_delete(*chain);
466 FLAC__metadata_iterator_delete(iterator);
469 /* iterator is left pointing to new block */
470 FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == *block);
473 FLAC__metadata_iterator_delete(iterator);
475 FLAC__ASSERT(0 != *block);
476 FLAC__ASSERT((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
481 static const char *store_to_file_post_(const char *filename, FLAC__Metadata_Chain *chain, FLAC__bool preserve_modtime)
484 const FLAC__bool have_stats = get_file_stats_(filename, &stats);
486 (void)grabbag__file_change_stats(filename, /*read_only=*/false);
488 FLAC__metadata_chain_sort_padding(chain);
489 if(!FLAC__metadata_chain_write(chain, /*use_padding=*/true, preserve_modtime)) {
491 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)];
492 FLAC__metadata_chain_delete(chain);
496 FLAC__metadata_chain_delete(chain);
499 set_file_stats_(filename, &stats);
504 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)
506 FLAC__Metadata_Chain *chain;
507 FLAC__StreamMetadata *block;
510 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
513 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment(block, album_gain, album_peak, title_gain, title_peak))) {
514 FLAC__metadata_chain_delete(chain);
518 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
524 const char *grabbag__replaygain_store_to_file_reference(const char *filename, FLAC__bool preserve_modtime)
526 FLAC__Metadata_Chain *chain;
527 FLAC__StreamMetadata *block;
530 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
533 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block))) {
534 FLAC__metadata_chain_delete(chain);
538 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
544 const char *grabbag__replaygain_store_to_file_album(const char *filename, float album_gain, float album_peak, FLAC__bool preserve_modtime)
546 FLAC__Metadata_Chain *chain;
547 FLAC__StreamMetadata *block;
550 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
553 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak))) {
554 FLAC__metadata_chain_delete(chain);
558 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
564 const char *grabbag__replaygain_store_to_file_title(const char *filename, float title_gain, float title_peak, FLAC__bool preserve_modtime)
566 FLAC__Metadata_Chain *chain;
567 FLAC__StreamMetadata *block;
570 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
573 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak))) {
574 FLAC__metadata_chain_delete(chain);
578 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
584 static FLAC__bool parse_double_(const FLAC__StreamMetadata_VorbisComment_Entry *entry, double *val)
590 FLAC__ASSERT(0 != entry);
591 FLAC__ASSERT(0 != val);
593 p = (const char *)entry->entry;
598 memset(s, 0, sizeof(s)-1);
599 strncpy(s, q, local_min(sizeof(s)-1, (size_t) (entry->length - (q-p))));
609 FLAC__bool grabbag__replaygain_load_from_vorbiscomment(const FLAC__StreamMetadata *block, FLAC__bool album_mode, FLAC__bool strict, double *reference, double *gain, double *peak)
611 int reference_offset, gain_offset, peak_offset;
613 FLAC__ASSERT(0 != block);
614 FLAC__ASSERT(0 != reference);
615 FLAC__ASSERT(0 != gain);
616 FLAC__ASSERT(0 != peak);
617 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
619 /* Default to current level until overridden by a detected tag; this
620 * will always be true until we change replaygain_analysis.c
622 *reference = ReplayGainReferenceLoudness;
624 if(0 <= (reference_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS)))
625 (void)parse_double_(block->data.vorbis_comment.comments + reference_offset, reference);
627 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))))
628 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
629 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))))
630 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
632 if(!parse_double_(block->data.vorbis_comment.comments + gain_offset, gain))
633 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
634 if(!parse_double_(block->data.vorbis_comment.comments + peak_offset, peak))
635 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
640 double grabbag__replaygain_compute_scale_factor(double peak, double gain, double preamp, FLAC__bool prevent_clipping)
643 FLAC__ASSERT(peak >= 0.0);
645 scale = (float) pow(10.0, gain * 0.05);
646 if(prevent_clipping && peak > 0.0) {
647 const double max_scale = (float)(1.0 / peak);
648 if(scale > max_scale)