File size: 8,468 Bytes
66a6dc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import torch
import torchaudio
import scipy.signal
import numpy as np
import pyloudnorm as pyln
import matplotlib.pyplot as plt
from deepafx_st.processors.dsp.compressor import compressor

from tqdm import tqdm


class BaselineEQ(torch.nn.Module):
    def __init__(
        self,
        ntaps: int = 63,
        n_fft: int = 65536,
        sample_rate: float = 44100,
    ):
        super().__init__()
        self.ntaps = ntaps
        self.n_fft = n_fft
        self.sample_rate = sample_rate

        # compute the target spectrum
        # print("Computing target spectrum...")
        # self.target_spec, self.sm_target_spec = self.analyze_speech_dataset(filepaths)
        # self.plot_spectrum(self.target_spec, filename="targetEQ")
        # self.plot_spectrum(self.sm_target_spec, filename="targetEQsm")

    def forward(self, x, y):

        bs, ch, s = x.size()

        x = x.view(bs * ch, -1)
        y = y.view(bs * ch, -1)

        in_spec = self.get_average_spectrum(x)
        ref_spec = self.get_average_spectrum(y)

        sm_in_spec = self.smooth_spectrum(in_spec)
        sm_ref_spec = self.smooth_spectrum(ref_spec)

        # self.plot_spectrum(in_spec, filename="inSpec")
        # self.plot_spectrum(sm_in_spec, filename="inSpecsm")

        # design inverse FIR filter to match target EQ
        freqs = np.linspace(0, 1.0, num=(self.n_fft // 2) + 1)
        response = sm_ref_spec / sm_in_spec
        response[-1] = 0.0  # zero gain at nyquist

        b = scipy.signal.firwin2(
            self.ntaps,
            freqs * (self.sample_rate / 2),
            response,
            fs=self.sample_rate,
        )

        # scale the coefficients for less intense filter
        # clearb *= 0.5

        # apply the filter
        x_filt = scipy.signal.lfilter(b, [1.0], x.numpy())
        x_filt = torch.tensor(x_filt.astype("float32"))

        if False:
            # plot the filter response
            w, h = scipy.signal.freqz(b, fs=self.sample_rate, worN=response.shape[-1])

            fig, ax1 = plt.subplots()
            ax1.set_title("Digital filter frequency response")
            ax1.plot(w, 20 * np.log10(abs(h + 1e-8)))
            ax1.plot(w, 20 * np.log10(abs(response + 1e-8)))

            ax1.set_xscale("log")
            ax1.set_ylim([-12, 12])
            plt.grid(c="lightgray")
            plt.savefig(f"inverse.png")

            x_filt_avg_spec = self.get_average_spectrum(x_filt)
            sm_x_filt_avg_spec = self.smooth_spectrum(x_filt_avg_spec)
            y_avg_spec = self.get_average_spectrum(y)
            sm_y_avg_spec = self.smooth_spectrum(y_avg_spec)
            compare = torch.stack(
                [
                    torch.tensor(sm_in_spec),
                    torch.tensor(sm_x_filt_avg_spec),
                    torch.tensor(sm_ref_spec),
                    torch.tensor(sm_y_avg_spec),
                ]
            )
            self.plot_multi_spectrum(
                compare,
                legend=["in", "out", "target curve", "actual target"],
                filename="outSpec",
            )

        return x_filt

    def analyze_speech_dataset(self, filepaths, peak=-3.0):
        avg_spec = []
        for filepath in tqdm(filepaths, ncols=80):
            x, sr = torchaudio.load(filepath)
            x /= x.abs().max()
            x *= 10 ** (peak / 20.0)
            avg_spec.append(self.get_average_spectrum(x))
        avg_specs = torch.stack(avg_spec)

        avg_spec = avg_specs.mean(dim=0).numpy()
        avg_spec_std = avg_specs.std(dim=0).numpy()

        # self.plot_multi_spectrum(avg_specs, filename="allTargetEQs")
        # self.plot_spectrum_stats(avg_spec, avg_spec_std, filename="targetEQstats")

        sm_avg_spec = self.smooth_spectrum(avg_spec)

        return avg_spec, sm_avg_spec

    def smooth_spectrum(self, H):
        # apply Savgol filter for smoothed target curve
        return scipy.signal.savgol_filter(H, 1025, 2)

    def get_average_spectrum(self, x):

        # x = x[:, : self.n_fft]
        X = torch.stft(x, self.n_fft, return_complex=True, normalized=True)
        # fft_size = self.next_power_of_2(x.shape[-1])
        # X = torch.fft.rfft(x, n=fft_size)

        X = X.abs()  # convert to magnitude
        X = X.mean(dim=-1).view(-1)  # average across frames

        return X

    @staticmethod
    def next_power_of_2(x):
        return 1 if x == 0 else int(2 ** np.ceil(np.log2(x)))

    def plot_multi_spectrum(self, Hs, legend=[], filename=None):

        bin_width = (self.sample_rate / 2) / (self.n_fft // 2)
        freqs = np.arange(0, (self.sample_rate / 2) + bin_width, step=bin_width)

        fig, ax1 = plt.subplots()

        for H in Hs:
            ax1.plot(
                freqs,
                20 * np.log10(abs(H) + 1e-8),
            )

        plt.legend(legend)

        # avg_spec = Hs.mean(dim=0).numpy()
        # ax1.plot(freqs, 20 * np.log10(avg_spec), color="k", linewidth=2)

        ax1.set_xscale("log")
        ax1.set_ylim([-80, 0])
        plt.grid(c="lightgray")

        if filename is not None:
            plt.savefig(f"{filename}.png")

    def plot_spectrum_stats(self, H_mean, H_std, filename=None):
        bin_width = (self.sample_rate / 2) / (self.n_fft // 2)
        freqs = np.arange(0, (self.sample_rate / 2) + bin_width, step=bin_width)

        fig, ax1 = plt.subplots()
        ax1.plot(freqs, 20 * np.log10(H_mean))
        ax1.plot(
            freqs,
            (20 * np.log10(H_mean)) + (20 * np.log10(H_std)),
            linestyle="--",
            color="k",
        )
        ax1.plot(
            freqs,
            (20 * np.log10(H_mean)) - (20 * np.log10(H_std)),
            linestyle="--",
            color="k",
        )

        ax1.set_xscale("log")
        ax1.set_ylim([-80, 0])
        plt.grid(c="lightgray")

        if filename is not None:
            plt.savefig(f"{filename}.png")

    def plot_spectrum(self, H, legend=[], filename=None):

        bin_width = (self.sample_rate / 2) / (self.n_fft // 2)
        freqs = np.arange(0, (self.sample_rate / 2) + bin_width, step=bin_width)

        fig, ax1 = plt.subplots()
        ax1.plot(freqs, 20 * np.log10(H))
        ax1.set_xscale("log")
        ax1.set_ylim([-80, 0])
        plt.grid(c="lightgray")

        plt.legend(legend)

        if filename is not None:
            plt.savefig(f"{filename}.png")


class BaslineComp(torch.nn.Module):
    def __init__(
        self,
        sample_rate: float = 44100,
    ):
        super().__init__()
        self.sample_rate = sample_rate
        self.meter = pyln.Meter(sample_rate)

    def forward(self, x, y):

        x_lufs = self.meter.integrated_loudness(x.view(-1).numpy())
        y_lufs = self.meter.integrated_loudness(y.view(-1).numpy())

        delta_lufs = y_lufs - x_lufs

        threshold = 0.0
        x_comp = x
        x_comp_new = x
        while delta_lufs > 0.5 and threshold > -80.0:
            x_comp = x_comp_new  # use the last setting
            x_comp_new = compressor(
                x.view(-1).numpy(),
                self.sample_rate,
                threshold=threshold,
                ratio=3,
                attack_time=0.001,
                release_time=0.05,
                knee_dB=6.0,
                makeup_gain_dB=0.0,
            )
            x_comp_new = torch.tensor(x_comp_new)
            x_comp_new /= x_comp_new.abs().max()
            x_comp_new *= 10 ** (-12.0 / 20)
            x_lufs = self.meter.integrated_loudness(x_comp_new.view(-1).numpy())
            delta_lufs = y_lufs - x_lufs
            threshold -= 0.5

        return x_comp.view(1, 1, -1)


class BaselineEQAndComp(torch.nn.Module):
    def __init__(
        self,
        ntaps=63,
        n_fft=65536,
        sample_rate=44100,
        block_size=1024,
        plugin_config=None,
    ):
        super().__init__()
        self.eq = BaselineEQ(ntaps, n_fft, sample_rate)
        self.comp = BaslineComp(sample_rate)

    def forward(self, x, y):

        with torch.inference_mode():
            x /= x.abs().max()
            y /= y.abs().max()
            x *= 10 ** (-12.0 / 20)
            y *= 10 ** (-12.0 / 20)

            x = self.eq(x, y)

            x /= x.abs().max()
            y /= y.abs().max()
            x *= 10 ** (-12.0 / 20)
            y *= 10 ** (-12.0 / 20)

            x = self.comp(x, y)

            x /= x.abs().max()
            x *= 10 ** (-12.0 / 20)

        return x