|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from json import loads |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +from scipy.linalg import toeplitz |
| 8 | +from scipy.signal import lfilter, unit_impulse |
| 9 | + |
| 10 | +from audio_filters.butterworth_filter import make_highpass |
| 11 | +from audio_filters.iir_filter import IIRFilter |
| 12 | + |
| 13 | +data = loads((Path(__file__).resolve().parent / "loudness_curve.json").read_text()) |
| 14 | + |
| 15 | + |
| 16 | +def _polystab(poly: np.ndarray) -> np.ndarray: |
| 17 | + """ |
| 18 | + Stabilize a polynomial by reflecting any roots that lie outside the unit |
| 19 | + circle back inside it. This keeps the resulting IIR filter stable without |
| 20 | + changing its magnitude response. |
| 21 | +
|
| 22 | + https://en.wikipedia.org/wiki/Minimum_phase |
| 23 | +
|
| 24 | + >>> np.round(_polystab(np.array([1.0, 2.0, 1.0])), 6) |
| 25 | + array([1., 2., 1.]) |
| 26 | + >>> np.round(_polystab(np.array([1.0, 2.0, 1.01])), 6) |
| 27 | + array([1. , 1.980198, 0.990099]) |
| 28 | + """ |
| 29 | + if poly.size <= 1: |
| 30 | + return poly |
| 31 | + roots = np.roots(poly) |
| 32 | + nonzero = np.where(roots != 0)[0] |
| 33 | + outside = 0.5 * (np.sign(np.abs(roots[nonzero]) - 1) + 1) |
| 34 | + roots[nonzero] = (1 - outside) * roots[nonzero] + outside / np.conj(roots[nonzero]) |
| 35 | + stabilized = np.poly(roots) |
| 36 | + if not np.imag(poly).any(): |
| 37 | + stabilized = np.real(stabilized) |
| 38 | + return stabilized |
| 39 | + |
| 40 | + |
| 41 | +def _numerator( |
| 42 | + impulse_response: np.ndarray, denominator: np.ndarray, numerator_order: int |
| 43 | +) -> np.ndarray: |
| 44 | + """ |
| 45 | + Least-squares estimate of the numerator polynomial of a transfer function |
| 46 | + given its impulse response and (already known) denominator polynomial. |
| 47 | +
|
| 48 | + >>> num = _numerator(np.array([1.0, 0.0, 0.0]), np.array([1.0, 0.0, 0.0]), 1) |
| 49 | + >>> np.round(num, 6) |
| 50 | + array([1., 0.]) |
| 51 | + """ |
| 52 | + length = impulse_response.size |
| 53 | + impulse = lfilter([1.0], denominator.ravel(), unit_impulse(length)) |
| 54 | + toep = toeplitz(impulse, unit_impulse(numerator_order + 1)) |
| 55 | + return np.linalg.lstsq(toep.conj(), impulse_response.ravel().conj(), rcond=None)[ |
| 56 | + 0 |
| 57 | + ].conj() |
| 58 | + |
| 59 | + |
| 60 | +def yulewalk( |
| 61 | + order: int, frequencies: np.ndarray, magnitudes: np.ndarray, npt: int = 512 |
| 62 | +) -> tuple[np.ndarray, np.ndarray]: |
| 63 | + """ |
| 64 | + Design a recursive (IIR) digital filter that approximates an arbitrary |
| 65 | + frequency response using the modified Yule-Walker method. This is a |
| 66 | + dependency-free re-implementation of MATLAB/Octave's ``yulewalk`` so that |
| 67 | + the equal-loudness filter below no longer relies on a third-party package. |
| 68 | +
|
| 69 | + https://en.wikipedia.org/wiki/Autoregressive_model#Yule%E2%80%93Walker_equations |
| 70 | +
|
| 71 | + :param order: order of the filter to design |
| 72 | + :param frequencies: sample points on ``[0, 1]`` where 1 is the Nyquist |
| 73 | + frequency, in increasing order and starting at 0 |
| 74 | + :param magnitudes: desired (linear) magnitude at each point in ``frequencies`` |
| 75 | + :param npt: number of points used to estimate the frequency response |
| 76 | + :return: ``(a_coeffs, b_coeffs)``, the denominator and numerator polynomials |
| 77 | +
|
| 78 | + >>> a, b = yulewalk(4, np.array([0.0, 0.5, 1.0]), np.array([1.0, 0.5, 0.0])) |
| 79 | + >>> len(a), len(b) |
| 80 | + (5, 5) |
| 81 | + >>> bool(np.all(np.abs(np.roots(a)) < 1)) # the designed filter is stable |
| 82 | + True |
| 83 | +
|
| 84 | + Mismatched inputs and non-increasing frequencies are rejected: |
| 85 | +
|
| 86 | + >>> yulewalk(4, np.array([0.0, 1.0]), np.array([1.0])) |
| 87 | + Traceback (most recent call last): |
| 88 | + ... |
| 89 | + ValueError: frequencies and magnitudes must have the same length |
| 90 | + >>> yulewalk(4, np.array([0.0, 1.0, 0.5]), np.array([1.0, 0.5, 0.0])) |
| 91 | + Traceback (most recent call last): |
| 92 | + ... |
| 93 | + ValueError: frequencies must be in increasing order |
| 94 | + """ |
| 95 | + frequencies = np.asarray(frequencies, dtype=float).ravel() |
| 96 | + magnitudes = np.asarray(magnitudes, dtype=float).ravel() |
| 97 | + if frequencies.size != magnitudes.size: |
| 98 | + msg = "frequencies and magnitudes must have the same length" |
| 99 | + raise ValueError(msg) |
| 100 | + if np.any(np.diff(frequencies) < 0): |
| 101 | + msg = "frequencies must be in increasing order" |
| 102 | + raise ValueError(msg) |
| 103 | + |
| 104 | + npt = npt + 1 |
| 105 | + # Linearly interpolate the target response onto a dense grid, then mirror it |
| 106 | + # to build the full (symmetric) magnitude spectrum. |
| 107 | + response = np.interp(np.linspace(0, 1, npt), frequencies, magnitudes) |
| 108 | + response = np.concatenate([response, response[-2:0:-1]]) |
| 109 | + |
| 110 | + total = response.size |
| 111 | + half = (total + 1) // 2 |
| 112 | + window_len = 4 * order |
| 113 | + index = np.arange(window_len) |
| 114 | + |
| 115 | + # Autocorrelation from the power spectrum, tapered with a Hamming window. |
| 116 | + correlation = np.real(np.fft.ifft(response * response)) |
| 117 | + correlation = correlation[:window_len] * ( |
| 118 | + 0.54 + 0.46 * np.cos(np.pi * index / (window_len - 1)) |
| 119 | + ) |
| 120 | + cepstral_window = np.concatenate([[0.5], np.ones(half - 1), np.zeros(total - half)]) |
| 121 | + |
| 122 | + # Solve the Yule-Walker normal equations for the denominator coefficients. |
| 123 | + rmat = toeplitz(correlation[order : window_len - 1], correlation[order:0:-1]) |
| 124 | + rhs = -correlation[order + 1 : window_len] |
| 125 | + denominator = np.concatenate([[1.0], np.linalg.lstsq(rmat, rhs, rcond=None)[0]]) |
| 126 | + denominator = _polystab(denominator) |
| 127 | + |
| 128 | + half_correlation = correlation.copy() |
| 129 | + half_correlation[0] = correlation[0] / 2 |
| 130 | + numerator = _numerator(half_correlation, denominator, order) |
| 131 | + |
| 132 | + padded_num = np.zeros(total) |
| 133 | + padded_num[: numerator.size] = numerator |
| 134 | + padded_den = np.zeros(total) |
| 135 | + padded_den[: denominator.size] = denominator |
| 136 | + |
| 137 | + spectrum = 2 * np.real(np.fft.fft(padded_num) / np.fft.fft(padded_den)) |
| 138 | + complex_log = np.log(np.abs(spectrum)) + 1j * np.angle(spectrum) |
| 139 | + cepstrum = np.fft.ifft( |
| 140 | + np.exp(np.fft.fft(cepstral_window * np.fft.ifft(complex_log))) |
| 141 | + ) |
| 142 | + numerator = np.real(_numerator(cepstrum[:window_len], denominator, order)) |
| 143 | + return denominator, numerator |
| 144 | + |
| 145 | + |
| 146 | +class EqualLoudnessFilter: |
| 147 | + r""" |
| 148 | + An equal-loudness filter which compensates for the human ear's non-linear |
| 149 | + response to sound. This filter corrects this by cascading a Yule-Walker |
| 150 | + filter and a Butterworth filter. |
| 151 | +
|
| 152 | + Designed for use with samplerate of 44.1kHz and above. If you're using a |
| 153 | + lower samplerate, use with caution. |
| 154 | +
|
| 155 | + Code based on the matlab implementation at https://bit.ly/3eqh2HU |
| 156 | + (url shortened for ruff) |
| 157 | +
|
| 158 | + Target curve: https://i.imgur.com/3g2VfaM.png |
| 159 | + Yulewalk response: https://i.imgur.com/J9LnJ4C.png |
| 160 | + Butterworth and overall response: https://i.imgur.com/3g2VfaM.png |
| 161 | +
|
| 162 | + Images and original matlab implementation by David Robinson, 2001 |
| 163 | +
|
| 164 | + https://en.wikipedia.org/wiki/Equal-loudness_contour |
| 165 | +
|
| 166 | + >>> filt = EqualLoudnessFilter() |
| 167 | + >>> isinstance(filt.yulewalk_filter, IIRFilter) |
| 168 | + True |
| 169 | + """ |
| 170 | + |
| 171 | + def __init__(self, samplerate: int = 44100) -> None: |
| 172 | + self.yulewalk_filter = IIRFilter(10) |
| 173 | + self.butterworth_filter = make_highpass(150, samplerate) |
| 174 | + |
| 175 | + # pad the data to nyquist |
| 176 | + curve_freqs = np.array(data["frequencies"] + [max(20000.0, samplerate / 2)]) |
| 177 | + curve_gains = np.array(data["gains"] + [140]) |
| 178 | + |
| 179 | + # Convert to angular frequency |
| 180 | + freqs_normalized = curve_freqs / samplerate * 2 |
| 181 | + # Invert the curve and normalize to 0dB |
| 182 | + gains_normalized = np.power(10, (np.min(curve_gains) - curve_gains) / 20) |
| 183 | + |
| 184 | + # Compute the coefficients using a least-squares fit to the curve with |
| 185 | + # the built-in ``yulewalk`` implementation above (no third-party deps). |
| 186 | + ya, yb = yulewalk(10, freqs_normalized, gains_normalized) |
| 187 | + self.yulewalk_filter.set_coefficients(ya.tolist(), yb.tolist()) |
| 188 | + |
| 189 | + def process(self, sample: float) -> float: |
| 190 | + """ |
| 191 | + Process a single sample through both filters |
| 192 | +
|
| 193 | + >>> filt = EqualLoudnessFilter() |
| 194 | + >>> filt.process(0.0) |
| 195 | + 0.0 |
| 196 | + """ |
| 197 | + tmp = self.yulewalk_filter.process(sample) |
| 198 | + return self.butterworth_filter.process(tmp) |
0 commit comments