xref: /aosp_15_r20/external/flac/src/share/grabbag/replaygain.c (revision 600f14f40d737144c998e2ec7a483122d3776fbc)
1 /* grabbag - Convenience lib for various routines common to several tools
2  * Copyright (C) 2002-2009  Josh Coalson
3  * Copyright (C) 2011-2023  Xiph.Org Foundation
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18  */
19 
20 #ifdef HAVE_CONFIG_H
21 #  include <config.h>
22 #endif
23 
24 #include <locale.h>
25 #include <math.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #if defined _MSC_VER || defined __MINGW32__
30 #include <io.h> /* for chmod() */
31 #endif
32 #include <sys/stat.h> /* for stat(), maybe chmod() */
33 
34 #include "FLAC/assert.h"
35 #include "FLAC/metadata.h"
36 #include "FLAC/stream_decoder.h"
37 #include "share/grabbag.h"
38 #include "share/replaygain_analysis.h"
39 #include "share/safe_str.h"
40 
41 #ifdef local_min
42 #undef local_min
43 #endif
44 #define local_min(a,b) ((a)<(b)?(a):(b))
45 
46 #ifdef local_max
47 #undef local_max
48 #endif
49 #define local_max(a,b) ((a)>(b)?(a):(b))
50 
51 #ifdef abs32
52 #undef abs32
53 #endif
54 #define abs32(a) (((a)==INT32_MIN)?INT32_MAX:abs(a))
55 
56 static const char *reference_format_ = "%s=%2.1f dB";
57 static const char *gain_format_ = "%s=%+2.2f dB";
58 static const char *peak_format_ = "%s=%1.8f";
59 
60 static double album_peak_, title_peak_;
61 
62 const uint32_t GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED = 190;
63 /*
64 	FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 29 + 1 + 8 +
65 	FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
66 	FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12 +
67 	FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
68 	FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12
69 */
70 
71 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS = (const FLAC__byte * const)"REPLAYGAIN_REFERENCE_LOUDNESS";
72 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN = (const FLAC__byte * const)"REPLAYGAIN_TRACK_GAIN";
73 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK = (const FLAC__byte * const)"REPLAYGAIN_TRACK_PEAK";
74 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_GAIN";
75 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_PEAK";
76 
77 
get_file_stats_(const char * filename,struct flac_stat_s * stats)78 static FLAC__bool get_file_stats_(const char *filename, struct flac_stat_s *stats)
79 {
80 	FLAC__ASSERT(0 != filename);
81 	FLAC__ASSERT(0 != stats);
82 	return (0 == flac_stat(filename, stats));
83 }
84 
set_file_stats_(const char * filename,struct flac_stat_s * stats)85 static void set_file_stats_(const char *filename, struct flac_stat_s *stats)
86 {
87 	FLAC__ASSERT(0 != filename);
88 	FLAC__ASSERT(0 != stats);
89 
90 	(void)flac_chmod(filename, stats->st_mode);
91 }
92 
append_tag_(FLAC__StreamMetadata * block,const char * format,const FLAC__byte * name,float value)93 static FLAC__bool append_tag_(FLAC__StreamMetadata *block, const char *format, const FLAC__byte *name, float value)
94 {
95 	char buffer[256];
96 	char *saved_locale;
97 	FLAC__StreamMetadata_VorbisComment_Entry entry;
98 
99 	FLAC__ASSERT(0 != block);
100 	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
101 	FLAC__ASSERT(0 != format);
102 	FLAC__ASSERT(0 != name);
103 
104 	buffer[sizeof(buffer)-1] = '\0';
105 	/*
106 	 * We need to save the old locale and switch to "C" because the locale
107 	 * influences the formatting of %f and we want it a certain way.
108 	 */
109 	saved_locale = strdup(setlocale(LC_ALL, 0));
110 	if (0 == saved_locale)
111 		return false;
112 	setlocale(LC_ALL, "C");
113 	flac_snprintf(buffer, sizeof(buffer), format, name, value);
114 	setlocale(LC_ALL, saved_locale);
115 	free(saved_locale);
116 
117 	entry.entry = (FLAC__byte *)buffer;
118 	entry.length = strlen(buffer);
119 
120 	return FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true);
121 }
122 
grabbag__replaygain_is_valid_sample_frequency(uint32_t sample_frequency)123 FLAC__bool grabbag__replaygain_is_valid_sample_frequency(uint32_t sample_frequency)
124 {
125 	return ValidGainFrequency( sample_frequency );
126 }
127 
grabbag__replaygain_init(uint32_t sample_frequency)128 FLAC__bool grabbag__replaygain_init(uint32_t sample_frequency)
129 {
130 	title_peak_ = album_peak_ = 0.0;
131 	return InitGainAnalysis((long)sample_frequency) == INIT_GAIN_ANALYSIS_OK;
132 }
133 
grabbag__replaygain_analyze(const FLAC__int32 * const input[],FLAC__bool is_stereo,uint32_t bps,uint32_t samples)134 FLAC__bool grabbag__replaygain_analyze(const FLAC__int32 * const input[], FLAC__bool is_stereo, uint32_t bps, uint32_t samples)
135 {
136 	/* using a small buffer improves data locality; we'd like it to fit easily in the dcache */
137 	static flac_float_t lbuffer[2048], rbuffer[2048];
138 	static const uint32_t nbuffer = sizeof(lbuffer) / sizeof(lbuffer[0]);
139 	FLAC__int32 block_peak = 0, s;
140 	uint32_t i, j;
141 
142 	FLAC__ASSERT(bps >= FLAC__MIN_BITS_PER_SAMPLE && bps <= FLAC__MAX_BITS_PER_SAMPLE);
143 	FLAC__ASSERT(FLAC__MIN_BITS_PER_SAMPLE == 4 && FLAC__MAX_BITS_PER_SAMPLE == 32);
144 
145 	if(bps == 16) {
146 		if(is_stereo) {
147 			j = 0;
148 			while(samples > 0) {
149 				const uint32_t n = local_min(samples, nbuffer);
150 				for(i = 0; i < n; i++, j++) {
151 					s = input[0][j];
152 					lbuffer[i] = (flac_float_t)s;
153 					s = abs(s);
154 					block_peak = local_max(block_peak, s);
155 
156 					s = input[1][j];
157 					rbuffer[i] = (flac_float_t)s;
158 					s = abs(s);
159 					block_peak = local_max(block_peak, s);
160 				}
161 				samples -= n;
162 				if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
163 					return false;
164 			}
165 		}
166 		else {
167 			j = 0;
168 			while(samples > 0) {
169 				const uint32_t n = local_min(samples, nbuffer);
170 				for(i = 0; i < n; i++, j++) {
171 					s = input[0][j];
172 					lbuffer[i] = (flac_float_t)s;
173 					s = abs(s);
174 					block_peak = local_max(block_peak, s);
175 				}
176 				samples -= n;
177 				if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
178 					return false;
179 			}
180 		}
181 	}
182 	else {
183 		const double scale = (
184 			(bps > 16)?
185 				(double)1. / (double)(1u << (bps - 16)) :
186 				(double)(1u << (16 - bps))
187 		);
188 
189 		if(is_stereo) {
190 			j = 0;
191 			while(samples > 0) {
192 				const uint32_t n = local_min(samples, nbuffer);
193 				for(i = 0; i < n; i++, j++) {
194 					s = input[0][j];
195 					lbuffer[i] = (flac_float_t)(scale * (double)s);
196 					s = abs32(s);
197 					block_peak = local_max(block_peak, s);
198 
199 					s = input[1][j];
200 					rbuffer[i] = (flac_float_t)(scale * (double)s);
201 					s = abs32(s);
202 					block_peak = local_max(block_peak, s);
203 				}
204 				samples -= n;
205 				if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
206 					return false;
207 			}
208 		}
209 		else {
210 			j = 0;
211 			while(samples > 0) {
212 				const uint32_t n = local_min(samples, nbuffer);
213 				for(i = 0; i < n; i++, j++) {
214 					s = input[0][j];
215 					lbuffer[i] = (flac_float_t)(scale * (double)s);
216 					s = abs32(s);
217 					block_peak = local_max(block_peak, s);
218 				}
219 				samples -= n;
220 				if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
221 					return false;
222 			}
223 		}
224 	}
225 
226 	{
227 		const double peak_scale = (double)(1u << (bps - 1));
228 		double peak = (double)block_peak / peak_scale;
229 		if(peak > title_peak_)
230 			title_peak_ = peak;
231 		if(peak > album_peak_)
232 			album_peak_ = peak;
233 	}
234 
235 	return true;
236 }
237 
grabbag__replaygain_get_album(float * gain,float * peak)238 void grabbag__replaygain_get_album(float *gain, float *peak)
239 {
240 	*gain = (float)GetAlbumGain();
241 	*peak = (float)album_peak_;
242 	album_peak_ = 0.0;
243 }
244 
grabbag__replaygain_get_title(float * gain,float * peak)245 void grabbag__replaygain_get_title(float *gain, float *peak)
246 {
247 	*gain = (float)GetTitleGain();
248 	*peak = (float)title_peak_;
249 	title_peak_ = 0.0;
250 }
251 
252 
253 typedef struct {
254 	uint32_t channels;
255 	uint32_t bits_per_sample;
256 	uint32_t sample_rate;
257 	FLAC__bool error;
258 } DecoderInstance;
259 
write_callback_(const FLAC__StreamDecoder * decoder,const FLAC__Frame * frame,const FLAC__int32 * const buffer[],void * client_data)260 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
261 {
262 	DecoderInstance *instance = (DecoderInstance*)client_data;
263 	const uint32_t bits_per_sample = frame->header.bits_per_sample;
264 	const uint32_t channels = frame->header.channels;
265 	const uint32_t sample_rate = frame->header.sample_rate;
266 	const uint32_t samples = frame->header.blocksize;
267 
268 	(void)decoder;
269 
270 	if(
271 		!instance->error &&
272 		(channels == 2 || channels == 1) &&
273 		bits_per_sample == instance->bits_per_sample &&
274 		channels == instance->channels &&
275 		sample_rate == instance->sample_rate
276 	) {
277 		instance->error = !grabbag__replaygain_analyze(buffer, channels==2, bits_per_sample, samples);
278 	}
279 	else {
280 		instance->error = true;
281 	}
282 
283 	if(!instance->error)
284 		return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
285 	else
286 		return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
287 }
288 
metadata_callback_(const FLAC__StreamDecoder * decoder,const FLAC__StreamMetadata * metadata,void * client_data)289 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
290 {
291 	DecoderInstance *instance = (DecoderInstance*)client_data;
292 
293 	(void)decoder;
294 
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;
299 
300 		if(instance->channels != 1 && instance->channels != 2) {
301 			instance->error = true;
302 			return;
303 		}
304 
305 		if(!grabbag__replaygain_is_valid_sample_frequency(instance->sample_rate)) {
306 			instance->error = true;
307 			return;
308 		}
309 	}
310 }
311 
error_callback_(const FLAC__StreamDecoder * decoder,FLAC__StreamDecoderErrorStatus status,void * client_data)312 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
313 {
314 	DecoderInstance *instance = (DecoderInstance*)client_data;
315 
316 	(void)decoder, (void)status;
317 
318 	instance->error = true;
319 }
320 
grabbag__replaygain_analyze_file(const char * filename,float * title_gain,float * title_peak)321 const char *grabbag__replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak)
322 {
323 	DecoderInstance instance;
324 	FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
325 
326 	if(0 == decoder)
327 		return "memory allocation error";
328 
329 	instance.error = false;
330 
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);
335 
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";
339 	}
340 
341 	if(!FLAC__stream_decoder_process_until_end_of_stream(decoder) || instance.error) {
342 		FLAC__stream_decoder_delete(decoder);
343 		return "decoding file";
344 	}
345 
346 	FLAC__stream_decoder_delete(decoder);
347 
348 	grabbag__replaygain_get_title(title_gain, title_peak);
349 
350 	return 0;
351 }
352 
grabbag__replaygain_store_to_vorbiscomment(FLAC__StreamMetadata * block,float album_gain,float album_peak,float title_gain,float 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)
354 {
355 	const char *error;
356 
357 	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block)))
358 		return error;
359 
360 	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak)))
361 		return error;
362 
363 	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak)))
364 		return error;
365 
366 	return 0;
367 }
368 
grabbag__replaygain_store_to_vorbiscomment_reference(FLAC__StreamMetadata * block)369 const char *grabbag__replaygain_store_to_vorbiscomment_reference(FLAC__StreamMetadata *block)
370 {
371 	FLAC__ASSERT(0 != block);
372 	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
373 
374 	if(FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS) < 0)
375 		return "memory allocation error";
376 
377 	if(!append_tag_(block, reference_format_, GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS, ReplayGainReferenceLoudness))
378 		return "memory allocation error";
379 
380 	return 0;
381 }
382 
grabbag__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata * block,float album_gain,float album_peak)383 const char *grabbag__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata *block, float album_gain, float album_peak)
384 {
385 	FLAC__ASSERT(0 != block);
386 	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
387 
388 	if(
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
391 	)
392 		return "memory allocation error";
393 
394 	if(
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)
397 	)
398 		return "memory allocation error";
399 
400 	return 0;
401 }
402 
grabbag__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata * block,float title_gain,float title_peak)403 const char *grabbag__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata *block, float title_gain, float title_peak)
404 {
405 	FLAC__ASSERT(0 != block);
406 	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
407 
408 	if(
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
411 	)
412 		return "memory allocation error";
413 
414 	if(
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)
417 	)
418 		return "memory allocation error";
419 
420 	return 0;
421 }
422 
store_to_file_pre_(const char * filename,FLAC__Metadata_Chain ** chain,FLAC__StreamMetadata ** block)423 static const char *store_to_file_pre_(const char *filename, FLAC__Metadata_Chain **chain, FLAC__StreamMetadata **block)
424 {
425 	FLAC__Metadata_Iterator *iterator;
426 	const char *error;
427 	FLAC__bool found_vc_block = false;
428 
429 	if(0 == (*chain = FLAC__metadata_chain_new()))
430 		return "memory allocation error";
431 
432 	if(!FLAC__metadata_chain_read(*chain, filename)) {
433 		error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
434 		FLAC__metadata_chain_delete(*chain);
435 		return error;
436 	}
437 
438 	if(0 == (iterator = FLAC__metadata_iterator_new())) {
439 		FLAC__metadata_chain_delete(*chain);
440 		return "memory allocation error";
441 	}
442 
443 	FLAC__metadata_iterator_init(iterator, *chain);
444 
445 	do {
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));
450 
451 	if(!found_vc_block) {
452 		/* create a new block */
453 		*block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
454 		if(0 == *block) {
455 			FLAC__metadata_chain_delete(*chain);
456 			FLAC__metadata_iterator_delete(iterator);
457 			return "memory allocation error";
458 		}
459 		while(FLAC__metadata_iterator_next(iterator))
460 			;
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);
465 			return error;
466 		}
467 		/* iterator is left pointing to new block */
468 		FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == *block);
469 	}
470 
471 	FLAC__metadata_iterator_delete(iterator);
472 
473 	FLAC__ASSERT(0 != *block);
474 	FLAC__ASSERT((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
475 
476 	return 0;
477 }
478 
store_to_file_post_(const char * filename,FLAC__Metadata_Chain * chain,FLAC__bool preserve_modtime)479 static const char *store_to_file_post_(const char *filename, FLAC__Metadata_Chain *chain, FLAC__bool preserve_modtime)
480 {
481 	struct flac_stat_s stats;
482 	const FLAC__bool have_stats = get_file_stats_(filename, &stats);
483 
484 	(void)grabbag__file_change_stats(filename, /*read_only=*/false);
485 
486 	FLAC__metadata_chain_sort_padding(chain);
487 	if(!FLAC__metadata_chain_write(chain, /*use_padding=*/true, preserve_modtime)) {
488 		const char *error;
489 		error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)];
490 		FLAC__metadata_chain_delete(chain);
491 		return error;
492 	}
493 
494 	FLAC__metadata_chain_delete(chain);
495 
496 	if(have_stats)
497 		set_file_stats_(filename, &stats);
498 
499 	return 0;
500 }
501 
grabbag__replaygain_store_to_file(const char * filename,float album_gain,float album_peak,float title_gain,float title_peak,FLAC__bool preserve_modtime)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)
503 {
504 	FLAC__Metadata_Chain *chain;
505 	FLAC__StreamMetadata *block = NULL;
506 	const char *error;
507 
508 	if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
509 		return error;
510 
511 	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment(block, album_gain, album_peak, title_gain, title_peak))) {
512 		FLAC__metadata_chain_delete(chain);
513 		return error;
514 	}
515 
516 	if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
517 		return error;
518 
519 	return 0;
520 }
521 
grabbag__replaygain_store_to_file_reference(const char * filename,FLAC__bool preserve_modtime)522 const char *grabbag__replaygain_store_to_file_reference(const char *filename, FLAC__bool preserve_modtime)
523 {
524 	FLAC__Metadata_Chain *chain;
525 	FLAC__StreamMetadata *block = NULL;
526 	const char *error;
527 
528 	if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
529 		return error;
530 
531 	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block))) {
532 		FLAC__metadata_chain_delete(chain);
533 		return error;
534 	}
535 
536 	if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
537 		return error;
538 
539 	return 0;
540 }
541 
grabbag__replaygain_store_to_file_album(const char * filename,float album_gain,float album_peak,FLAC__bool preserve_modtime)542 const char *grabbag__replaygain_store_to_file_album(const char *filename, float album_gain, float album_peak, FLAC__bool preserve_modtime)
543 {
544 	FLAC__Metadata_Chain *chain;
545 	FLAC__StreamMetadata *block = NULL;
546 	const char *error;
547 
548 	if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
549 		return error;
550 
551 	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak))) {
552 		FLAC__metadata_chain_delete(chain);
553 		return error;
554 	}
555 
556 	if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
557 		return error;
558 
559 	return 0;
560 }
561 
grabbag__replaygain_store_to_file_title(const char * filename,float title_gain,float title_peak,FLAC__bool preserve_modtime)562 const char *grabbag__replaygain_store_to_file_title(const char *filename, float title_gain, float title_peak, FLAC__bool preserve_modtime)
563 {
564 	FLAC__Metadata_Chain *chain;
565 	FLAC__StreamMetadata *block = NULL;
566 	const char *error;
567 
568 	if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
569 		return error;
570 
571 	if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak))) {
572 		FLAC__metadata_chain_delete(chain);
573 		return error;
574 	}
575 
576 	if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
577 		return error;
578 
579 	return 0;
580 }
581 
parse_double_(const FLAC__StreamMetadata_VorbisComment_Entry * entry,double * val)582 static FLAC__bool parse_double_(const FLAC__StreamMetadata_VorbisComment_Entry *entry, double *val)
583 {
584 	char s[32], *end;
585 	const char *p, *q;
586 	double v;
587 
588 	FLAC__ASSERT(0 != entry);
589 	FLAC__ASSERT(0 != val);
590 
591 	p = (const char *)entry->entry;
592 	q = strchr(p, '=');
593 	if(0 == q)
594 		return false;
595 	q++;
596 	safe_strncpy(s, q, local_min(sizeof(s), (size_t) (entry->length - (q-p))));
597 
598 	v = strtod(s, &end);
599 	if(end == s)
600 		return false;
601 
602 	*val = v;
603 	return true;
604 }
605 
grabbag__replaygain_load_from_vorbiscomment(const FLAC__StreamMetadata * block,FLAC__bool album_mode,FLAC__bool strict,double * reference,double * gain,double * peak)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)
607 {
608 	int reference_offset, gain_offset, peak_offset;
609 	char *saved_locale;
610 	FLAC__bool res = true;
611 
612 	FLAC__ASSERT(0 != block);
613 	FLAC__ASSERT(0 != reference);
614 	FLAC__ASSERT(0 != gain);
615 	FLAC__ASSERT(0 != peak);
616 	FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
617 
618 	/* Default to current level until overridden by a detected tag; this
619 	 * will always be true until we change replaygain_analysis.c
620 	 */
621 	*reference = ReplayGainReferenceLoudness;
622 
623 	/*
624 	 * We need to save the old locale and switch to "C" because the locale
625 	 * influences the behaviour of strtod and we want it a certain way.
626 	 */
627 	saved_locale = strdup(setlocale(LC_ALL, 0));
628 	if (0 == saved_locale)
629 		return false;
630 	setlocale(LC_ALL, "C");
631 
632 	if(0 <= (reference_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS)))
633 		(void)parse_double_(block->data.vorbis_comment.comments + reference_offset, reference);
634 
635 	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))))
636 		res = false;
637 	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))))
638 		res = false;
639 
640 	if(res && !parse_double_(block->data.vorbis_comment.comments + gain_offset, gain))
641 		res = false;
642 	if(res && !parse_double_(block->data.vorbis_comment.comments + peak_offset, peak))
643 		res = false;
644 	if(res && *peak < 0.0)
645 		res = false;
646 
647 	setlocale(LC_ALL, saved_locale);
648 	free(saved_locale);
649 
650 	/* something failed; retry with strict */
651 	if (!res && !strict)
652 		res = grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
653 
654 	return res;
655 }
656 
grabbag__replaygain_compute_scale_factor(double peak,double gain,double preamp,FLAC__bool prevent_clipping)657 double grabbag__replaygain_compute_scale_factor(double peak, double gain, double preamp, FLAC__bool prevent_clipping)
658 {
659 	double scale;
660 	FLAC__ASSERT(peak >= 0.0);
661  	gain += preamp;
662 	scale = (float) pow(10.0, gain * 0.05);
663 	if(prevent_clipping && peak > 0.0) {
664 		const double max_scale = (float)(1.0 / peak);
665 		if(scale > max_scale)
666 			scale = max_scale;
667 	}
668 	return scale;
669 }
670