Files

72 lines
3.1 KiB
Python

#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
"""The polyphase FIR of the USB audio input's 44.1 -> 48 kHz resampler (firmware/src/usb.c, FELUCCA_UAC_48K).
After Felucca 1.1.5's tools/gen_uac_fir.py (Leo Kuroshita), made smaller for SLOOP 2.5: 12 taps per phase in Q15
(1920 bytes of flash instead of 7680).
48000 / 44100 = 160 / 147: up by L = 160, low-pass, down by M = 147. Output frame k sits at input time
k * 147 / 160: phase p = (k * 147) % 160, newest input frame floor(k * 147 / 160). Each phase is N taps of
the prototype (a Kaiser-windowed sinc of 160 * N taps at 7.056 MHz, cut-off FC):
y[k] = sum_j PROTO[p + 160 j] * x[base - j], j = 0 .. N-1
The table holds the taps oldest input first, Q15, and only the phases 0 .. 79: the prototype is symmetric,
so phase 159 - p is phase p read backwards. Each phase's taps sum to exactly 1 << 15 (unity gain at DC).
Why these numbers (tests/uac_test.c measures them on the C code): N = 12, FC = 20 kHz, beta 7.5: images that
would fold into the audible band are down about 80 dB, the passband is flat to about 12 kHz (-1 dB at 16 kHz,
-2.7 dB at 18 kHz), the 1 kHz SNR is above 80 dB. For recording into a phone's sampler.
tools/gen_uac_fir.py [OUT] (default firmware/src/uac_fir.h); numpy only."""
import sys
from pathlib import Path
import numpy as np
L, M, N = 160, 147, 12
FC, BETA, QB = 20000.0, 7.5, 15
FS = 44100.0
def prototype():
n = L * N
t = np.arange(n) - (n - 1) / 2.0
fc = FC / (FS * L)
h = 2 * fc * np.sinc(2 * fc * t) * np.kaiser(n, BETA)
return h / h.sum() * L
def table():
h = prototype()
tab = np.zeros((L, N), dtype=np.int64)
for p in range(L):
c = h[p::L][::-1]
q = np.round(c * (1 << QB)).astype(np.int64)
q[np.argmax(np.abs(c))] += (1 << QB) - q.sum()
tab[p] = q
for p in range(L // 2):
assert np.abs(tab[L - 1 - p] - tab[p][::-1]).max() <= 1
assert np.abs(tab).max() < 32768 and np.abs(tab).sum(axis=1).max() < 2 * 32768 # (int32 sums in C)
return tab
def main():
out = Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).resolve().parents[1] / "firmware" / "src" / "uac_fir.h")
tab = table()
lines = [
"/* SPDX-License-Identifier: GPL-3.0-only */",
"/* generated by tools/gen_uac_fir.py: do not edit. The 44.1 -> 48 kHz polyphase FIR of the USB audio input",
f" * (usb.c): L {L}, M {M}, {N} taps per phase, Kaiser beta {BETA:g}, cut-off {FC:g} Hz, Q{QB}; phases 0..{L // 2 - 1}",
f" * (phase {L - 1} - p = phase p backwards), taps oldest input first. After Felucca 1.1.5 (24 taps, Q30). */",
f"#define UAC_FIR_L {L}u",
f"#define UAC_FIR_M {M}u",
f"#define UAC_FIR_N {N}u",
f"#define UAC_FIR_Q {QB}",
f"static const int16_t UAC_FIR[{L // 2}][{N}] = {{",
]
for p in range(L // 2):
lines.append(" {" + ", ".join(str(int(v)) for v in tab[p]) + "},")
lines.append("};")
out.write_text("\n".join(lines) + "\n")
print(f"wrote {out}: {L // 2} x {N} taps, {L // 2 * N * 2} B")
if __name__ == "__main__":
main()