|
| 1 | +from json import loads |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +from yulewalker import yulewalk |
| 6 | + |
| 7 | +from audio_filters.butterworth_filter import make_highpass |
| 8 | +from audio_filters.iir_filter import IIRFilter |
| 9 | + |
| 10 | +data = loads((Path(__file__).resolve().parent / "loudness_curve.json").read_text()) |
| 11 | + |
| 12 | + |
| 13 | +class EqualLoudnessFilter: |
| 14 | + r""" |
| 15 | + An equal-loudness filter which compensates for the human ear's non-linear response |
| 16 | + to sound. |
| 17 | + This filter corrects this by cascading a yulewalk filter and a butterworth filter. |
| 18 | +
|
| 19 | + Designed for use with samplerate of 44.1kHz and above. If you're using a lower |
| 20 | + samplerate, use with caution. |
| 21 | +
|
| 22 | + Code based on matlab implementation at https://bit.ly/3eqh2HU |
| 23 | + (url shortened for flake8) |
| 24 | +
|
| 25 | + Target curve: https://i.imgur.com/3g2VfaM.png |
| 26 | + Yulewalk response: https://i.imgur.com/J9LnJ4C.png |
| 27 | + Butterworth and overall response: https://i.imgur.com/3g2VfaM.png |
| 28 | +
|
| 29 | + Images and original matlab implementation by David Robinson, 2001 |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__(self, samplerate: int = 44100) -> None: |
| 33 | + self.yulewalk_filter = IIRFilter(10) |
| 34 | + self.butterworth_filter = make_highpass(150, samplerate) |
| 35 | + |
| 36 | + # pad the data to nyquist |
| 37 | + curve_freqs = np.array(data["frequencies"] + [max(20000.0, samplerate / 2)]) |
| 38 | + curve_gains = np.array(data["gains"] + [140]) |
| 39 | + |
| 40 | + # Convert to angular frequency |
| 41 | + freqs_normalized = curve_freqs / samplerate * 2 |
| 42 | + # Invert the curve and normalize to 0dB |
| 43 | + gains_normalized = np.power(10, (np.min(curve_gains) - curve_gains) / 20) |
| 44 | + |
| 45 | + # Scipy's `yulewalk` function is a stub, so we're using the |
| 46 | + # `yulewalker` library instead. |
| 47 | + # This function computes the coefficients using a least-squares |
| 48 | + # fit to the specified curve. |
| 49 | + ya, yb = yulewalk(10, freqs_normalized, gains_normalized) |
| 50 | + self.yulewalk_filter.set_coefficients(ya, yb) |
| 51 | + |
| 52 | + def process(self, sample: float) -> float: |
| 53 | + """ |
| 54 | + Process a single sample through both filters |
| 55 | +
|
| 56 | + >>> filt = EqualLoudnessFilter() |
| 57 | + >>> filt.process(0.0) |
| 58 | + 0.0 |
| 59 | + """ |
| 60 | + tmp = self.yulewalk_filter.process(sample) |
| 61 | + return self.butterworth_filter.process(tmp) |
0 commit comments