1 /* grabbag - Convenience lib for various routines common to several tools
2 * Copyright (C) 2002,2003,2004,2005 Josh Coalson
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program 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
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 #include "share/grabbag.h"
20 #include "share/replaygain_analysis.h"
21 #include "FLAC/assert.h"
22 #include "FLAC/file_decoder.h"
23 #include "FLAC/metadata.h"
29 #if defined _MSC_VER || defined __MINGW32__
30 #include <io.h> /* for chmod() */
32 #include <sys/stat.h> /* for stat(), maybe chmod() */
37 #define local_min(a,b) ((a)<(b)?(a):(b))
42 #define local_max(a,b) ((a)>(b)?(a):(b))
44 static const char *peak_format_ = "%s=%1.8f";
45 static const char *gain_format_ = "%s=%+2.2f dB";
47 static double album_peak_, title_peak_;
49 const unsigned GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED = 148;
51 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
52 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12 +
53 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
54 FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12
57 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN = (const FLAC__byte * const)"REPLAYGAIN_TRACK_GAIN";
58 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK = (const FLAC__byte * const)"REPLAYGAIN_TRACK_PEAK";
59 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_GAIN";
60 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_PEAK";
63 static FLAC__bool get_file_stats_(const char *filename, struct stat *stats)
65 FLAC__ASSERT(0 != filename);
66 FLAC__ASSERT(0 != stats);
67 return (0 == stat(filename, stats));
70 static void set_file_stats_(const char *filename, struct stat *stats)
72 FLAC__ASSERT(0 != filename);
73 FLAC__ASSERT(0 != stats);
75 (void)chmod(filename, stats->st_mode);
78 static FLAC__bool append_tag_(FLAC__StreamMetadata *block, const char *format, const FLAC__byte *name, float value)
82 FLAC__StreamMetadata_VorbisComment_Entry entry;
84 FLAC__ASSERT(0 != block);
85 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
86 FLAC__ASSERT(0 != name);
87 FLAC__ASSERT(0 != value);
89 buffer[sizeof(buffer)-1] = '\0';
91 * We need to save the old locale and switch to "C" because the locale
92 * influences the formatting of %f and we want it a certain way.
94 saved_locale = setlocale(LC_ALL, 0);
95 setlocale(LC_ALL, "C");
96 #if defined _MSC_VER || defined __MINGW32__
97 _snprintf(buffer, sizeof(buffer)-1, format, name, value);
99 snprintf(buffer, sizeof(buffer)-1, format, name, value);
101 setlocale(LC_ALL, saved_locale);
103 entry.entry = (FLAC__byte *)buffer;
104 entry.length = strlen(buffer);
106 return FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true);
109 FLAC__bool grabbag__replaygain_is_valid_sample_frequency(unsigned sample_frequency)
111 static const unsigned valid_sample_rates[] = {
122 static const unsigned n_valid_sample_rates = sizeof(valid_sample_rates) / sizeof(valid_sample_rates[0]);
126 for(i = 0; i < n_valid_sample_rates; i++)
127 if(sample_frequency == valid_sample_rates[i])
132 FLAC__bool grabbag__replaygain_init(unsigned sample_frequency)
134 title_peak_ = album_peak_ = 0.0;
135 return InitGainAnalysis((long)sample_frequency) == INIT_GAIN_ANALYSIS_OK;
138 FLAC__bool grabbag__replaygain_analyze(const FLAC__int32 * const input[], FLAC__bool is_stereo, unsigned bps, unsigned samples)
140 /* using a small buffer improves data locality; we'd like it to fit easily in the dcache */
141 static Float_t lbuffer[2048], rbuffer[2048];
142 static const unsigned nbuffer = sizeof(lbuffer) / sizeof(lbuffer[0]);
143 FLAC__int32 block_peak = 0, s;
146 FLAC__ASSERT(bps >= 4 && bps <= FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE);
147 FLAC__ASSERT(FLAC__MIN_BITS_PER_SAMPLE == 4);
149 * We use abs() on a FLAC__int32 which is undefined for the most negative value.
150 * If the reference codec ever handles 32bps we will have to write a special
153 FLAC__ASSERT(FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE < 32);
159 const unsigned n = local_min(samples, nbuffer);
160 for(i = 0; i < n; i++, j++) {
162 lbuffer[i] = (Float_t)s;
164 block_peak = local_max(block_peak, s);
167 rbuffer[i] = (Float_t)s;
169 block_peak = local_max(block_peak, s);
172 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
179 const unsigned n = local_min(samples, nbuffer);
180 for(i = 0; i < n; i++, j++) {
182 lbuffer[i] = (Float_t)s;
184 block_peak = local_max(block_peak, s);
187 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
192 else { /* bps must be < 32 according to above assertion */
193 const double scale = (
195 (double)1. / (double)(1u << (bps - 16)) :
196 (double)(1u << (16 - bps))
202 const unsigned n = local_min(samples, nbuffer);
203 for(i = 0; i < n; i++, j++) {
205 lbuffer[i] = (Float_t)(scale * (double)s);
207 block_peak = local_max(block_peak, s);
210 rbuffer[i] = (Float_t)(scale * (double)s);
212 block_peak = local_max(block_peak, s);
215 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
222 const unsigned n = local_min(samples, nbuffer);
223 for(i = 0; i < n; i++, j++) {
225 lbuffer[i] = (Float_t)(scale * (double)s);
227 block_peak = local_max(block_peak, s);
230 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
237 const double peak_scale = (double)(1u << (bps - 1));
238 double peak = (double)block_peak / peak_scale;
239 if(peak > title_peak_)
241 if(peak > album_peak_)
248 void grabbag__replaygain_get_album(float *gain, float *peak)
250 *gain = (float)GetAlbumGain();
251 *peak = (float)album_peak_;
255 void grabbag__replaygain_get_title(float *gain, float *peak)
257 *gain = (float)GetTitleGain();
258 *peak = (float)title_peak_;
265 unsigned bits_per_sample;
266 unsigned sample_rate;
270 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
272 DecoderInstance *instance = (DecoderInstance*)client_data;
273 const unsigned bits_per_sample = frame->header.bits_per_sample;
274 const unsigned channels = frame->header.channels;
275 const unsigned sample_rate = frame->header.sample_rate;
276 const unsigned samples = frame->header.blocksize;
282 (channels == 2 || channels == 1) &&
283 bits_per_sample == instance->bits_per_sample &&
284 channels == instance->channels &&
285 sample_rate == instance->sample_rate
287 instance->error = !grabbag__replaygain_analyze(buffer, channels==2, bits_per_sample, samples);
290 instance->error = true;
294 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
296 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
299 static void metadata_callback_(const FLAC__FileDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
301 DecoderInstance *instance = (DecoderInstance*)client_data;
305 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
306 instance->bits_per_sample = metadata->data.stream_info.bits_per_sample;
307 instance->channels = metadata->data.stream_info.channels;
308 instance->sample_rate = metadata->data.stream_info.sample_rate;
310 if(instance->channels != 1 && instance->channels != 2) {
311 instance->error = true;
315 if(!grabbag__replaygain_is_valid_sample_frequency(instance->sample_rate)) {
316 instance->error = true;
322 static void error_callback_(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
324 DecoderInstance *instance = (DecoderInstance*)client_data;
326 (void)decoder, (void)status;
328 instance->error = true;
331 const char *grabbag__replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak)
333 DecoderInstance instance;
334 FLAC__FileDecoder *decoder = FLAC__file_decoder_new();
337 return "memory allocation error";
339 instance.error = false;
341 /* It does these three by default but lets be explicit: */
342 FLAC__file_decoder_set_md5_checking(decoder, false);
343 FLAC__file_decoder_set_metadata_ignore_all(decoder);
344 FLAC__file_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
346 FLAC__file_decoder_set_filename(decoder, filename);
347 FLAC__file_decoder_set_write_callback(decoder, write_callback_);
348 FLAC__file_decoder_set_metadata_callback(decoder, metadata_callback_);
349 FLAC__file_decoder_set_error_callback(decoder, error_callback_);
350 FLAC__file_decoder_set_client_data(decoder, &instance);
352 if(FLAC__file_decoder_init(decoder) != FLAC__FILE_DECODER_OK) {
353 FLAC__file_decoder_delete(decoder);
354 return "initializing decoder";
357 if(!FLAC__file_decoder_process_until_end_of_file(decoder) || instance.error) {
358 FLAC__file_decoder_delete(decoder);
359 return "decoding file";
362 FLAC__file_decoder_delete(decoder);
364 grabbag__replaygain_get_title(title_gain, title_peak);
369 const char *grabbag__replaygain_store_to_vorbiscomment(FLAC__StreamMetadata *block, float album_gain, float album_peak, float title_gain, float title_peak)
373 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak)))
376 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak)))
382 const char *grabbag__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata *block, float album_gain, float album_peak)
384 FLAC__ASSERT(0 != block);
385 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
388 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN) < 0 ||
389 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK) < 0
391 return "memory allocation error";
394 !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK, album_peak) ||
395 !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN, album_gain)
397 return "memory allocation error";
402 const char *grabbag__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata *block, float title_gain, float title_peak)
404 FLAC__ASSERT(0 != block);
405 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
408 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN) < 0 ||
409 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK) < 0
411 return "memory allocation error";
414 !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK, title_peak) ||
415 !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN, title_gain)
417 return "memory allocation error";
422 static const char *store_to_file_pre_(const char *filename, FLAC__Metadata_Chain **chain, FLAC__StreamMetadata **block)
424 FLAC__Metadata_Iterator *iterator;
426 FLAC__bool found_vc_block = false;
428 if(0 == (*chain = FLAC__metadata_chain_new()))
429 return "memory allocation error";
431 if(!FLAC__metadata_chain_read(*chain, filename)) {
432 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
433 FLAC__metadata_chain_delete(*chain);
437 if(0 == (iterator = FLAC__metadata_iterator_new())) {
438 FLAC__metadata_chain_delete(*chain);
439 return "memory allocation error";
442 FLAC__metadata_iterator_init(iterator, *chain);
445 *block = FLAC__metadata_iterator_get_block(iterator);
446 if((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
447 found_vc_block = true;
448 } while(!found_vc_block && FLAC__metadata_iterator_next(iterator));
450 if(!found_vc_block) {
451 /* create a new block */
452 *block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
454 FLAC__metadata_chain_delete(*chain);
455 FLAC__metadata_iterator_delete(iterator);
456 return "memory allocation error";
458 while(FLAC__metadata_iterator_next(iterator))
460 if(!FLAC__metadata_iterator_insert_block_after(iterator, *block)) {
461 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
462 FLAC__metadata_chain_delete(*chain);
463 FLAC__metadata_iterator_delete(iterator);
466 /* iterator is left pointing to new block */
467 FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == *block);
470 FLAC__metadata_iterator_delete(iterator);
472 FLAC__ASSERT(0 != *block);
473 FLAC__ASSERT((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
478 static const char *store_to_file_post_(const char *filename, FLAC__Metadata_Chain *chain, FLAC__bool preserve_modtime)
481 const FLAC__bool have_stats = get_file_stats_(filename, &stats);
483 (void)grabbag__file_change_stats(filename, /*read_only=*/false);
485 FLAC__metadata_chain_sort_padding(chain);
486 if(!FLAC__metadata_chain_write(chain, /*use_padding=*/true, preserve_modtime)) {
487 FLAC__metadata_chain_delete(chain);
488 return FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)];
491 FLAC__metadata_chain_delete(chain);
494 set_file_stats_(filename, &stats);
499 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)
501 FLAC__Metadata_Chain *chain;
502 FLAC__StreamMetadata *block;
505 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
508 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment(block, album_gain, album_peak, title_gain, title_peak))) {
509 FLAC__metadata_chain_delete(chain);
513 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
519 const char *grabbag__replaygain_store_to_file_album(const char *filename, float album_gain, float album_peak, FLAC__bool preserve_modtime)
521 FLAC__Metadata_Chain *chain;
522 FLAC__StreamMetadata *block;
525 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
528 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak))) {
529 FLAC__metadata_chain_delete(chain);
533 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
539 const char *grabbag__replaygain_store_to_file_title(const char *filename, float title_gain, float title_peak, FLAC__bool preserve_modtime)
541 FLAC__Metadata_Chain *chain;
542 FLAC__StreamMetadata *block;
545 if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
548 if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak))) {
549 FLAC__metadata_chain_delete(chain);
553 if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
559 static FLAC__bool parse_double_(const FLAC__StreamMetadata_VorbisComment_Entry *entry, double *val)
565 FLAC__ASSERT(0 != entry);
566 FLAC__ASSERT(0 != val);
568 p = (const char *)entry->entry;
573 memset(s, 0, sizeof(s)-1);
574 strncpy(s, q, local_min(sizeof(s)-1, entry->length - (q-p)));
584 FLAC__bool grabbag__replaygain_load_from_vorbiscomment(const FLAC__StreamMetadata *block, FLAC__bool album_mode, double *gain, double *peak)
586 int gain_offset, peak_offset;
588 FLAC__ASSERT(0 != block);
589 FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
591 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))))
593 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))))
596 if(!parse_double_(block->data.vorbis_comment.comments + gain_offset, gain))
598 if(!parse_double_(block->data.vorbis_comment.comments + peak_offset, peak))
604 double grabbag__replaygain_compute_scale_factor(double peak, double gain, double preamp, FLAC__bool prevent_clipping)
607 FLAC__ASSERT(peak >= 0.0);
609 scale = (float) pow(10.0, gain * 0.05);
610 if(prevent_clipping && peak > 0.0) {
611 const double max_scale = (float)(1.0 / peak);
612 if(scale > max_scale)