Commit
·
b250889
1
Parent(s):
7c90e55
feat: modules folder to load the effects
Browse files- modules/functional.py +229 -0
- modules/fx.py +1061 -0
- modules/rt.py +150 -0
- modules/utils.py +64 -0
modules/functional.py
ADDED
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn.functional as F
|
3 |
+
from torchcomp import compexp_gain, db2amp
|
4 |
+
from torchlpc import sample_wise_lpc
|
5 |
+
from typing import List, Tuple, Union, Any, Optional
|
6 |
+
import math
|
7 |
+
|
8 |
+
|
9 |
+
def inv_22(a, b, c, d):
|
10 |
+
return torch.stack([d, -b, -c, a]).view(2, 2) / (a * d - b * c)
|
11 |
+
|
12 |
+
|
13 |
+
def eig_22(a, b, c, d):
|
14 |
+
# https://croninprojects.org/Vince/Geodesy/FindingEigenvectors.pdf
|
15 |
+
T = a + d
|
16 |
+
D = a * d - b * c
|
17 |
+
half_T = T * 0.5
|
18 |
+
root = torch.sqrt(half_T * half_T - D) # + 0j)
|
19 |
+
L = torch.stack([half_T + root, half_T - root])
|
20 |
+
|
21 |
+
y = (L - a) / b
|
22 |
+
# y = c / L
|
23 |
+
V = torch.stack([torch.ones_like(y), y])
|
24 |
+
return L, V / V.abs().square().sum(0).sqrt()
|
25 |
+
|
26 |
+
|
27 |
+
def fir(x, b):
|
28 |
+
padded = F.pad(x.reshape(-1, 1, x.size(-1)), (b.size(0) - 1, 0))
|
29 |
+
return F.conv1d(padded, b.flip(0).view(1, 1, -1)).view(*x.shape)
|
30 |
+
|
31 |
+
|
32 |
+
def allpole(x: torch.Tensor, a: torch.Tensor):
|
33 |
+
h = x.reshape(-1, x.shape[-1])
|
34 |
+
return sample_wise_lpc(
|
35 |
+
h,
|
36 |
+
a.broadcast_to(h.shape + a.shape),
|
37 |
+
).reshape(*x.shape)
|
38 |
+
|
39 |
+
|
40 |
+
def biquad(x: torch.Tensor, b0, b1, b2, a0, a1, a2):
|
41 |
+
b0 = b0 / a0
|
42 |
+
b1 = b1 / a0
|
43 |
+
b2 = b2 / a0
|
44 |
+
a1 = a1 / a0
|
45 |
+
a2 = a2 / a0
|
46 |
+
|
47 |
+
beta1 = b1 - b0 * a1
|
48 |
+
beta2 = b2 - b0 * a2
|
49 |
+
|
50 |
+
tmp = a1.square() - 4 * a2
|
51 |
+
if tmp < 0:
|
52 |
+
pole = 0.5 * (-a1 + 1j * torch.sqrt(-tmp))
|
53 |
+
u = -1j * x[..., :-1]
|
54 |
+
h = sample_wise_lpc(
|
55 |
+
u.reshape(-1, u.shape[-1]),
|
56 |
+
-pole.broadcast_to(u.shape).reshape(-1, u.shape[-1], 1),
|
57 |
+
).reshape(*u.shape)
|
58 |
+
h = (
|
59 |
+
h.real * (beta1 * pole.real / pole.imag + beta2 / pole.imag)
|
60 |
+
- beta1 * h.imag
|
61 |
+
)
|
62 |
+
else:
|
63 |
+
L, V = eig_22(-a1, -a2, torch.ones_like(a1), torch.zeros_like(a1))
|
64 |
+
inv_V = inv_22(*V.view(-1))
|
65 |
+
|
66 |
+
C = torch.stack([beta1, beta2]) @ V
|
67 |
+
|
68 |
+
# project input to eigen space
|
69 |
+
h = x[..., :-1].unsqueeze(-2) * inv_V[:, :1]
|
70 |
+
L = L.unsqueeze(-1).broadcast_to(h.shape)
|
71 |
+
|
72 |
+
h = (
|
73 |
+
sample_wise_lpc(h.reshape(-1, h.shape[-1]), -L.reshape(-1, L.shape[-1], 1))
|
74 |
+
.reshape(*h.shape)
|
75 |
+
.transpose(-2, -1)
|
76 |
+
) @ C
|
77 |
+
tmp = b0 * x
|
78 |
+
y = torch.cat([tmp[..., :1], h + tmp[..., 1:]], -1)
|
79 |
+
return y
|
80 |
+
|
81 |
+
|
82 |
+
def highpass_biquad_coef(
|
83 |
+
sample_rate: int,
|
84 |
+
cutoff_freq: torch.Tensor,
|
85 |
+
Q: torch.Tensor,
|
86 |
+
):
|
87 |
+
w0 = 2 * torch.pi * cutoff_freq / sample_rate
|
88 |
+
alpha = torch.sin(w0) / 2.0 / Q
|
89 |
+
|
90 |
+
b0 = (1 + torch.cos(w0)) / 2
|
91 |
+
b1 = -1 - torch.cos(w0)
|
92 |
+
b2 = b0
|
93 |
+
a0 = 1 + alpha
|
94 |
+
a1 = -2 * torch.cos(w0)
|
95 |
+
a2 = 1 - alpha
|
96 |
+
return b0, b1, b2, a0, a1, a2
|
97 |
+
|
98 |
+
|
99 |
+
def apply_biquad(bq):
|
100 |
+
return lambda waveform, *args, **kwargs: biquad(waveform, *bq(*args, **kwargs))
|
101 |
+
|
102 |
+
|
103 |
+
highpass_biquad = apply_biquad(highpass_biquad_coef)
|
104 |
+
|
105 |
+
|
106 |
+
def lowpass_biquad_coef(
|
107 |
+
sample_rate: int,
|
108 |
+
cutoff_freq: torch.Tensor,
|
109 |
+
Q: torch.Tensor,
|
110 |
+
):
|
111 |
+
w0 = 2 * torch.pi * cutoff_freq / sample_rate
|
112 |
+
alpha = torch.sin(w0) / 2 / Q
|
113 |
+
|
114 |
+
b0 = (1 - torch.cos(w0)) / 2
|
115 |
+
b1 = 1 - torch.cos(w0)
|
116 |
+
b2 = b0
|
117 |
+
a0 = 1 + alpha
|
118 |
+
a1 = -2 * torch.cos(w0)
|
119 |
+
a2 = 1 - alpha
|
120 |
+
return b0, b1, b2, a0, a1, a2
|
121 |
+
|
122 |
+
|
123 |
+
def equalizer_biquad_coef(
|
124 |
+
sample_rate: int,
|
125 |
+
center_freq: torch.Tensor,
|
126 |
+
gain: torch.Tensor,
|
127 |
+
Q: torch.Tensor,
|
128 |
+
):
|
129 |
+
|
130 |
+
w0 = 2 * torch.pi * center_freq / sample_rate
|
131 |
+
A = torch.exp(gain / 40.0 * math.log(10))
|
132 |
+
alpha = torch.sin(w0) / 2 / Q
|
133 |
+
|
134 |
+
b0 = 1 + alpha * A
|
135 |
+
b1 = -2 * torch.cos(w0)
|
136 |
+
b2 = 1 - alpha * A
|
137 |
+
|
138 |
+
a0 = 1 + alpha / A
|
139 |
+
a1 = -2 * torch.cos(w0)
|
140 |
+
a2 = 1 - alpha / A
|
141 |
+
return b0, b1, b2, a0, a1, a2
|
142 |
+
|
143 |
+
|
144 |
+
def lowshelf_biquad_coef(
|
145 |
+
sample_rate: int,
|
146 |
+
cutoff_freq: torch.Tensor,
|
147 |
+
gain: torch.Tensor,
|
148 |
+
Q: torch.Tensor,
|
149 |
+
):
|
150 |
+
|
151 |
+
w0 = 2 * torch.pi * cutoff_freq / sample_rate
|
152 |
+
A = torch.exp(gain / 40.0 * math.log(10))
|
153 |
+
alpha = torch.sin(w0) / 2 / Q
|
154 |
+
cosw0 = torch.cos(w0)
|
155 |
+
sqrtA = torch.sqrt(A)
|
156 |
+
|
157 |
+
b0 = A * (A + 1 - (A - 1) * cosw0 + 2 * alpha * sqrtA)
|
158 |
+
b1 = 2 * A * (A - 1 - (A + 1) * cosw0)
|
159 |
+
b2 = A * (A + 1 - (A - 1) * cosw0 - 2 * alpha * sqrtA)
|
160 |
+
|
161 |
+
a0 = A + 1 + (A - 1) * cosw0 + 2 * alpha * sqrtA
|
162 |
+
a1 = -2 * (A - 1 + (A + 1) * cosw0)
|
163 |
+
a2 = A + 1 + (A - 1) * cosw0 - 2 * alpha * sqrtA
|
164 |
+
|
165 |
+
return b0, b1, b2, a0, a1, a2
|
166 |
+
|
167 |
+
|
168 |
+
def highshelf_biquad_coef(
|
169 |
+
sample_rate: int,
|
170 |
+
cutoff_freq: torch.Tensor,
|
171 |
+
gain: torch.Tensor,
|
172 |
+
Q: torch.Tensor,
|
173 |
+
):
|
174 |
+
|
175 |
+
w0 = 2 * torch.pi * cutoff_freq / sample_rate
|
176 |
+
A = torch.exp(gain / 40.0 * math.log(10))
|
177 |
+
alpha = torch.sin(w0) / 2 / Q
|
178 |
+
cosw0 = torch.cos(w0)
|
179 |
+
sqrtA = torch.sqrt(A)
|
180 |
+
|
181 |
+
b0 = A * (A + 1 + (A - 1) * cosw0 + 2 * alpha * sqrtA)
|
182 |
+
b1 = -2 * A * (A - 1 + (A + 1) * cosw0)
|
183 |
+
b2 = A * (A + 1 + (A - 1) * cosw0 - 2 * alpha * sqrtA)
|
184 |
+
|
185 |
+
a0 = A + 1 - (A - 1) * cosw0 + 2 * alpha * sqrtA
|
186 |
+
a1 = 2 * (A - 1 - (A + 1) * cosw0)
|
187 |
+
a2 = A + 1 - (A - 1) * cosw0 - 2 * alpha * sqrtA
|
188 |
+
|
189 |
+
return b0, b1, b2, a0, a1, a2
|
190 |
+
|
191 |
+
|
192 |
+
highpass_biquad = apply_biquad(highpass_biquad_coef)
|
193 |
+
lowpass_biquad = apply_biquad(lowpass_biquad_coef)
|
194 |
+
highshelf_biquad = apply_biquad(highshelf_biquad_coef)
|
195 |
+
lowshelf_biquad = apply_biquad(lowshelf_biquad_coef)
|
196 |
+
equalizer_biquad = apply_biquad(equalizer_biquad_coef)
|
197 |
+
|
198 |
+
|
199 |
+
def avg(rms: torch.Tensor, avg_coef: torch.Tensor):
|
200 |
+
assert torch.all(avg_coef > 0) and torch.all(avg_coef <= 1)
|
201 |
+
|
202 |
+
h = rms * avg_coef
|
203 |
+
|
204 |
+
return sample_wise_lpc(
|
205 |
+
h,
|
206 |
+
(avg_coef - 1).broadcast_to(h.shape).unsqueeze(-1),
|
207 |
+
)
|
208 |
+
|
209 |
+
|
210 |
+
def avg_rms(audio: torch.Tensor, avg_coef) -> torch.Tensor:
|
211 |
+
return avg(audio.square().clamp_min(1e-8), avg_coef).sqrt()
|
212 |
+
|
213 |
+
|
214 |
+
def compressor_expander(
|
215 |
+
x: torch.Tensor,
|
216 |
+
avg_coef: Union[torch.Tensor, float],
|
217 |
+
cmp_th: Union[torch.Tensor, float],
|
218 |
+
cmp_ratio: Union[torch.Tensor, float],
|
219 |
+
exp_th: Union[torch.Tensor, float],
|
220 |
+
exp_ratio: Union[torch.Tensor, float],
|
221 |
+
at: Union[torch.Tensor, float],
|
222 |
+
rt: Union[torch.Tensor, float],
|
223 |
+
make_up: torch.Tensor,
|
224 |
+
lookahead_func=lambda x: x,
|
225 |
+
):
|
226 |
+
rms = avg_rms(x, avg_coef=avg_coef)
|
227 |
+
gain = compexp_gain(rms, cmp_th, cmp_ratio, exp_th, exp_ratio, at, rt)
|
228 |
+
gain = lookahead_func(gain)
|
229 |
+
return x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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from torch.nn.utils.parametrize import register_parametrization
|
5 |
+
from torchcomp import ms2coef, coef2ms, db2amp, amp2db
|
6 |
+
from torchaudio.transforms import Spectrogram, InverseSpectrogram
|
7 |
+
|
8 |
+
from typing import List, Tuple, Union, Any, Optional, Callable
|
9 |
+
import math
|
10 |
+
from torch_fftconv import fft_conv1d
|
11 |
+
from functools import reduce
|
12 |
+
|
13 |
+
from .functional import (
|
14 |
+
compressor_expander,
|
15 |
+
lowpass_biquad,
|
16 |
+
highpass_biquad,
|
17 |
+
equalizer_biquad,
|
18 |
+
lowshelf_biquad,
|
19 |
+
highshelf_biquad,
|
20 |
+
lowpass_biquad_coef,
|
21 |
+
highpass_biquad_coef,
|
22 |
+
highshelf_biquad_coef,
|
23 |
+
lowshelf_biquad_coef,
|
24 |
+
equalizer_biquad_coef,
|
25 |
+
)
|
26 |
+
from .utils import chain_functions
|
27 |
+
|
28 |
+
|
29 |
+
class Clip(nn.Module):
|
30 |
+
def __init__(self, max: Optional[float] = None, min: Optional[float] = None):
|
31 |
+
super().__init__()
|
32 |
+
self.min = min
|
33 |
+
self.max = max
|
34 |
+
|
35 |
+
def forward(self, x):
|
36 |
+
if self.min is not None:
|
37 |
+
x = torch.clip(x, min=self.min)
|
38 |
+
if self.max is not None:
|
39 |
+
x = torch.clip(x, max=self.max)
|
40 |
+
return x
|
41 |
+
|
42 |
+
|
43 |
+
def clip_delay_eq_Q(m: nn.Module, Q: float):
|
44 |
+
if isinstance(m, Delay) and isinstance(m.eq, LowPass):
|
45 |
+
register_parametrization(m.eq.params, "Q", Clip(max=Q))
|
46 |
+
return m
|
47 |
+
|
48 |
+
|
49 |
+
float2param = lambda x: nn.Parameter(
|
50 |
+
torch.tensor(x, dtype=torch.float32) if not isinstance(x, torch.Tensor) else x
|
51 |
+
)
|
52 |
+
|
53 |
+
STEREO_NORM = math.sqrt(2)
|
54 |
+
|
55 |
+
|
56 |
+
def broadcast2stereo(m, args):
|
57 |
+
x, *_ = args
|
58 |
+
return x.expand(-1, 2, -1) if x.shape[1] == 1 else x
|
59 |
+
|
60 |
+
|
61 |
+
hadamard = lambda x: torch.stack([x.sum(1), x[:, 0] - x[:, 1]], 1) / STEREO_NORM
|
62 |
+
|
63 |
+
|
64 |
+
class Hadamard(nn.Module):
|
65 |
+
def forward(self, x):
|
66 |
+
return hadamard(x)
|
67 |
+
|
68 |
+
|
69 |
+
class FX(nn.Module):
|
70 |
+
def __init__(self, **kwargs) -> None:
|
71 |
+
super().__init__()
|
72 |
+
|
73 |
+
self.params = nn.ParameterDict({k: float2param(v) for k, v in kwargs.items()})
|
74 |
+
|
75 |
+
def toJSON(self) -> dict[str, Any]:
|
76 |
+
return {k: v.item() for k, v in self.params.items() if v.numel() == 1}
|
77 |
+
|
78 |
+
|
79 |
+
class SmoothingCoef(nn.Module):
|
80 |
+
def forward(self, x):
|
81 |
+
return x.sigmoid()
|
82 |
+
|
83 |
+
def right_inverse(self, y):
|
84 |
+
return (y / (1 - y)).log()
|
85 |
+
|
86 |
+
|
87 |
+
class CompRatio(nn.Module):
|
88 |
+
def forward(self, x):
|
89 |
+
return x.exp() + 1
|
90 |
+
|
91 |
+
def right_inverse(self, y):
|
92 |
+
return torch.log(y - 1)
|
93 |
+
|
94 |
+
|
95 |
+
class MinMax(nn.Module):
|
96 |
+
def __init__(self, min=0.0, max: Union[float, torch.Tensor] = 1.0):
|
97 |
+
super().__init__()
|
98 |
+
if isinstance(min, torch.Tensor):
|
99 |
+
self.register_buffer("min", min, persistent=False)
|
100 |
+
else:
|
101 |
+
self.min = min
|
102 |
+
|
103 |
+
if isinstance(max, torch.Tensor):
|
104 |
+
self.register_buffer("max", max, persistent=False)
|
105 |
+
else:
|
106 |
+
self.max = max
|
107 |
+
|
108 |
+
self._m = SmoothingCoef()
|
109 |
+
|
110 |
+
def forward(self, x):
|
111 |
+
return self._m(x) * (self.max - self.min) + self.min
|
112 |
+
|
113 |
+
def right_inverse(self, y):
|
114 |
+
return self._m.right_inverse((y - self.min) / (self.max - self.min))
|
115 |
+
|
116 |
+
|
117 |
+
class WrappedPositive(nn.Module):
|
118 |
+
def __init__(self, period):
|
119 |
+
super().__init__()
|
120 |
+
self.period = period
|
121 |
+
|
122 |
+
def forward(self, x):
|
123 |
+
return x.abs() % self.period
|
124 |
+
|
125 |
+
def right_inverse(self, y):
|
126 |
+
return y
|
127 |
+
|
128 |
+
|
129 |
+
class CompressorExpander(FX):
|
130 |
+
cmp_ratio_min: float = 1
|
131 |
+
cmp_ratio_max: float = 20
|
132 |
+
|
133 |
+
def __init__(
|
134 |
+
self,
|
135 |
+
sr: int,
|
136 |
+
cmp_ratio: float = 2.0,
|
137 |
+
exp_ratio: float = 0.5,
|
138 |
+
at_ms: float = 50.0,
|
139 |
+
rt_ms: float = 50.0,
|
140 |
+
avg_coef: float = 0.3,
|
141 |
+
cmp_th: float = -18.0,
|
142 |
+
exp_th: float = -54.0,
|
143 |
+
make_up: float = 0.0,
|
144 |
+
delay: int = 0,
|
145 |
+
lookahead: bool = False,
|
146 |
+
max_lookahead: float = 15.0,
|
147 |
+
):
|
148 |
+
super().__init__(
|
149 |
+
cmp_th=cmp_th,
|
150 |
+
exp_th=exp_th,
|
151 |
+
make_up=make_up,
|
152 |
+
avg_coef=avg_coef,
|
153 |
+
cmp_ratio=cmp_ratio,
|
154 |
+
exp_ratio=exp_ratio,
|
155 |
+
)
|
156 |
+
# deprecated, please use lookahead instead
|
157 |
+
self.delay = delay
|
158 |
+
self.sr = sr
|
159 |
+
|
160 |
+
self.params["at"] = nn.Parameter(ms2coef(torch.tensor(at_ms), sr))
|
161 |
+
self.params["rt"] = nn.Parameter(ms2coef(torch.tensor(rt_ms), sr))
|
162 |
+
|
163 |
+
if lookahead:
|
164 |
+
self.params["lookahead"] = nn.Parameter(torch.ones(1) / sr * 1000)
|
165 |
+
register_parametrization(
|
166 |
+
self.params, "lookahead", WrappedPositive(max_lookahead)
|
167 |
+
)
|
168 |
+
sinc_length = int(sr * (max_lookahead + 1) * 0.001) + 1
|
169 |
+
left_pad_size = int(sr * 0.001)
|
170 |
+
self._pad_size = (left_pad_size, sinc_length - left_pad_size - 1)
|
171 |
+
self.register_buffer(
|
172 |
+
"_arange",
|
173 |
+
torch.arange(sinc_length) - left_pad_size,
|
174 |
+
persistent=False,
|
175 |
+
)
|
176 |
+
self.lookahead = lookahead
|
177 |
+
|
178 |
+
register_parametrization(self.params, "at", SmoothingCoef())
|
179 |
+
register_parametrization(self.params, "rt", SmoothingCoef())
|
180 |
+
register_parametrization(self.params, "avg_coef", SmoothingCoef())
|
181 |
+
register_parametrization(
|
182 |
+
self.params, "cmp_ratio", MinMax(self.cmp_ratio_min, self.cmp_ratio_max)
|
183 |
+
)
|
184 |
+
register_parametrization(self.params, "exp_ratio", SmoothingCoef())
|
185 |
+
|
186 |
+
def extra_repr(self) -> str:
|
187 |
+
with torch.no_grad():
|
188 |
+
s = (
|
189 |
+
f"attack: {coef2ms(self.params.at, self.sr).item()} (ms)\n"
|
190 |
+
f"release: {coef2ms(self.params.rt, self.sr).item()} (ms)\n"
|
191 |
+
f"avg_coef: {self.params.avg_coef.item()}\n"
|
192 |
+
f"compressor_ratio: {self.params.cmp_ratio.item()}\n"
|
193 |
+
f"expander_ratio: {self.params.exp_ratio.item()}\n"
|
194 |
+
f"compressor_threshold: {self.params.cmp_th.item()} (dB)\n"
|
195 |
+
f"expander_threshold: {self.params.exp_th.item()} (dB)\n"
|
196 |
+
f"make_up: {self.params.make_up.item()} (dB)"
|
197 |
+
)
|
198 |
+
if self.lookahead:
|
199 |
+
s += f"\nlookahead: {self.params.lookahead.item()} (ms)"
|
200 |
+
return s
|
201 |
+
|
202 |
+
def toJSON(self) -> dict[str, Any]:
|
203 |
+
return {
|
204 |
+
"Attack (ms)": coef2ms(self.params.at, self.sr).item(),
|
205 |
+
"Release (ms)": coef2ms(self.params.rt, self.sr).item(),
|
206 |
+
"Average Coefficient": self.params.avg_coef.item(),
|
207 |
+
"Compressor Ratio": self.params.cmp_ratio.item(),
|
208 |
+
"Expander Ratio": self.params.exp_ratio.item(),
|
209 |
+
"Compressor Threshold (dB)": self.params.cmp_th.item(),
|
210 |
+
"Expander Threshold (dB)": self.params.exp_th.item(),
|
211 |
+
"Make Up (dB)": self.params.make_up.item(),
|
212 |
+
} | ({"Lookahead (ms)": self.params.lookahead.item()} if self.lookahead else {})
|
213 |
+
|
214 |
+
def forward(self, x):
|
215 |
+
if self.lookahead:
|
216 |
+
lookahead_in_samples = self.params.lookahead * 0.001 * self.sr
|
217 |
+
sinc_filter = torch.sinc(self._arange - lookahead_in_samples)
|
218 |
+
lookahead_func = lambda gain: F.conv1d(
|
219 |
+
F.pad(
|
220 |
+
gain.view(-1, 1, gain.size(-1)), self._pad_size, mode="replicate"
|
221 |
+
),
|
222 |
+
sinc_filter[None, None, :],
|
223 |
+
).view(*gain.shape)
|
224 |
+
else:
|
225 |
+
lookahead_func = lambda x: x
|
226 |
+
|
227 |
+
return compressor_expander(
|
228 |
+
x.reshape(-1, x.shape[-1]),
|
229 |
+
lookahead_func=lookahead_func,
|
230 |
+
**{k: v for k, v in self.params.items() if k != "lookahead"},
|
231 |
+
).view(*x.shape)
|
232 |
+
|
233 |
+
|
234 |
+
class Panning(FX):
|
235 |
+
def __init__(self, pan: float = 0.0):
|
236 |
+
assert pan <= 100 and pan >= -100
|
237 |
+
super().__init__(pan=(pan + 100) / 200)
|
238 |
+
|
239 |
+
register_parametrization(self.params, "pan", SmoothingCoef())
|
240 |
+
|
241 |
+
self.register_forward_pre_hook(broadcast2stereo)
|
242 |
+
|
243 |
+
def extra_repr(self) -> str:
|
244 |
+
with torch.no_grad():
|
245 |
+
s = f"pan: {self.params.pan.item() * 200 - 100}"
|
246 |
+
return s
|
247 |
+
|
248 |
+
def toJSON(self) -> dict[str, Any]:
|
249 |
+
return {
|
250 |
+
"Pan": self.params.pan.item() * 200 - 100,
|
251 |
+
}
|
252 |
+
|
253 |
+
def forward(self, x: torch.Tensor):
|
254 |
+
angle = self.params.pan.view(1) * torch.pi * 0.5
|
255 |
+
amp = torch.concat([angle.cos(), angle.sin()]).view(2, 1) * STEREO_NORM
|
256 |
+
return x * amp
|
257 |
+
|
258 |
+
|
259 |
+
class StereoWidth(Panning):
|
260 |
+
def forward(self, x: torch.Tensor):
|
261 |
+
return chain_functions(hadamard, super().forward, hadamard)(x)
|
262 |
+
|
263 |
+
|
264 |
+
class ImpulseResponse(nn.Module):
|
265 |
+
def forward(self, h):
|
266 |
+
return torch.cat([torch.ones_like(h[..., :1]), h], dim=-1)
|
267 |
+
|
268 |
+
|
269 |
+
class FIR(FX):
|
270 |
+
def __init__(
|
271 |
+
self,
|
272 |
+
length: int,
|
273 |
+
channels: int = 2,
|
274 |
+
conv_method: str = "direct",
|
275 |
+
):
|
276 |
+
super().__init__(kernel=torch.zeros(channels, length - 1))
|
277 |
+
self._padding = length - 1
|
278 |
+
self.channels = channels
|
279 |
+
|
280 |
+
match conv_method:
|
281 |
+
case "direct":
|
282 |
+
self.conv_func = F.conv1d
|
283 |
+
case "fft":
|
284 |
+
self.conv_func = fft_conv1d
|
285 |
+
case _:
|
286 |
+
raise ValueError(f"Unknown conv_method: {conv_method}")
|
287 |
+
|
288 |
+
if channels == 2:
|
289 |
+
self.register_forward_pre_hook(broadcast2stereo)
|
290 |
+
|
291 |
+
def forward(self, x: torch.Tensor):
|
292 |
+
zero_padded = F.pad(x[..., :-1], (self._padding, 0), "constant", 0)
|
293 |
+
return x + self.conv_func(
|
294 |
+
zero_padded, self.params.kernel.flip(1).unsqueeze(1), groups=self.channels
|
295 |
+
)
|
296 |
+
|
297 |
+
|
298 |
+
class QFactor(nn.Module):
|
299 |
+
def forward(self, x):
|
300 |
+
return x.exp()
|
301 |
+
|
302 |
+
def right_inverse(self, y):
|
303 |
+
return y.log()
|
304 |
+
|
305 |
+
|
306 |
+
class LowPass(FX):
|
307 |
+
def __init__(
|
308 |
+
self,
|
309 |
+
sr: int,
|
310 |
+
freq: float = 17500.0,
|
311 |
+
Q: float = 0.707,
|
312 |
+
min_freq: float = 200.0,
|
313 |
+
max_freq: float = 18000,
|
314 |
+
min_Q: float = 0.5,
|
315 |
+
max_Q: float = 10.0,
|
316 |
+
):
|
317 |
+
super().__init__(freq=freq, Q=Q)
|
318 |
+
|
319 |
+
self.sr = sr
|
320 |
+
register_parametrization(self.params, "freq", MinMax(min_freq, max_freq))
|
321 |
+
register_parametrization(self.params, "Q", MinMax(min_Q, max_Q))
|
322 |
+
|
323 |
+
def forward(self, x):
|
324 |
+
return lowpass_biquad(
|
325 |
+
x, sample_rate=self.sr, cutoff_freq=self.params.freq, Q=self.params.Q
|
326 |
+
)
|
327 |
+
|
328 |
+
def extra_repr(self) -> str:
|
329 |
+
with torch.no_grad():
|
330 |
+
s = f"freq: {self.params.freq.item():.4f}, Q: {self.params.Q.item():.4f}"
|
331 |
+
return s
|
332 |
+
|
333 |
+
def toJSON(self) -> dict[str, Any]:
|
334 |
+
return {
|
335 |
+
"Frequency (Hz)": self.params.freq.item(),
|
336 |
+
"Q": self.params.Q.item(),
|
337 |
+
}
|
338 |
+
|
339 |
+
|
340 |
+
class HighPass(LowPass):
|
341 |
+
def __init__(
|
342 |
+
self,
|
343 |
+
*args,
|
344 |
+
freq: float = 200.0,
|
345 |
+
min_freq: float = 16.0,
|
346 |
+
max_freq: float = 5300.0,
|
347 |
+
**kwargs,
|
348 |
+
):
|
349 |
+
super().__init__(
|
350 |
+
*args, freq=freq, min_freq=min_freq, max_freq=max_freq, **kwargs
|
351 |
+
)
|
352 |
+
|
353 |
+
def forward(self, x):
|
354 |
+
return highpass_biquad(
|
355 |
+
x, sample_rate=self.sr, cutoff_freq=self.params.freq, Q=self.params.Q
|
356 |
+
)
|
357 |
+
|
358 |
+
|
359 |
+
class Peak(FX):
|
360 |
+
def __init__(
|
361 |
+
self,
|
362 |
+
sr: int,
|
363 |
+
gain: float = 0.0,
|
364 |
+
freq: float = 2000.0,
|
365 |
+
Q: float = 0.707,
|
366 |
+
min_freq: float = 33.0,
|
367 |
+
max_freq: float = 17500.0,
|
368 |
+
min_Q: float = 0.2,
|
369 |
+
max_Q: float = 20,
|
370 |
+
):
|
371 |
+
super().__init__(freq=freq, Q=Q, gain=gain)
|
372 |
+
|
373 |
+
self.sr = sr
|
374 |
+
|
375 |
+
register_parametrization(self.params, "freq", MinMax(min_freq, max_freq))
|
376 |
+
register_parametrization(self.params, "Q", MinMax(min_Q, max_Q))
|
377 |
+
|
378 |
+
def forward(self, x):
|
379 |
+
return equalizer_biquad(
|
380 |
+
x,
|
381 |
+
sample_rate=self.sr,
|
382 |
+
center_freq=self.params.freq,
|
383 |
+
Q=self.params.Q,
|
384 |
+
gain=self.params.gain,
|
385 |
+
)
|
386 |
+
|
387 |
+
def extra_repr(self) -> str:
|
388 |
+
with torch.no_grad():
|
389 |
+
s = f"freq: {self.params.freq.item():.4f}, gain: {self.params.gain.item():.4f}, Q: {self.params.Q.item():.4f}"
|
390 |
+
return s
|
391 |
+
|
392 |
+
def toJSON(self) -> dict[str, Any]:
|
393 |
+
return {
|
394 |
+
"Frequency (Hz)": self.params.freq.item(),
|
395 |
+
"Gain (dB)": self.params.gain.item(),
|
396 |
+
"Q": self.params.Q.item(),
|
397 |
+
}
|
398 |
+
|
399 |
+
|
400 |
+
class LowShelf(FX):
|
401 |
+
def __init__(
|
402 |
+
self,
|
403 |
+
sr: int,
|
404 |
+
gain: float = 0.0,
|
405 |
+
freq: float = 115.0,
|
406 |
+
min_freq: float = 30,
|
407 |
+
max_freq: float = 200,
|
408 |
+
):
|
409 |
+
super().__init__(freq=freq, gain=gain)
|
410 |
+
|
411 |
+
self.sr = sr
|
412 |
+
register_parametrization(self.params, "freq", MinMax(min_freq, max_freq))
|
413 |
+
|
414 |
+
self.register_buffer("Q", torch.tensor(0.707), persistent=False)
|
415 |
+
|
416 |
+
def forward(self, x):
|
417 |
+
return lowshelf_biquad(
|
418 |
+
x,
|
419 |
+
sample_rate=self.sr,
|
420 |
+
cutoff_freq=self.params.freq,
|
421 |
+
gain=self.params.gain,
|
422 |
+
Q=self.Q,
|
423 |
+
)
|
424 |
+
|
425 |
+
def extra_repr(self) -> str:
|
426 |
+
with torch.no_grad():
|
427 |
+
s = f"freq: {self.params.freq.item():.4f}, gain: {self.params.gain.item():.4f}"
|
428 |
+
return s
|
429 |
+
|
430 |
+
def toJSON(self) -> dict[str, Any]:
|
431 |
+
return {
|
432 |
+
"Frequency (Hz)": self.params.freq.item(),
|
433 |
+
"Gain (dB)": self.params.gain.item(),
|
434 |
+
}
|
435 |
+
|
436 |
+
|
437 |
+
class HighShelf(LowShelf):
|
438 |
+
def __init__(
|
439 |
+
self,
|
440 |
+
*args,
|
441 |
+
freq: float = 4525,
|
442 |
+
min_freq: float = 750,
|
443 |
+
max_freq: float = 8300,
|
444 |
+
**kwargs,
|
445 |
+
):
|
446 |
+
super().__init__(
|
447 |
+
*args, freq=freq, min_freq=min_freq, max_freq=max_freq, **kwargs
|
448 |
+
)
|
449 |
+
|
450 |
+
def forward(self, x):
|
451 |
+
return highshelf_biquad(
|
452 |
+
x,
|
453 |
+
sample_rate=self.sr,
|
454 |
+
cutoff_freq=self.params.freq,
|
455 |
+
gain=self.params.gain,
|
456 |
+
Q=self.Q,
|
457 |
+
)
|
458 |
+
|
459 |
+
|
460 |
+
def module2coeffs(
|
461 |
+
m: Union[LowPass, HighPass, Peak, LowShelf, HighShelf],
|
462 |
+
) -> Tuple[
|
463 |
+
torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor
|
464 |
+
]:
|
465 |
+
match m:
|
466 |
+
case LowPass():
|
467 |
+
return lowpass_biquad_coef(m.sr, m.params.freq, m.params.Q)
|
468 |
+
case HighPass():
|
469 |
+
return highpass_biquad_coef(m.sr, m.params.freq, m.params.Q)
|
470 |
+
case Peak():
|
471 |
+
return equalizer_biquad_coef(m.sr, m.params.freq, m.params.Q, m.params.gain)
|
472 |
+
case LowShelf():
|
473 |
+
return lowshelf_biquad_coef(m.sr, m.params.freq, m.params.gain, m.Q)
|
474 |
+
case HighShelf():
|
475 |
+
return highshelf_biquad_coef(m.sr, m.params.freq, m.params.gain, m.Q)
|
476 |
+
case _:
|
477 |
+
raise ValueError(f"Unknown module: {m}")
|
478 |
+
|
479 |
+
|
480 |
+
class AlwaysNegative(nn.Module):
|
481 |
+
def forward(self, x):
|
482 |
+
return -F.softplus(x)
|
483 |
+
|
484 |
+
def right_inverse(self, y):
|
485 |
+
return torch.log(y.neg().exp() - 1)
|
486 |
+
|
487 |
+
|
488 |
+
class Reverb(FX):
|
489 |
+
def __init__(self, ir_len=60000, n_fft=384, hop_length=192, downsample_factor=1):
|
490 |
+
super().__init__(
|
491 |
+
log_mag=torch.full((2, n_fft // downsample_factor // 2 + 1), -1.0),
|
492 |
+
log_mag_delta=torch.full((2, n_fft // downsample_factor // 2 + 1), -5.0),
|
493 |
+
)
|
494 |
+
|
495 |
+
self.steps = (ir_len - n_fft + hop_length - 1) // hop_length
|
496 |
+
self.n_fft = n_fft
|
497 |
+
self.hop_length = hop_length
|
498 |
+
self.downsample_factor = downsample_factor
|
499 |
+
|
500 |
+
self._noise_angle = nn.Parameter(
|
501 |
+
torch.rand(2, n_fft // 2 + 1, self.steps) * 2 * torch.pi
|
502 |
+
)
|
503 |
+
|
504 |
+
self.register_buffer(
|
505 |
+
"_arange", torch.arange(self.steps, dtype=torch.float32), persistent=False
|
506 |
+
)
|
507 |
+
self.spec_forward = Spectrogram(n_fft, hop_length=hop_length, power=None)
|
508 |
+
self.spec_inverse = InverseSpectrogram(
|
509 |
+
n_fft,
|
510 |
+
hop_length=hop_length,
|
511 |
+
)
|
512 |
+
|
513 |
+
register_parametrization(self.params, "log_mag", AlwaysNegative())
|
514 |
+
register_parametrization(self.params, "log_mag_delta", AlwaysNegative())
|
515 |
+
|
516 |
+
self.register_forward_pre_hook(broadcast2stereo)
|
517 |
+
|
518 |
+
def forward(self, x):
|
519 |
+
h = x
|
520 |
+
H = self.spec_forward(h)
|
521 |
+
|
522 |
+
log_mag = self.params.log_mag
|
523 |
+
log_mag_delta = self.params.log_mag_delta
|
524 |
+
|
525 |
+
if self.downsample_factor > 1:
|
526 |
+
log_mag = F.interpolate(
|
527 |
+
log_mag.unsqueeze(0),
|
528 |
+
size=self._noise_angle.size(1),
|
529 |
+
align_corners=True,
|
530 |
+
mode="linear",
|
531 |
+
).squeeze(0)
|
532 |
+
log_mag_delta = F.interpolate(
|
533 |
+
log_mag_delta.unsqueeze(0),
|
534 |
+
size=self._noise_angle.size(1),
|
535 |
+
align_corners=True,
|
536 |
+
mode="linear",
|
537 |
+
).squeeze(0)
|
538 |
+
|
539 |
+
ir_2d = torch.exp(
|
540 |
+
log_mag.unsqueeze(-1)
|
541 |
+
+ log_mag_delta.unsqueeze(-1) * self._arange
|
542 |
+
+ self._noise_angle * 1j
|
543 |
+
)
|
544 |
+
|
545 |
+
padded_H = F.pad(H.flatten(1, 2), (ir_2d.shape[-1] - 1, 0))
|
546 |
+
|
547 |
+
H = F.conv1d(
|
548 |
+
padded_H,
|
549 |
+
hadamard(ir_2d.unsqueeze(0)).flatten(1, 2).flip(-1).transpose(0, 1),
|
550 |
+
groups=H.shape[2] * 2,
|
551 |
+
).view(*H.shape)
|
552 |
+
|
553 |
+
h = self.spec_inverse(H)
|
554 |
+
return h
|
555 |
+
|
556 |
+
|
557 |
+
class Delay(FX):
|
558 |
+
min_delay: float = 100
|
559 |
+
max_delay: float = 1000
|
560 |
+
|
561 |
+
def __init__(
|
562 |
+
self,
|
563 |
+
sr: int,
|
564 |
+
delay=200.0,
|
565 |
+
feedback=0.1,
|
566 |
+
gain=0.1,
|
567 |
+
ir_duration: float = 2,
|
568 |
+
eq: Optional[nn.Module] = None,
|
569 |
+
recursive_eq=False,
|
570 |
+
):
|
571 |
+
super().__init__(
|
572 |
+
delay=delay,
|
573 |
+
feedback=feedback,
|
574 |
+
gain=gain,
|
575 |
+
)
|
576 |
+
self.sr = sr
|
577 |
+
self.ir_length = int(sr * max(ir_duration, self.max_delay * 0.002))
|
578 |
+
|
579 |
+
register_parametrization(
|
580 |
+
self.params, "delay", MinMax(self.min_delay, self.max_delay)
|
581 |
+
)
|
582 |
+
register_parametrization(self.params, "feedback", SmoothingCoef())
|
583 |
+
register_parametrization(self.params, "gain", SmoothingCoef())
|
584 |
+
|
585 |
+
self.eq = eq
|
586 |
+
self.recursive_eq = recursive_eq
|
587 |
+
|
588 |
+
self.register_buffer(
|
589 |
+
"_arange", torch.arange(self.ir_length, dtype=torch.float32)
|
590 |
+
)
|
591 |
+
|
592 |
+
self.odd_pan = Panning(0)
|
593 |
+
self.even_pan = Panning(0)
|
594 |
+
|
595 |
+
def forward(self, x):
|
596 |
+
assert x.size(1) == 1, x.size()
|
597 |
+
delay_in_samples = self.sr * self.params.delay * 0.001
|
598 |
+
num_delays = self.ir_length // int(delay_in_samples.item() + 1)
|
599 |
+
series = torch.arange(1, num_delays + 1, device=x.device)
|
600 |
+
decays = self.params.feedback ** (series - 1)
|
601 |
+
|
602 |
+
if self.recursive_eq and self.eq is not None:
|
603 |
+
sinc_index = self._arange - delay_in_samples
|
604 |
+
single_sinc_filter = torch.sinc(sinc_index)
|
605 |
+
eq_sinc_filter = self.eq(single_sinc_filter)
|
606 |
+
H = torch.fft.rfft(eq_sinc_filter)
|
607 |
+
H_powered = torch.polar(
|
608 |
+
H.abs() ** series.unsqueeze(-1), H.angle() * series.unsqueeze(-1)
|
609 |
+
)
|
610 |
+
sinc_filters = torch.fft.irfft(H_powered, n=self.ir_length)
|
611 |
+
else:
|
612 |
+
delays_in_samples = delay_in_samples * series
|
613 |
+
sinc_indexes = self._arange - delays_in_samples.unsqueeze(-1)
|
614 |
+
sinc_filters = torch.sinc(sinc_indexes)
|
615 |
+
|
616 |
+
decayed_sinc_filters = sinc_filters * decays.unsqueeze(-1)
|
617 |
+
return self._filter(x, decayed_sinc_filters)
|
618 |
+
|
619 |
+
def _filter(self, x: torch.Tensor, decayed_sinc_filters: torch.Tensor):
|
620 |
+
odd_delay_filters = torch.sum(decayed_sinc_filters[::2], 0)
|
621 |
+
even_delay_filters = torch.sum(decayed_sinc_filters[1::2], 0)
|
622 |
+
stacked_filters = torch.stack([odd_delay_filters, even_delay_filters])
|
623 |
+
|
624 |
+
if self.eq is not None and not self.recursive_eq:
|
625 |
+
stacked_filters = self.eq(stacked_filters)
|
626 |
+
|
627 |
+
gained_odd_even_filters = stacked_filters * self.params.gain
|
628 |
+
padded_x = F.pad(x, (gained_odd_even_filters.size(-1) - 1, 0))
|
629 |
+
conv1d = F.conv1d if x.size(-1) > 44100 * 20 else fft_conv1d
|
630 |
+
return sum(
|
631 |
+
[
|
632 |
+
panner(s)
|
633 |
+
for panner, s in zip(
|
634 |
+
[self.odd_pan, self.even_pan],
|
635 |
+
# fft_conv1d(
|
636 |
+
conv1d(
|
637 |
+
padded_x,
|
638 |
+
gained_odd_even_filters.flip(-1).unsqueeze(1),
|
639 |
+
).chunk(2, 1),
|
640 |
+
)
|
641 |
+
]
|
642 |
+
)
|
643 |
+
|
644 |
+
def extra_repr(self) -> str:
|
645 |
+
with torch.no_grad():
|
646 |
+
s = (
|
647 |
+
f"delay: {self.sr * self.params.delay.item() * 0.001} (samples)\n"
|
648 |
+
f"feedback: {self.params.feedback.item()}\n"
|
649 |
+
f"gain: {self.params.gain.item()}"
|
650 |
+
)
|
651 |
+
return s
|
652 |
+
|
653 |
+
def toJSON(self) -> dict[str, Any]:
|
654 |
+
return {
|
655 |
+
"Delay (ms)": self.params.delay.item(),
|
656 |
+
"Feedback (dB)": self.params.feedback.log10().mul(20).item(),
|
657 |
+
"Gain (dB)": self.params.gain.log10().mul(20).item(),
|
658 |
+
"Odd delays": self.odd_pan.toJSON(),
|
659 |
+
"Even delays": self.even_pan.toJSON(),
|
660 |
+
}
|
661 |
+
|
662 |
+
|
663 |
+
class SurrogateDelay(Delay):
|
664 |
+
def __init__(self, *args, dropout=0.5, straight_through=False, **kwargs):
|
665 |
+
super().__init__(*args, **kwargs)
|
666 |
+
|
667 |
+
self.dropout = dropout
|
668 |
+
self.straight_through = straight_through
|
669 |
+
self.log_damp = nn.Parameter(torch.ones(1) * -0.01)
|
670 |
+
register_parametrization(self, "log_damp", AlwaysNegative())
|
671 |
+
|
672 |
+
def forward(self, x):
|
673 |
+
assert x.size(1) == 1, x.size()
|
674 |
+
if not self.training:
|
675 |
+
return super().forward(x)
|
676 |
+
|
677 |
+
log_damp = self.log_damp
|
678 |
+
delay_in_samples = self.sr * self.params.delay * 0.001
|
679 |
+
num_delays = self.ir_length // int(delay_in_samples.item() + 1)
|
680 |
+
series = torch.arange(1, num_delays + 1, device=x.device)
|
681 |
+
decays = self.params.feedback ** (series - 1)
|
682 |
+
|
683 |
+
if self.recursive_eq and self.eq is not None:
|
684 |
+
exp_factor = self._arange[: self.ir_length // 2 + 1]
|
685 |
+
damped_exp = torch.exp(
|
686 |
+
log_damp * exp_factor
|
687 |
+
- 1j * delay_in_samples / self.ir_length * 2 * torch.pi * exp_factor
|
688 |
+
)
|
689 |
+
sinc_filter = torch.fft.irfft(damped_exp, n=self.ir_length)
|
690 |
+
if self.straight_through:
|
691 |
+
sinc_index = self._arange - delay_in_samples
|
692 |
+
hard_sinc_filter = torch.sinc(sinc_index)
|
693 |
+
sinc_filter = sinc_filter + (hard_sinc_filter - sinc_filter).detach()
|
694 |
+
|
695 |
+
eq_sinc_filter = self.eq(sinc_filter)
|
696 |
+
H = torch.fft.rfft(eq_sinc_filter)
|
697 |
+
|
698 |
+
# use polar form to avoid NaN
|
699 |
+
H_powered = torch.polar(
|
700 |
+
H.abs() ** series.unsqueeze(-1), H.angle() * series.unsqueeze(-1)
|
701 |
+
)
|
702 |
+
sinc_filters = torch.fft.irfft(H_powered, n=self.ir_length)
|
703 |
+
else:
|
704 |
+
exp_factors = series.unsqueeze(-1) * self._arange[: self.ir_length // 2 + 1]
|
705 |
+
damped_exps = torch.exp(
|
706 |
+
log_damp * exp_factors
|
707 |
+
- 1j * delay_in_samples / self.ir_length * 2 * torch.pi * exp_factors
|
708 |
+
)
|
709 |
+
sinc_filters = torch.fft.irfft(damped_exps, n=self.ir_length)
|
710 |
+
if self.straight_through:
|
711 |
+
delays_in_samples = delay_in_samples * series
|
712 |
+
sinc_indexes = self._arange - delays_in_samples.unsqueeze(-1)
|
713 |
+
hard_sinc_filters = torch.sinc(sinc_indexes)
|
714 |
+
sinc_filters = (
|
715 |
+
sinc_filters + (hard_sinc_filters - sinc_filters).detach()
|
716 |
+
)
|
717 |
+
|
718 |
+
decayed_sinc_filters = sinc_filters * decays.unsqueeze(-1)
|
719 |
+
|
720 |
+
dropout_mask = torch.rand(x.size(0), device=x.device) < self.dropout
|
721 |
+
if not torch.any(dropout_mask):
|
722 |
+
return self._filter(x, decayed_sinc_filters)
|
723 |
+
elif torch.all(dropout_mask):
|
724 |
+
return super().forward(x)
|
725 |
+
|
726 |
+
out = torch.zeros((x.size(0), 2, x.size(2)), device=x.device)
|
727 |
+
out[~dropout_mask] = self._filter(x[~dropout_mask], decayed_sinc_filters)
|
728 |
+
out[dropout_mask] = super().forward(x[dropout_mask])
|
729 |
+
return out
|
730 |
+
|
731 |
+
def extra_repr(self) -> str:
|
732 |
+
with torch.no_grad():
|
733 |
+
return super().extra_repr() + f"\ndamp: {self.log_damp.exp().item()}"
|
734 |
+
|
735 |
+
|
736 |
+
class FSDelay(FX):
|
737 |
+
def __init__(
|
738 |
+
self,
|
739 |
+
sr: int,
|
740 |
+
delay=200.0,
|
741 |
+
feedback=0.1,
|
742 |
+
gain=0.1,
|
743 |
+
ir_duration: float = 6,
|
744 |
+
eq: Optional[LowPass] = None,
|
745 |
+
recursive_eq=False,
|
746 |
+
):
|
747 |
+
super().__init__(
|
748 |
+
delay=delay,
|
749 |
+
feedback=feedback,
|
750 |
+
gain=gain,
|
751 |
+
)
|
752 |
+
self.sr = sr
|
753 |
+
self.ir_length = int(sr * max(ir_duration, Delay.max_delay * 0.002))
|
754 |
+
|
755 |
+
register_parametrization(
|
756 |
+
self.params, "delay", MinMax(Delay.min_delay, Delay.max_delay)
|
757 |
+
)
|
758 |
+
register_parametrization(self.params, "gain", SmoothingCoef())
|
759 |
+
|
760 |
+
T_60 = ir_duration * 0.75
|
761 |
+
max_delay_in_samples = sr * Delay.max_delay * 0.001
|
762 |
+
maximum_decay = db2amp(torch.tensor(-60 / sr / T_60 * max_delay_in_samples))
|
763 |
+
register_parametrization(self.params, "feedback", MinMax(0, maximum_decay))
|
764 |
+
|
765 |
+
self.eq = eq
|
766 |
+
self.recursive_eq = recursive_eq
|
767 |
+
|
768 |
+
self.odd_pan = Panning(0)
|
769 |
+
self.even_pan = Panning(0)
|
770 |
+
|
771 |
+
self.register_buffer(
|
772 |
+
"_arange", torch.arange(self.ir_length, dtype=torch.float32)
|
773 |
+
)
|
774 |
+
|
775 |
+
def _get_h(self):
|
776 |
+
freqs = self._arange[: self.ir_length // 2 + 1] / self.ir_length * 2 * torch.pi
|
777 |
+
delay_in_samples = self.sr * self.params.delay * 0.001
|
778 |
+
|
779 |
+
# construct it like a fdn
|
780 |
+
Dinv = torch.exp(1j * freqs * delay_in_samples)
|
781 |
+
Dinv2 = torch.exp(2j * freqs * delay_in_samples)
|
782 |
+
if self.recursive_eq and self.eq is not None:
|
783 |
+
b0, b1, b2, a0, a1, a2 = module2coeffs(self.eq)
|
784 |
+
z_inv = torch.exp(-1j * freqs)
|
785 |
+
z_inv2 = torch.exp(-2j * freqs)
|
786 |
+
eq_H = (b0 + b1 * z_inv + b2 * z_inv2) / (a0 + a1 * z_inv + a2 * z_inv2)
|
787 |
+
damp = eq_H * self.params.feedback
|
788 |
+
det = Dinv2 - damp * damp
|
789 |
+
else:
|
790 |
+
damp = torch.full_like(Dinv, self.params.feedback) + 0j
|
791 |
+
det = Dinv2 - self.params.feedback.square()
|
792 |
+
inv_Dinv_m_A = torch.stack([Dinv, damp], 0) / det
|
793 |
+
h = torch.fft.irfft(inv_Dinv_m_A, n=self.ir_length) * self.params.gain
|
794 |
+
|
795 |
+
if self.eq is not None and not self.recursive_eq:
|
796 |
+
h = self.eq(h)
|
797 |
+
return h
|
798 |
+
|
799 |
+
def forward(self, x):
|
800 |
+
assert x.size(1) == 1, x.size()
|
801 |
+
h = self._get_h()
|
802 |
+
|
803 |
+
padded_x = F.pad(x, (h.size(-1) - 1, 0))
|
804 |
+
conv1d = F.conv1d if x.size(-1) > 44100 * 20 else fft_conv1d
|
805 |
+
return sum(
|
806 |
+
[
|
807 |
+
panner(s)
|
808 |
+
for panner, s in zip(
|
809 |
+
[self.odd_pan, self.even_pan],
|
810 |
+
conv1d(
|
811 |
+
padded_x,
|
812 |
+
h.flip(-1).unsqueeze(1),
|
813 |
+
).chunk(2, 1),
|
814 |
+
)
|
815 |
+
]
|
816 |
+
)
|
817 |
+
|
818 |
+
def extra_repr(self) -> str:
|
819 |
+
with torch.no_grad():
|
820 |
+
s = (
|
821 |
+
f"delay: {self.sr * self.params.delay.item() * 0.001} (samples)\n"
|
822 |
+
f"feedback: {self.params.feedback.item()}\n"
|
823 |
+
f"gain: {self.params.gain.item()}"
|
824 |
+
)
|
825 |
+
return s
|
826 |
+
|
827 |
+
|
828 |
+
class FSSurrogateDelay(FSDelay):
|
829 |
+
def __init__(self, *args, straight_through=False, **kwargs):
|
830 |
+
super().__init__(*args, **kwargs)
|
831 |
+
|
832 |
+
self.straight_through = straight_through
|
833 |
+
self.log_damp = nn.Parameter(torch.ones(1) * -0.0001)
|
834 |
+
register_parametrization(self, "log_damp", AlwaysNegative())
|
835 |
+
|
836 |
+
def _get_h(self):
|
837 |
+
if not self.training:
|
838 |
+
return super()._get_h()
|
839 |
+
|
840 |
+
log_damp = self.log_damp
|
841 |
+
delay_in_samples = self.sr * self.params.delay * 0.001
|
842 |
+
|
843 |
+
exp_factor = self._arange[: self.ir_length // 2 + 1]
|
844 |
+
freqs = exp_factor / self.ir_length * 2 * torch.pi
|
845 |
+
D = torch.exp(log_damp * exp_factor - 1j * delay_in_samples * freqs)
|
846 |
+
D2 = torch.exp(log_damp * exp_factor * 2 - 2j * delay_in_samples * freqs)
|
847 |
+
|
848 |
+
if self.straight_through:
|
849 |
+
D_orig = torch.exp(-1j * delay_in_samples * freqs)
|
850 |
+
D2_orig = torch.exp(-2j * delay_in_samples * freqs)
|
851 |
+
D = torch.stack([D, D_orig], 0)
|
852 |
+
D2 = torch.stack([D2, D2_orig], 0)
|
853 |
+
|
854 |
+
if self.recursive_eq and self.eq is not None:
|
855 |
+
b0, b1, b2, a0, a1, a2 = module2coeffs(self.eq)
|
856 |
+
z_inv = torch.exp(-1j * freqs)
|
857 |
+
z_inv2 = torch.exp(-2j * freqs)
|
858 |
+
eq_H = (b0 + b1 * z_inv + b2 * z_inv2) / (a0 + a1 * z_inv + a2 * z_inv2)
|
859 |
+
damp = eq_H * self.params.feedback
|
860 |
+
odd_H = D / (1 - damp * damp * D2)
|
861 |
+
even_H = odd_H * D * damp
|
862 |
+
else:
|
863 |
+
damp = torch.full_like(D, self.params.feedback) + 0j
|
864 |
+
odd_H = D / (1 - self.params.feedback.square() * D2)
|
865 |
+
even_H = odd_H * D * self.params.feedback
|
866 |
+
|
867 |
+
inv_Dinv_m_A = torch.stack([odd_H, even_H], 0)
|
868 |
+
h = torch.fft.irfft(inv_Dinv_m_A, n=self.ir_length)
|
869 |
+
|
870 |
+
if self.straight_through:
|
871 |
+
damped_h, orig_h = h.unbind(1)
|
872 |
+
h = damped_h + (orig_h - damped_h).detach()
|
873 |
+
|
874 |
+
if self.eq is not None and not self.recursive_eq:
|
875 |
+
h = self.eq(h)
|
876 |
+
return h * self.params.gain
|
877 |
+
|
878 |
+
def extra_repr(self) -> str:
|
879 |
+
with torch.no_grad():
|
880 |
+
return super().extra_repr() + f"\ndamp: {self.log_damp.exp().item()}"
|
881 |
+
|
882 |
+
|
883 |
+
class SendFXsAndSum(FX):
|
884 |
+
def __init__(self, *args, cross_send=True, pan_direct=False):
|
885 |
+
super().__init__(
|
886 |
+
**(
|
887 |
+
{
|
888 |
+
f"sends_{i}": torch.full([len(args) - i - 1], 0.01)
|
889 |
+
for i in range(len(args) - 1)
|
890 |
+
}
|
891 |
+
if cross_send
|
892 |
+
else {}
|
893 |
+
)
|
894 |
+
)
|
895 |
+
self.effects = nn.ModuleList(args)
|
896 |
+
if pan_direct:
|
897 |
+
self.pan = Panning()
|
898 |
+
|
899 |
+
if cross_send:
|
900 |
+
for i in range(len(args) - 1):
|
901 |
+
register_parametrization(self.params, f"sends_{i}", SmoothingCoef())
|
902 |
+
|
903 |
+
def forward(self, x):
|
904 |
+
if hasattr(self, "pan"):
|
905 |
+
di = self.pan(x)
|
906 |
+
else:
|
907 |
+
di = x
|
908 |
+
|
909 |
+
if len(self.params) == 0:
|
910 |
+
return di, reduce(
|
911 |
+
lambda x, y: x[..., : y.shape[-1]] + y[..., : x.shape[-1]],
|
912 |
+
map(lambda f: f(x), self.effects),
|
913 |
+
)
|
914 |
+
|
915 |
+
def f(states, ps):
|
916 |
+
x, cum_sends = states
|
917 |
+
m, send_gains = ps
|
918 |
+
h = m(cum_sends[0])
|
919 |
+
return (
|
920 |
+
x[..., : h.shape[-1]] + h[..., : x.shape[-1]],
|
921 |
+
(
|
922 |
+
None
|
923 |
+
if cum_sends.size(0) == 1
|
924 |
+
else cum_sends[1:, ..., : h.shape[-1]]
|
925 |
+
+ send_gains[:, None, None, None] * h[..., : cum_sends.shape[-1]]
|
926 |
+
),
|
927 |
+
)
|
928 |
+
|
929 |
+
return (
|
930 |
+
di,
|
931 |
+
reduce(
|
932 |
+
f,
|
933 |
+
zip(
|
934 |
+
self.effects,
|
935 |
+
[self.params[f"sends_{i}"] for i in range(len(self.effects) - 1)]
|
936 |
+
+ [None],
|
937 |
+
),
|
938 |
+
(
|
939 |
+
torch.zeros_like(x),
|
940 |
+
x.unsqueeze(0).expand(len(self.effects), -1, -1, -1),
|
941 |
+
),
|
942 |
+
)[0],
|
943 |
+
)
|
944 |
+
|
945 |
+
|
946 |
+
class UniLossLess(nn.Module):
|
947 |
+
def forward(self, x):
|
948 |
+
tri = x.triu(1)
|
949 |
+
return torch.linalg.matrix_exp(tri - tri.T)
|
950 |
+
|
951 |
+
|
952 |
+
class FDN(FX):
|
953 |
+
max_delay = 100
|
954 |
+
|
955 |
+
def __init__(
|
956 |
+
self,
|
957 |
+
sr: int,
|
958 |
+
ir_duration: float = 1.0,
|
959 |
+
delays=(997, 1153, 1327, 1559, 1801, 2099),
|
960 |
+
trainable_delay=False,
|
961 |
+
num_decay_freq=1,
|
962 |
+
delay_independent_decay=False,
|
963 |
+
eq: Optional[nn.Module] = None,
|
964 |
+
):
|
965 |
+
# beta = torch.distributions.Beta(1.1, 6)
|
966 |
+
num_delays = len(delays)
|
967 |
+
super().__init__(
|
968 |
+
b=torch.ones(num_delays, 2) / num_delays,
|
969 |
+
c=torch.zeros(2, num_delays),
|
970 |
+
U=torch.randn(num_delays, num_delays) / num_delays**0.5,
|
971 |
+
gamma=torch.rand(
|
972 |
+
num_decay_freq, num_delays if not delay_independent_decay else 1
|
973 |
+
)
|
974 |
+
* 0.2
|
975 |
+
+ 0.4,
|
976 |
+
# delays=beta.sample((num_delays,)) * 64,
|
977 |
+
)
|
978 |
+
|
979 |
+
self.sr = sr
|
980 |
+
self.ir_length = int(sr * ir_duration)
|
981 |
+
|
982 |
+
# ir_duration = T_60
|
983 |
+
T_60 = ir_duration * 0.75
|
984 |
+
delays = torch.tensor(delays)
|
985 |
+
if delay_independent_decay:
|
986 |
+
gamma_max = db2amp(-60 / sr / T_60 * delays.min())
|
987 |
+
else:
|
988 |
+
gamma_max = db2amp(-60 / sr / T_60 * delays)
|
989 |
+
|
990 |
+
register_parametrization(self.params, "gamma", MinMax(0, gamma_max))
|
991 |
+
register_parametrization(self.params, "U", UniLossLess())
|
992 |
+
|
993 |
+
if not trainable_delay:
|
994 |
+
self.register_buffer(
|
995 |
+
"delays",
|
996 |
+
delays,
|
997 |
+
)
|
998 |
+
else:
|
999 |
+
self.params["delays"] = nn.Parameter(delays / sr * 1000)
|
1000 |
+
register_parametrization(self.params, "delays", MinMax(0, self.max_delay))
|
1001 |
+
|
1002 |
+
self.register_forward_pre_hook(broadcast2stereo)
|
1003 |
+
|
1004 |
+
self.eq = eq
|
1005 |
+
|
1006 |
+
def forward(self, x):
|
1007 |
+
conv1d = F.conv1d if x.size(-1) > 44100 * 20 else fft_conv1d
|
1008 |
+
|
1009 |
+
c = self.params.c + 0j
|
1010 |
+
b = self.params.b + 0j
|
1011 |
+
|
1012 |
+
gamma = self.params.gamma
|
1013 |
+
delays = self.delays if hasattr(self, "delays") else self.params.delays
|
1014 |
+
|
1015 |
+
if gamma.size(0) > 1:
|
1016 |
+
gamma = F.interpolate(
|
1017 |
+
gamma.T.unsqueeze(1),
|
1018 |
+
size=self.ir_length // 2 + 1,
|
1019 |
+
align_corners=True,
|
1020 |
+
mode="linear",
|
1021 |
+
).transpose(0, 2)
|
1022 |
+
|
1023 |
+
if gamma.size(2) == 1:
|
1024 |
+
gamma = gamma ** (delays / delays.min())
|
1025 |
+
|
1026 |
+
A = self.params.U * gamma
|
1027 |
+
|
1028 |
+
freqs = (
|
1029 |
+
torch.arange(self.ir_length // 2 + 1, device=x.device)
|
1030 |
+
/ self.ir_length
|
1031 |
+
* 2
|
1032 |
+
* torch.pi
|
1033 |
+
)
|
1034 |
+
invD = torch.exp(1j * freqs[:, None] * delays)
|
1035 |
+
# H = c @ torch.linalg.inv(torch.diag_embed(invD) - A) @ b
|
1036 |
+
H = c @ torch.linalg.solve(torch.diag_embed(invD) - A, b)
|
1037 |
+
|
1038 |
+
h = torch.fft.irfft(H.permute(1, 2, 0), n=self.ir_length)
|
1039 |
+
|
1040 |
+
if self.eq is not None:
|
1041 |
+
h = self.eq(h)
|
1042 |
+
|
1043 |
+
# return fft_conv1d(
|
1044 |
+
return conv1d(
|
1045 |
+
F.pad(x, (self.ir_length - 1, 0)),
|
1046 |
+
h.flip(-1),
|
1047 |
+
)
|
1048 |
+
|
1049 |
+
def toJSON(self) -> dict[str, Any]:
|
1050 |
+
return {
|
1051 |
+
"T60 (s)": {
|
1052 |
+
f"{f:.2f} Hz": g.item()
|
1053 |
+
for f, g in zip(
|
1054 |
+
torch.linspace(0, 22050, self.params.gamma.numel()),
|
1055 |
+
-60 * self.delays.min() / amp2db(self.params.gamma) / 44100,
|
1056 |
+
)
|
1057 |
+
},
|
1058 |
+
"Gain (dB, approx)": amp2db(
|
1059 |
+
torch.linalg.norm(self.params.b) * torch.linalg.norm(self.params.c)
|
1060 |
+
).item(),
|
1061 |
+
}
|
modules/rt.py
ADDED
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from numba import njit, prange
|
3 |
+
from scipy.signal import firwin2
|
4 |
+
import torch
|
5 |
+
|
6 |
+
from .fx import Delay, FDN, module2coeffs
|
7 |
+
|
8 |
+
|
9 |
+
@njit
|
10 |
+
def rt_fdn(
|
11 |
+
x: np.ndarray,
|
12 |
+
delay_steps: np.ndarray,
|
13 |
+
firs: np.ndarray,
|
14 |
+
U: np.ndarray,
|
15 |
+
):
|
16 |
+
_, T = x.shape
|
17 |
+
M = delay_steps.shape[0]
|
18 |
+
order = firs.shape[1]
|
19 |
+
y = np.zeros_like(x)
|
20 |
+
buf_size = delay_steps.max() + order
|
21 |
+
delay_buf = np.zeros((M, buf_size), dtype=x.dtype)
|
22 |
+
read_pointer = 0
|
23 |
+
|
24 |
+
for t in range(T):
|
25 |
+
# out = delay_buf[(range(M), read_pointers)]
|
26 |
+
# for i in prange(M):
|
27 |
+
# out[i] = delay_buf[i, read_pointers[i]]
|
28 |
+
out = delay_buf[:, read_pointer]
|
29 |
+
y[:, t] = out
|
30 |
+
|
31 |
+
s = out * firs[:, 0]
|
32 |
+
# indexes = (read_pointers[:, None] - np.arange(1, order)) % buf_sizes[:, None]
|
33 |
+
# reg = np.take_along_axis(delay_buf, indexes, axis=1)
|
34 |
+
# s += firs[:, 1:] @ reg.T
|
35 |
+
# for j in prange(M):
|
36 |
+
# s[j] += firs[j, 1:] @ delay_buf[j, indexes[j]]
|
37 |
+
for i in prange(M):
|
38 |
+
for j in prange(1, order):
|
39 |
+
s[i] += firs[i, j] * delay_buf[i, (read_pointer - j) % buf_size]
|
40 |
+
# for i in prange(1, order):
|
41 |
+
# s += firs[:, i] * delay_buf[:, (read_pointer - i) % buf_size]
|
42 |
+
|
43 |
+
feedback = U @ s + x[:, t]
|
44 |
+
w_pointers = (read_pointer + delay_steps) % buf_size
|
45 |
+
# delay_buf[(range(M), w_pointers)] = s + B @ x[:, t]
|
46 |
+
for i in prange(M):
|
47 |
+
delay_buf[i, w_pointers[i]] = feedback[i]
|
48 |
+
read_pointer = (read_pointer + 1) % buf_size
|
49 |
+
|
50 |
+
return y
|
51 |
+
|
52 |
+
|
53 |
+
@njit
|
54 |
+
def rt_delay(
|
55 |
+
x: np.ndarray,
|
56 |
+
delay_step: int,
|
57 |
+
b0: float,
|
58 |
+
b1: float,
|
59 |
+
b2: float,
|
60 |
+
a1: float,
|
61 |
+
a2: float,
|
62 |
+
):
|
63 |
+
T = x.shape[0]
|
64 |
+
y = np.zeros((2, T), dtype=x.dtype)
|
65 |
+
buf_size = delay_step + 1
|
66 |
+
read_pointer = 0
|
67 |
+
delay_buf = np.zeros((2, buf_size), dtype=x.dtype)
|
68 |
+
bq_buf = np.zeros((2, 2), dtype=x.dtype)
|
69 |
+
|
70 |
+
for t in range(T):
|
71 |
+
out = delay_buf[:, read_pointer]
|
72 |
+
y[:, t] = out
|
73 |
+
|
74 |
+
s = bq_buf[:, 0] + b0 * out
|
75 |
+
bq_buf[:, 0] = bq_buf[:, 1] + b1 * out - a1 * s
|
76 |
+
bq_buf[:, 1] = b2 * out - a2 * s
|
77 |
+
|
78 |
+
w_pointer = (read_pointer + delay_step) % buf_size
|
79 |
+
# cross feeding because of ping-pong delay
|
80 |
+
delay_buf[0, w_pointer] = s[1] + x[t]
|
81 |
+
delay_buf[1, w_pointer] = s[0]
|
82 |
+
|
83 |
+
read_pointer = (read_pointer + 1) % buf_size
|
84 |
+
|
85 |
+
return y
|
86 |
+
|
87 |
+
|
88 |
+
class RealTimeDelay(Delay):
|
89 |
+
def forward(self, x):
|
90 |
+
assert x.size(1) == 1, x.size()
|
91 |
+
assert x.size(0) == 1, x.size()
|
92 |
+
with torch.no_grad():
|
93 |
+
delay_in_samples = round(self.sr * self.params.delay.item() * 0.001)
|
94 |
+
feedback = self.params.feedback.item()
|
95 |
+
|
96 |
+
if self.recursive_eq and self.eq is not None:
|
97 |
+
b0, b1, b2, a0, a1, a2 = [p.item() for p in module2coeffs(self.eq)]
|
98 |
+
b0, b1, b2, a1, a2 = b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0
|
99 |
+
else:
|
100 |
+
b0, b1, b2, a1, a2 = 1.0, 0.0, 0.0, 0.0, 0.0
|
101 |
+
|
102 |
+
b0 = b0 * feedback
|
103 |
+
b1 = b1 * feedback
|
104 |
+
b2 = b2 * feedback
|
105 |
+
x_numpy = x.squeeze().cpu().numpy()
|
106 |
+
y_numpy = rt_delay(x_numpy, delay_in_samples, b0, b1, b2, a1, a2)
|
107 |
+
y = torch.from_numpy(y_numpy).unsqueeze(0).to(x.device) * self.params.gain
|
108 |
+
return self.odd_pan(y[:, :1]) + self.even_pan(y[:, 1:])
|
109 |
+
|
110 |
+
|
111 |
+
class RealTimeFDN(FDN):
|
112 |
+
def forward(self, x):
|
113 |
+
assert x.size(1) == 2, x.size()
|
114 |
+
assert x.size(0) == 1, x.size()
|
115 |
+
with torch.no_grad():
|
116 |
+
delays = self.delays if hasattr(self, "delays") else self.params.delays
|
117 |
+
|
118 |
+
c = self.params.c
|
119 |
+
b = self.params.b
|
120 |
+
gamma = self.params.gamma.clone()
|
121 |
+
|
122 |
+
if gamma.size(1) == 1:
|
123 |
+
gamma = gamma ** (delays / delays.min())
|
124 |
+
|
125 |
+
freqs = np.linspace(0, 1, gamma.size(0))
|
126 |
+
firs = np.apply_along_axis(
|
127 |
+
lambda x: firwin2(gamma.size(0) * 2 - 1, freqs, x, fs=2),
|
128 |
+
1,
|
129 |
+
gamma.cpu().numpy().T,
|
130 |
+
).astype(np.float32)
|
131 |
+
shifted_delays = delays - firs.shape[1] // 2
|
132 |
+
|
133 |
+
U = self.params.U
|
134 |
+
|
135 |
+
x = b @ x.squeeze()
|
136 |
+
|
137 |
+
y_numpy = rt_fdn(
|
138 |
+
x.cpu().numpy(),
|
139 |
+
# delays.cpu().numpy(),
|
140 |
+
shifted_delays.cpu().numpy(),
|
141 |
+
# firs.cpu().numpy(),
|
142 |
+
firs,
|
143 |
+
U.cpu().numpy(),
|
144 |
+
)
|
145 |
+
y = c @ torch.from_numpy(y_numpy).to(x.device)
|
146 |
+
y = y.unsqueeze(0)
|
147 |
+
|
148 |
+
if self.eq is not None:
|
149 |
+
y = self.eq(y)
|
150 |
+
return y
|
modules/utils.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
from functools import reduce, partial
|
4 |
+
from operator import mul
|
5 |
+
from torch.nn.utils.parametrize import is_parametrized, remove_parametrizations
|
6 |
+
|
7 |
+
|
8 |
+
def chain_functions(*functions):
|
9 |
+
return lambda initial: reduce(lambda x, f: f(x), functions, initial)
|
10 |
+
|
11 |
+
|
12 |
+
def remove_fx_parametrisation(fx):
|
13 |
+
def remover(m):
|
14 |
+
if not is_parametrized(m):
|
15 |
+
return
|
16 |
+
for k in list(m.parametrizations.keys()):
|
17 |
+
remove_parametrizations(m, k)
|
18 |
+
|
19 |
+
fx.apply(remover)
|
20 |
+
return fx
|
21 |
+
|
22 |
+
|
23 |
+
def get_chunks(keys, original_shapes):
|
24 |
+
(position, _), *_ = filter(lambda i_k: "U.original" in i_k[1], enumerate(keys))
|
25 |
+
original_chunks = list(map(partial(reduce, mul), original_shapes))
|
26 |
+
U_matrix_shape = original_shapes[position]
|
27 |
+
|
28 |
+
dimensions_not_need = np.ravel_multi_index(
|
29 |
+
np.tril_indices(**dict(zip(("n", "m"), U_matrix_shape))), U_matrix_shape
|
30 |
+
) + sum(original_chunks[:position])
|
31 |
+
|
32 |
+
selected_chunks = (
|
33 |
+
original_chunks[:position]
|
34 |
+
+ [original_chunks[position] - dimensions_not_need.size]
|
35 |
+
+ original_chunks[position + 1 :]
|
36 |
+
)
|
37 |
+
return selected_chunks, position, U_matrix_shape, dimensions_not_need
|
38 |
+
|
39 |
+
|
40 |
+
def vec2statedict(
|
41 |
+
x: torch.Tensor,
|
42 |
+
keys,
|
43 |
+
original_shapes,
|
44 |
+
selected_chunks,
|
45 |
+
position,
|
46 |
+
U_matrix_shape,
|
47 |
+
):
|
48 |
+
chunks = list(torch.split(x, selected_chunks))
|
49 |
+
U = x.new_zeros(reduce(mul, U_matrix_shape))
|
50 |
+
U[
|
51 |
+
np.ravel_multi_index(
|
52 |
+
np.triu_indices(n=U_matrix_shape[0], k=1, m=U_matrix_shape[1]),
|
53 |
+
U_matrix_shape,
|
54 |
+
)
|
55 |
+
] = chunks[position]
|
56 |
+
chunks[position] = U
|
57 |
+
|
58 |
+
state_dict = dict(
|
59 |
+
zip(
|
60 |
+
keys,
|
61 |
+
map(lambda x, shape: x.reshape(*shape), chunks, original_shapes),
|
62 |
+
)
|
63 |
+
)
|
64 |
+
return state_dict
|