File size: 7,397 Bytes
0a46626 | 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | # SPDX-License-Identifier: Apache-2.0
"""Fast hn-NSF excitation for the device engine (numpy, float32): the same excitation as ``model.source`` (the
official op order, kept for the bit-exact ``noise=torch`` reference), computed block-wise:
* ``rad[k, h] = (F0[k] h / 24000) mod 1`` at 80 Hz is exact (ARCH 3.9);
* the 24 kHz phase in cycles, modulo 1: with ``d = (300 rad) mod 1`` and ``P = cumsum(d) mod 1`` (float64 prefix sum,
then wrapped), sample ``j = 300 k + r`` of block ``k`` is ``P[k-1] + w1_r 300 rad[k]`` (r < 150) or
``P[k] + w2_r 300 rad[k+1]`` (r >= 150), the official linear upsampling (align_corners False, clamped ends)
written per block; ``sin(2 pi frac(.))`` keeps the argument small (the official fp32 phase grows to ~1e5 rad);
* the 9 noise streams (``z`` [N, 9], the official layout) or the folded single stream (``z1`` [N]).
Measured vs the official op order: PCC 0.9999 (en_long), the difference being the official fp32 phase rounding.
"""
from __future__ import annotations
from typing import Optional
import numpy as np
SR, UP, H = 24000, 300, 9
SINE_AMP, NOISE_STD, VOICED = np.float32(0.1), np.float32(0.003), np.float32(10.0)
def excitation(F0: np.ndarray, lin_w: np.ndarray, lin_b: float, z: Optional[np.ndarray] = None,
z1: Optional[np.ndarray] = None) -> np.ndarray:
"""F0 [K] (80 Hz) -> har_source [300 K] float32"""
f0 = np.asarray(F0, np.float32)
K = f0.shape[0]
h = np.arange(1, H + 1, dtype=np.float32)
rad = np.mod(f0[:, None] * h / np.float32(SR), np.float32(1)) # [K, 9]
inc = np.float32(UP) * rad # 300 rad (unwrapped increments)
P = np.mod(np.cumsum(np.mod(inc.astype(np.float64), 1.0), axis=0), 1.0).astype(np.float32) # [K, 9]
r = np.arange(UP, dtype=np.float32)
half = UP // 2
w1 = (r[:half] + np.float32(0.5)) / np.float32(UP) + np.float32(0.5) # r < 150: between k-1 and k
w2 = (r[half:] + np.float32(0.5)) / np.float32(UP) - np.float32(0.5) # r >= 150: between k and k+1
c = np.empty((K, UP, H), np.float32)
Pm = np.concatenate([P[:1], P[:-1]])
incn = np.concatenate([inc[1:], inc[-1:]])
c[:, :half] = Pm[:, None, :] + w1[None, :, None] * inc[:, None, :]
c[:, half:] = P[:, None, :] + w2[None, :, None] * incn[:, None, :]
c[0, :half] = P[0][None, :] # clamped start (src < 0)
c[K - 1, half:] = P[K - 1][None, :] # clamped end (src > K - 1)
c -= np.floor(c)
s = np.sin(np.float32(2 * np.pi) * c).reshape(K * UP, H) * SINE_AMP
uv = np.repeat(f0 > VOICED, UP).astype(np.float32)
amp = uv * NOISE_STD + (1 - uv) * (SINE_AMP / np.float32(3))
lw = np.asarray(lin_w, np.float32)
x = (s @ lw) * uv + np.float32(lin_b)
if z is not None:
x += amp * (np.asarray(z, np.float32) @ lw)
elif z1 is not None:
x += amp * np.float32(np.linalg.norm(lw)) * np.asarray(z1, np.float32)
return np.tanh(x)
def excitation_torch(F0, lin_w, lin_b: float, z=None, z1=None):
""":func:`excitation` in torch (vectorised, multi-threaded; the engine's path): F0 [K] -> har_source [300 K]
float32 torch tensor. Same arithmetic (float32, float64 prefix sum), equal to the numpy version to ~1e-7."""
import torch
f0 = torch.as_tensor(F0, dtype=torch.float32)
K = f0.shape[0]
h = torch.arange(1, H + 1, dtype=torch.float32)
rad = torch.remainder(f0[:, None] * h / float(SR), 1.0) # [K, 9]
inc = float(UP) * rad
P = torch.remainder(torch.cumsum(torch.remainder(inc.double(), 1.0), 0), 1.0).float()
r = torch.arange(UP, dtype=torch.float32)
half = UP // 2
w1 = (r[:half] + 0.5) / float(UP) + 0.5
w2 = (r[half:] + 0.5) / float(UP) - 0.5
Pm = torch.cat([P[:1], P[:-1]])
incn = torch.cat([inc[1:], inc[-1:]])
c = torch.empty(K, UP, H)
c[:, :half] = Pm[:, None, :] + w1[None, :, None] * inc[:, None, :]
c[:, half:] = P[:, None, :] + w2[None, :, None] * incn[:, None, :]
c[0, :half] = P[0][None, :]
c[K - 1, half:] = P[K - 1][None, :]
c.sub_(torch.floor(c)).mul_(float(2 * np.pi)).sin_()
lw = torch.as_tensor(np.asarray(lin_w, np.float32))
s = c.view(K * UP, H) @ (lw * float(SINE_AMP))
uv = (f0 > float(VOICED)).float().repeat_interleave(UP)
amp = uv * float(NOISE_STD) + (1 - uv) * float(SINE_AMP / np.float32(3))
x = s * uv + float(lin_b)
if z is not None:
x += amp * (torch.as_tensor(z, dtype=torch.float32) @ lw)
elif z1 is not None:
x += amp * float(np.linalg.norm(np.asarray(lin_w, np.float32))) * torch.as_tensor(z1, dtype=torch.float32)
return torch.tanh(x)
# ---------------------------------------------------------------------------------------- STFT / iSTFT (n_fft 20)
# torch.stft / torch.istft with n_fft = 20 spend most of their time in per-frame FFT overhead (195 ms / 80 ms for
# 25 s of audio on the shared host); with 20-sample frames a dense DFT matrix is cheaper. Same definitions:
# periodic Hann window, center=True (reflect padding for the analysis), onesided, istft normalised by the overlapped
# squared window and trimmed by n_fft // 2 at both ends.
N_FFT, HOP, NB = 20, 5, 11
_n = np.arange(N_FFT)
_k = np.arange(NB)
WIN = (0.5 - 0.5 * np.cos(2 * np.pi * _n / N_FFT)).astype(np.float64)
_ang = 2 * np.pi * np.outer(_n, _k) / N_FFT # [20, 11]
DFT_RE = (np.cos(_ang) * WIN[:, None]).astype(np.float32) # windowed analysis
DFT_IM = (-np.sin(_ang) * WIN[:, None]).astype(np.float32)
_scale = np.full(NB, 2.0)
_scale[0] = _scale[-1] = 1.0 # DC and Nyquist counted once (even n_fft)
IDFT_RE = (np.cos(_ang.T) * _scale[:, None] / N_FFT * WIN[None, :]).astype(np.float32) # [11, 20], windowed synthesis
IDFT_IM = (-np.sin(_ang.T) * _scale[:, None] / N_FFT * WIN[None, :]).astype(np.float32)
def stft_fast(x: np.ndarray):
"""x [N] -> (magnitude [11, N / 5 + 1], phase [11, N / 5 + 1]) float32"""
x = np.asarray(x, np.float32)
xp = np.pad(x, (N_FFT // 2, N_FFT // 2), mode="reflect")
nfr = 1 + (xp.size - N_FFT) // HOP
fr = np.lib.stride_tricks.as_strided(xp, (nfr, N_FFT), (xp.strides[0] * HOP, xp.strides[0]))
re = fr @ DFT_RE
im = fr @ DFT_IM
return np.sqrt(re * re + im * im).T, np.arctan2(im, re).T
def istft_fast(mag: np.ndarray, phase: np.ndarray) -> np.ndarray:
"""(magnitude [11, F], phase [11, F]) -> audio [5 (F - 1)] float32 (torch.istft semantics, center=True)"""
re = (mag * np.cos(phase)).T.astype(np.float32) # [F, 11]
im = (mag * np.sin(phase)).T.astype(np.float32)
fr = re @ IDFT_RE + im @ IDFT_IM # [F, 20] windowed frames
F = fr.shape[0]
total = HOP * (F - 1) + N_FFT
y = np.zeros(total + HOP, np.float32)
env = np.zeros(total + HOP, np.float64)
w2 = WIN * WIN
blocks = y[: (F + 3) * HOP].reshape(F + 3, HOP)
eblocks = env[: (F + 3) * HOP].reshape(F + 3, HOP)
for q in range(N_FFT // HOP): # 4 overlapping quarters
blocks[q: q + F] += fr[:, q * HOP:(q + 1) * HOP]
eblocks[q: q + F] += w2[q * HOP:(q + 1) * HOP]
y = y[:total]
env = env[:total]
y = np.where(env > 1e-11, y / np.maximum(env, 1e-11), y)
return y[N_FFT // 2: total - N_FFT // 2].astype(np.float32)
|