-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calibration.cs
66 lines (57 loc) · 1.92 KB
/
Calibration.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
namespace ToneGenerator
{
/// <summary>
/// A calibration class using a dictionary for frequencies and amplitudes.
/// </summary>
public class Calibration
{
const int MaxCacheSize = 100;
private readonly float minFrequency;
private readonly float maxFrequency;
// Simple caching
private readonly Dictionary<float, float> cache = new();
public Dictionary<float, float> AmplitudesDb { get; set; }
public Calibration(Dictionary<float, float> amplitudesDb)
{
AmplitudesDb = amplitudesDb;
if (amplitudesDb != null)
{
minFrequency = amplitudesDb.Keys.Min();
maxFrequency = amplitudesDb.Keys.Max();
}
}
public float GetAmplitudeDb(float frequency)
{
if (frequency <= minFrequency)
return AmplitudesDb[minFrequency];
if (frequency >= maxFrequency)
return AmplitudesDb[maxFrequency];
// Simple caching, because this is going to be called over and over
if (cache.TryGetValue(frequency, out float result))
return result;
var freqKeys = AmplitudesDb.Keys.Zip(AmplitudesDb.Keys.Skip(1), (a, b) => new { LowerKey = a, UpperKey = b })
.Where(x => x.LowerKey <= frequency && x.UpperKey >= frequency)
.First();
// Linear interpolation
var t = (frequency - freqKeys.LowerKey) / (freqKeys.UpperKey - freqKeys.LowerKey);
result = (1 - t) * AmplitudesDb[freqKeys.LowerKey]
+ t * AmplitudesDb[freqKeys.UpperKey];
if (cache.Count > MaxCacheSize)
cache.Clear();
cache[frequency] = result;
return result;
}
public float GetCalibratedAmplitude(Soundtrack track, bool useLoudness = true)
{
// Loudness normalization: 120 dB -> 0 dBFS, 0 dB -> threshold
const float MaxDb = 120;
var thresholdDb = GetAmplitudeDb(track.Frequency);
var amplitudeDb = Utilities.MagToDb(track.Amplitude);
if (useLoudness)
amplitudeDb = -thresholdDb / MaxDb * (amplitudeDb - MaxDb);
else
amplitudeDb += thresholdDb;
return Utilities.DbToMag(amplitudeDb);
}
}
}