replaygain.c 20.3 KB
Newer Older
Josh Coalson's avatar
Josh Coalson committed
1
/* grabbag - Convenience lib for various routines common to several tools
2
3
 * Copyright (C) 2002-2009  Josh Coalson
 * Copyright (C) 2011-2013  Xiph.Org Foundation
Josh Coalson's avatar
Josh Coalson committed
4
 *
5
6
7
8
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
Josh Coalson's avatar
Josh Coalson committed
9
 *
10
 * This library is distributed in the hope that it will be useful,
Josh Coalson's avatar
Josh Coalson committed
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Josh Coalson's avatar
Josh Coalson committed
14
 *
15
16
17
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
Josh Coalson's avatar
Josh Coalson committed
18
19
 */

20
#ifdef HAVE_CONFIG_H
Josh Coalson's avatar
Josh Coalson committed
21
22
23
#  include <config.h>
#endif

24
#include <locale.h>
Josh Coalson's avatar
Josh Coalson committed
25
26
27
28
29
30
31
32
33
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined _MSC_VER || defined __MINGW32__
#include <io.h> /* for chmod() */
#endif
#include <sys/stat.h> /* for stat(), maybe chmod() */

34
35
36
37
38
39
40
#include "FLAC/assert.h"
#include "FLAC/metadata.h"
#include "FLAC/stream_decoder.h"
#include "share/grabbag.h"
#include "share/replaygain_analysis.h"
#include "share/safe_str.h"

Josh Coalson's avatar
Josh Coalson committed
41
42
43
44
45
46
47
48
49
50
#ifdef local_min
#undef local_min
#endif
#define local_min(a,b) ((a)<(b)?(a):(b))

#ifdef local_max
#undef local_max
#endif
#define local_max(a,b) ((a)>(b)?(a):(b))

51
static const char *reference_format_ = "%s=%2.1f dB";
Josh Coalson's avatar
Josh Coalson committed
52
static const char *gain_format_ = "%s=%+2.2f dB";
53
static const char *peak_format_ = "%s=%1.8f";
Josh Coalson's avatar
Josh Coalson committed
54
55
56

static double album_peak_, title_peak_;

57
const unsigned GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED = 190;
Josh Coalson's avatar
Josh Coalson committed
58
/*
59
	FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 29 + 1 + 8 +
Josh Coalson's avatar
Josh Coalson committed
60
61
62
63
64
65
	FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
	FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12 +
	FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
	FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12
*/

66
const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS = (const FLAC__byte * const)"REPLAYGAIN_REFERENCE_LOUDNESS";
67
68
69
70
71
const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN = (const FLAC__byte * const)"REPLAYGAIN_TRACK_GAIN";
const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK = (const FLAC__byte * const)"REPLAYGAIN_TRACK_PEAK";
const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_GAIN";
const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_PEAK";

Josh Coalson's avatar
Josh Coalson committed
72

73
static FLAC__bool get_file_stats_(const char *filename, struct flac_stat_s *stats)
Josh Coalson's avatar
Josh Coalson committed
74
75
76
{
	FLAC__ASSERT(0 != filename);
	FLAC__ASSERT(0 != stats);
77
	return (0 == flac_stat(filename, stats));
Josh Coalson's avatar
Josh Coalson committed
78
79
}

80
static void set_file_stats_(const char *filename, struct flac_stat_s *stats)
Josh Coalson's avatar
Josh Coalson committed
81
82
83
84
{
	FLAC__ASSERT(0 != filename);
	FLAC__ASSERT(0 != stats);

85
	(void)flac_chmod(filename, stats->st_mode);
Josh Coalson's avatar
Josh Coalson committed
86
87
88
89
90
}

static FLAC__bool append_tag_(FLAC__StreamMetadata *block, const char *format, const FLAC__byte *name, float value)
{
	char buffer[256];
91
	char *saved_locale;
Josh Coalson's avatar
Josh Coalson committed
92
93
94
95
	FLAC__StreamMetadata_VorbisComment_Entry entry;

	FLAC__ASSERT(0 != block);
	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
Josh Coalson's avatar
Josh Coalson committed
96
	FLAC__ASSERT(0 != format);
Josh Coalson's avatar
Josh Coalson committed
97
98
99
	FLAC__ASSERT(0 != name);

	buffer[sizeof(buffer)-1] = '\0';
100
101
102
103
	/*
	 * We need to save the old locale and switch to "C" because the locale
	 * influences the formatting of %f and we want it a certain way.
	 */
104
105
106
	saved_locale = strdup(setlocale(LC_ALL, 0));
	if (0 == saved_locale)
		return false;
107
	setlocale(LC_ALL, "C");
108
	flac_snprintf(buffer, sizeof(buffer), format, name, value);
109
	setlocale(LC_ALL, saved_locale);
110
	free(saved_locale);
Josh Coalson's avatar
Josh Coalson committed
111

112
	entry.entry = (FLAC__byte *)buffer;
Josh Coalson's avatar
Josh Coalson committed
113
114
	entry.length = strlen(buffer);

115
	return FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true);
Josh Coalson's avatar
Josh Coalson committed
116
117
}

118
FLAC__bool grabbag__replaygain_is_valid_sample_frequency(unsigned sample_frequency)
Josh Coalson's avatar
Josh Coalson committed
119
{
120
        return ValidGainFrequency( sample_frequency );
Josh Coalson's avatar
Josh Coalson committed
121
122
}

123
FLAC__bool grabbag__replaygain_init(unsigned sample_frequency)
Josh Coalson's avatar
Josh Coalson committed
124
125
126
127
128
{
	title_peak_ = album_peak_ = 0.0;
	return InitGainAnalysis((long)sample_frequency) == INIT_GAIN_ANALYSIS_OK;
}

129
FLAC__bool grabbag__replaygain_analyze(const FLAC__int32 * const input[], FLAC__bool is_stereo, unsigned bps, unsigned samples)
Josh Coalson's avatar
Josh Coalson committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
{
	/* using a small buffer improves data locality; we'd like it to fit easily in the dcache */
	static Float_t lbuffer[2048], rbuffer[2048];
	static const unsigned nbuffer = sizeof(lbuffer) / sizeof(lbuffer[0]);
	FLAC__int32 block_peak = 0, s;
	unsigned i, j;

	FLAC__ASSERT(bps >= 4 && bps <= FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE);
	FLAC__ASSERT(FLAC__MIN_BITS_PER_SAMPLE == 4);
	/*
	 * We use abs() on a FLAC__int32 which is undefined for the most negative value.
	 * If the reference codec ever handles 32bps we will have to write a special
	 * case here.
	 */
	FLAC__ASSERT(FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE < 32);

	if(bps == 16) {
		if(is_stereo) {
			j = 0;
			while(samples > 0) {
				const unsigned n = local_min(samples, nbuffer);
				for(i = 0; i < n; i++, j++) {
					s = input[0][j];
					lbuffer[i] = (Float_t)s;
					s = abs(s);
					block_peak = local_max(block_peak, s);

					s = input[1][j];
					rbuffer[i] = (Float_t)s;
					s = abs(s);
					block_peak = local_max(block_peak, s);
				}
				samples -= n;
				if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
					return false;
			}
		}
		else {
			j = 0;
			while(samples > 0) {
				const unsigned n = local_min(samples, nbuffer);
				for(i = 0; i < n; i++, j++) {
					s = input[0][j];
					lbuffer[i] = (Float_t)s;
					s = abs(s);
					block_peak = local_max(block_peak, s);
				}
				samples -= n;
				if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
					return false;
			}
		}
	}
	else { /* bps must be < 32 according to above assertion */
		const double scale = (
			(bps > 16)?
				(double)1. / (double)(1u << (bps - 16)) :
				(double)(1u << (16 - bps))
		);

		if(is_stereo) {
			j = 0;
			while(samples > 0) {
				const unsigned n = local_min(samples, nbuffer);
				for(i = 0; i < n; i++, j++) {
					s = input[0][j];
					lbuffer[i] = (Float_t)(scale * (double)s);
					s = abs(s);
					block_peak = local_max(block_peak, s);

					s = input[1][j];
					rbuffer[i] = (Float_t)(scale * (double)s);
					s = abs(s);
					block_peak = local_max(block_peak, s);
				}
				samples -= n;
				if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
					return false;
			}
		}
		else {
			j = 0;
			while(samples > 0) {
				const unsigned n = local_min(samples, nbuffer);
				for(i = 0; i < n; i++, j++) {
					s = input[0][j];
					lbuffer[i] = (Float_t)(scale * (double)s);
					s = abs(s);
					block_peak = local_max(block_peak, s);
				}
				samples -= n;
				if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
					return false;
			}
		}
	}

	{
		const double peak_scale = (double)(1u << (bps - 1));
		double peak = (double)block_peak / peak_scale;
		if(peak > title_peak_)
			title_peak_ = peak;
		if(peak > album_peak_)
			album_peak_ = peak;
	}

	return true;
}

239
void grabbag__replaygain_get_album(float *gain, float *peak)
Josh Coalson's avatar
Josh Coalson committed
240
241
242
243
244
245
{
	*gain = (float)GetAlbumGain();
	*peak = (float)album_peak_;
	album_peak_ = 0.0;
}

246
void grabbag__replaygain_get_title(float *gain, float *peak)
Josh Coalson's avatar
Josh Coalson committed
247
248
249
250
251
252
253
254
255
256
257
258
259
260
{
	*gain = (float)GetTitleGain();
	*peak = (float)title_peak_;
	title_peak_ = 0.0;
}


typedef struct {
	unsigned channels;
	unsigned bits_per_sample;
	unsigned sample_rate;
	FLAC__bool error;
} DecoderInstance;

261
static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
Josh Coalson's avatar
Josh Coalson committed
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
{
	DecoderInstance *instance = (DecoderInstance*)client_data;
	const unsigned bits_per_sample = frame->header.bits_per_sample;
	const unsigned channels = frame->header.channels;
	const unsigned sample_rate = frame->header.sample_rate;
	const unsigned samples = frame->header.blocksize;

	(void)decoder;

	if(
		!instance->error &&
		(channels == 2 || channels == 1) &&
		bits_per_sample == instance->bits_per_sample &&
		channels == instance->channels &&
		sample_rate == instance->sample_rate
	) {
		instance->error = !grabbag__replaygain_analyze(buffer, channels==2, bits_per_sample, samples);
	}
	else {
		instance->error = true;
	}

	if(!instance->error)
		return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
	else
		return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}

290
static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
Josh Coalson's avatar
Josh Coalson committed
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
{
	DecoderInstance *instance = (DecoderInstance*)client_data;

	(void)decoder;

	if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
		instance->bits_per_sample = metadata->data.stream_info.bits_per_sample;
		instance->channels = metadata->data.stream_info.channels;
		instance->sample_rate = metadata->data.stream_info.sample_rate;

		if(instance->channels != 1 && instance->channels != 2) {
			instance->error = true;
			return;
		}

		if(!grabbag__replaygain_is_valid_sample_frequency(instance->sample_rate)) {
			instance->error = true;
			return;
		}
	}
}

313
static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
Josh Coalson's avatar
Josh Coalson committed
314
315
316
317
318
319
320
321
{
	DecoderInstance *instance = (DecoderInstance*)client_data;

	(void)decoder, (void)status;

	instance->error = true;
}

322
const char *grabbag__replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak)
Josh Coalson's avatar
Josh Coalson committed
323
324
{
	DecoderInstance instance;
325
	FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
Josh Coalson's avatar
Josh Coalson committed
326
327
328
329
330
331
332

	if(0 == decoder)
		return "memory allocation error";

	instance.error = false;

	/* It does these three by default but lets be explicit: */
333
334
335
336
337
338
	FLAC__stream_decoder_set_md5_checking(decoder, false);
	FLAC__stream_decoder_set_metadata_ignore_all(decoder);
	FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);

	if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &instance) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
		FLAC__stream_decoder_delete(decoder);
Josh Coalson's avatar
Josh Coalson committed
339
340
341
		return "initializing decoder";
	}

342
343
	if(!FLAC__stream_decoder_process_until_end_of_stream(decoder) || instance.error) {
		FLAC__stream_decoder_delete(decoder);
Josh Coalson's avatar
Josh Coalson committed
344
345
346
		return "decoding file";
	}

347
	FLAC__stream_decoder_delete(decoder);
Josh Coalson's avatar
Josh Coalson committed
348
349
350
351
352
353

	grabbag__replaygain_get_title(title_gain, title_peak);

	return 0;
}

354
const char *grabbag__replaygain_store_to_vorbiscomment(FLAC__StreamMetadata *block, float album_gain, float album_peak, float title_gain, float title_peak)
Josh Coalson's avatar
Josh Coalson committed
355
356
357
{
	const char *error;

358
359
360
	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block)))
		return error;

Josh Coalson's avatar
Josh Coalson committed
361
362
363
364
365
366
367
368
369
	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak)))
		return error;

	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak)))
		return error;

	return 0;
}

370
371
372
373
374
375
376
377
378
379
380
381
382
383
const char *grabbag__replaygain_store_to_vorbiscomment_reference(FLAC__StreamMetadata *block)
{
	FLAC__ASSERT(0 != block);
	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);

	if(FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS) < 0)
		return "memory allocation error";

	if(!append_tag_(block, reference_format_, GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS, ReplayGainReferenceLoudness))
		return "memory allocation error";

	return 0;
}

384
const char *grabbag__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata *block, float album_gain, float album_peak)
Josh Coalson's avatar
Josh Coalson committed
385
386
387
388
389
{
	FLAC__ASSERT(0 != block);
	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);

	if(
390
391
		FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN) < 0 ||
		FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK) < 0
Josh Coalson's avatar
Josh Coalson committed
392
393
394
395
	)
		return "memory allocation error";

	if(
396
397
		!append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN, album_gain) ||
		!append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK, album_peak)
Josh Coalson's avatar
Josh Coalson committed
398
399
400
401
402
403
	)
		return "memory allocation error";

	return 0;
}

404
const char *grabbag__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata *block, float title_gain, float title_peak)
Josh Coalson's avatar
Josh Coalson committed
405
406
407
408
409
{
	FLAC__ASSERT(0 != block);
	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);

	if(
410
411
		FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN) < 0 ||
		FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK) < 0
Josh Coalson's avatar
Josh Coalson committed
412
413
414
415
	)
		return "memory allocation error";

	if(
416
417
		!append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN, title_gain) ||
		!append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK, title_peak)
Josh Coalson's avatar
Josh Coalson committed
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
	)
		return "memory allocation error";

	return 0;
}

static const char *store_to_file_pre_(const char *filename, FLAC__Metadata_Chain **chain, FLAC__StreamMetadata **block)
{
	FLAC__Metadata_Iterator *iterator;
	const char *error;
	FLAC__bool found_vc_block = false;

	if(0 == (*chain = FLAC__metadata_chain_new()))
		return "memory allocation error";

	if(!FLAC__metadata_chain_read(*chain, filename)) {
		error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
		FLAC__metadata_chain_delete(*chain);
		return error;
	}

	if(0 == (iterator = FLAC__metadata_iterator_new())) {
		FLAC__metadata_chain_delete(*chain);
		return "memory allocation error";
	}

	FLAC__metadata_iterator_init(iterator, *chain);

	do {
		*block = FLAC__metadata_iterator_get_block(iterator);
		if((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
			found_vc_block = true;
	} while(!found_vc_block && FLAC__metadata_iterator_next(iterator));

	if(!found_vc_block) {
		/* create a new block */
		*block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
		if(0 == *block) {
			FLAC__metadata_chain_delete(*chain);
			FLAC__metadata_iterator_delete(iterator);
			return "memory allocation error";
		}
		while(FLAC__metadata_iterator_next(iterator))
			;
		if(!FLAC__metadata_iterator_insert_block_after(iterator, *block)) {
			error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
			FLAC__metadata_chain_delete(*chain);
			FLAC__metadata_iterator_delete(iterator);
			return error;
		}
		/* iterator is left pointing to new block */
		FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == *block);
	}

	FLAC__metadata_iterator_delete(iterator);

	FLAC__ASSERT(0 != *block);
	FLAC__ASSERT((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);

	return 0;
}

static const char *store_to_file_post_(const char *filename, FLAC__Metadata_Chain *chain, FLAC__bool preserve_modtime)
{
482
	struct flac_stat_s stats;
Josh Coalson's avatar
Josh Coalson committed
483
484
485
486
487
488
	const FLAC__bool have_stats = get_file_stats_(filename, &stats);

	(void)grabbag__file_change_stats(filename, /*read_only=*/false);

	FLAC__metadata_chain_sort_padding(chain);
	if(!FLAC__metadata_chain_write(chain, /*use_padding=*/true, preserve_modtime)) {
Felipe Contreras's avatar
Felipe Contreras committed
489
490
		const char *error;
		error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)];
Josh Coalson's avatar
Josh Coalson committed
491
		FLAC__metadata_chain_delete(chain);
Felipe Contreras's avatar
Felipe Contreras committed
492
		return error;
Josh Coalson's avatar
Josh Coalson committed
493
494
495
496
497
498
499
500
501
502
	}

	FLAC__metadata_chain_delete(chain);

	if(have_stats)
		set_file_stats_(filename, &stats);

	return 0;
}

503
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)
Josh Coalson's avatar
Josh Coalson committed
504
505
{
	FLAC__Metadata_Chain *chain;
506
	FLAC__StreamMetadata *block = NULL;
Josh Coalson's avatar
Josh Coalson committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
	const char *error;

	if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
		return error;

	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment(block, album_gain, album_peak, title_gain, title_peak))) {
		FLAC__metadata_chain_delete(chain);
		return error;
	}

	if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
		return error;

	return 0;
}

523
524
525
const char *grabbag__replaygain_store_to_file_reference(const char *filename, FLAC__bool preserve_modtime)
{
	FLAC__Metadata_Chain *chain;
526
	FLAC__StreamMetadata *block = NULL;
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
	const char *error;

	if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
		return error;

	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block))) {
		FLAC__metadata_chain_delete(chain);
		return error;
	}

	if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
		return error;

	return 0;
}

543
const char *grabbag__replaygain_store_to_file_album(const char *filename, float album_gain, float album_peak, FLAC__bool preserve_modtime)
Josh Coalson's avatar
Josh Coalson committed
544
545
{
	FLAC__Metadata_Chain *chain;
546
	FLAC__StreamMetadata *block = NULL;
Josh Coalson's avatar
Josh Coalson committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
	const char *error;

	if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
		return error;

	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak))) {
		FLAC__metadata_chain_delete(chain);
		return error;
	}

	if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
		return error;

	return 0;
}

563
const char *grabbag__replaygain_store_to_file_title(const char *filename, float title_gain, float title_peak, FLAC__bool preserve_modtime)
Josh Coalson's avatar
Josh Coalson committed
564
565
{
	FLAC__Metadata_Chain *chain;
566
	FLAC__StreamMetadata *block = NULL;
Josh Coalson's avatar
Josh Coalson committed
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
	const char *error;

	if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
		return error;

	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak))) {
		FLAC__metadata_chain_delete(chain);
		return error;
	}

	if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
		return error;

	return 0;
}

static FLAC__bool parse_double_(const FLAC__StreamMetadata_VorbisComment_Entry *entry, double *val)
{
	char s[32], *end;
	const char *p, *q;
	double v;

	FLAC__ASSERT(0 != entry);
	FLAC__ASSERT(0 != val);

	p = (const char *)entry->entry;
	q = strchr(p, '=');
	if(0 == q)
		return false;
	q++;
597
	safe_strncpy(s, q, local_min(sizeof(s), (size_t) (entry->length - (q-p))));
Josh Coalson's avatar
Josh Coalson committed
598
599
600
601
602
603
604
605
606

	v = strtod(s, &end);
	if(end == s)
		return false;

	*val = v;
	return true;
}

607
FLAC__bool grabbag__replaygain_load_from_vorbiscomment(const FLAC__StreamMetadata *block, FLAC__bool album_mode, FLAC__bool strict, double *reference, double *gain, double *peak)
Josh Coalson's avatar
Josh Coalson committed
608
{
609
	int reference_offset, gain_offset, peak_offset;
610
611
	char *saved_locale;
	FLAC__bool res = true;
Josh Coalson's avatar
Josh Coalson committed
612
613

	FLAC__ASSERT(0 != block);
614
615
616
	FLAC__ASSERT(0 != reference);
	FLAC__ASSERT(0 != gain);
	FLAC__ASSERT(0 != peak);
Josh Coalson's avatar
Josh Coalson committed
617
618
	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);

619
620
621
622
623
	/* Default to current level until overridden by a detected tag; this
	 * will always be true until we change replaygain_analysis.c
	 */
	*reference = ReplayGainReferenceLoudness;

624
625
626
627
628
629
630
631
632
	/*
	 * We need to save the old locale and switch to "C" because the locale
	 * influences the formatting of %f and we want it a certain way.
	 */
	saved_locale = strdup(setlocale(LC_ALL, 0));
	if (0 == saved_locale)
		return false;
	setlocale(LC_ALL, "C");

633
634
635
	if(0 <= (reference_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS)))
		(void)parse_double_(block->data.vorbis_comment.comments + reference_offset, reference);

636
	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))))
637
		res = false;
638
	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))))
639
		res = false;
Josh Coalson's avatar
Josh Coalson committed
640

641
642
643
644
	if(res && !parse_double_(block->data.vorbis_comment.comments + gain_offset, gain))
		res = false;
	if(res && !parse_double_(block->data.vorbis_comment.comments + peak_offset, peak))
		res = false;
Josh Coalson's avatar
Josh Coalson committed
645

646
647
648
649
650
651
652
653
	setlocale(LC_ALL, saved_locale);
	free(saved_locale);

	/* something failed; retry with strict */
	if (!res && !strict)
		res = grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);

	return res;
Josh Coalson's avatar
Josh Coalson committed
654
655
}

656
double grabbag__replaygain_compute_scale_factor(double peak, double gain, double preamp, FLAC__bool prevent_clipping)
Josh Coalson's avatar
Josh Coalson committed
657
658
659
660
661
662
663
664
665
666
667
668
{
	double scale;
	FLAC__ASSERT(peak >= 0.0);
 	gain += preamp;
	scale = (float) pow(10.0, gain * 0.05);
	if(prevent_clipping && peak > 0.0) {
		const double max_scale = (float)(1.0 / peak);
		if(scale > max_scale)
			scale = max_scale;
	}
	return scale;
}