File size: 16,323 Bytes
f053b90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
"""VeriSpoof-Bench audio realization (standalone; numpy, scipy, soundfile, librosa; torch + transformers only for
EnCodec; ffmpeg 7.0.2 for the classical codecs).

Mirrors, operation for operation, the evaluation-time realization of the VeriSpoof research code
(`spoofllm/data/audio_bank.py`, `spoofllm/data/augment.py`, `spoofllm/data/processing.py`), so a derived item
(augmented `_aug*` / recorded-condition `_cond` / post-processed `+proc`) can be regenerated from the user's own copy of
the source corpus, MUSAN and the OpenSLR-28 RIRs:

  1. read the source recording as mono float32 at 16 kHz (libsndfile; ffmpeg for files libsndfile rejects; soxr_hq
     resampling when the file is not 16 kHz)
  2. post-processing only: silence trimming on the whole recording (`proc.silence == "trimmed"`)
  3. the model's window: the first `window` samples (128,000 = 8.0 s); shorter recordings are tiled
  4. augmentation (derived rows only), in the order reverb -> noise -> codec, with
     rng = numpy.random.default_rng(zlib.crc32(seed_key)) where seed_key is the row's utt_id; the random draws pick the
     RIR inside the RT60 bin, the SNR inside the level range, the noise type and MUSAN file(s) and offsets, and the
     codec setting inside the codec kind; then peak normalisation to 0.99 if needed
  5. post-processing only: band filter, gain / clipping, then silence padding (low-level noise padding draws from the
     same rng)

Every draw is also returned in a trace (file names, SNR, offsets, codec setting, ...), which the benchmark files store
as `realization`; `realize(..., check=<stored realization>)` asserts that the replay reproduces it.
"""
import os
import subprocess
import zlib

import numpy as np
import soundfile as sf
from scipy.signal import butter, fftconvolve, sosfilt

SR = 16000
WINDOW = 128000
FFMPEG = os.environ.get("VSBENCH_FFMPEG", os.environ.get("SPOOFLLM_FFMPEG", "ffmpeg"))
HERE = os.path.dirname(os.path.abspath(__file__))
LISTS = os.path.join(HERE, "..", "aug_sources")

NOISE_LEVELS = {"clean": None, "mild": (20, 30), "moderate": (10, 20), "severe": (5, 10), "extreme": (0, 5)}
REVERB_LEVELS = {"minimal": None, "slight": (0.0, 0.3), "moderate": (0.3, 0.6), "heavy": (0.6, 1.0),
                 "extreme": (1.0, 9.9)}
_CODECS = {
    "mp3": [("mp3_32k", ["-c:a", "libmp3lame", "-b:a", "32k"], 16000, "mp3"),
            ("mp3_64k", ["-c:a", "libmp3lame", "-b:a", "64k"], 16000, "mp3"),
            ("mp3_128k", ["-c:a", "libmp3lame", "-b:a", "128k"], 16000, "mp3")],
    "aac": [("aac_32k", ["-c:a", "aac", "-b:a", "32k"], 16000, "adts"),
            ("aac_64k", ["-c:a", "aac", "-b:a", "64k"], 16000, "adts")],
    "opus": [("opus_12k", ["-c:a", "libopus", "-b:a", "12k"], 16000, "ogg"),
             ("opus_24k", ["-c:a", "libopus", "-b:a", "24k"], 16000, "ogg")],
    "narrowband": [("amrnb_12k2", ["-c:a", "libopencore_amrnb", "-b:a", "12.2k"], 8000, "amr"),
                   ("g711_ulaw", ["-c:a", "pcm_mulaw"], 8000, "wav"),
                   ("speex_nb", ["-c:a", "libspeex"], 8000, "ogg")],
    "neural": [("encodec_1.5k", 1.5, 24000, None), ("encodec_3k", 3.0, 24000, None), ("encodec_6k", 6.0, 24000, None)],
}
# the evaluation codec set (CODECS_V2 of the research code)
CODECS = {**_CODECS,
          "narrowband": _CODECS["narrowband"] + [("opus_nb_8k", ["-c:a", "libopus", "-b:a", "8k"], 8000, "ogg")],
          "wideband": [("amrwb_6k6", ["-c:a", "libvo_amrwbenc", "-b:a", "6.6k"], 16000, "amr"),
                       ("amrwb_12k65", ["-c:a", "libvo_amrwbenc", "-b:a", "12.65k"], 16000, "amr"),
                       ("amrwb_23k85", ["-c:a", "libvo_amrwbenc", "-b:a", "23.85k"], 16000, "amr"),
                       ("speex_wb_q3", ["-c:a", "libspeex", "-cbr_quality", "3"], 16000, "ogg"),
                       ("speex_wb_q8", ["-c:a", "libspeex", "-cbr_quality", "8"], 16000, "ogg"),
                       ("g722", ["-c:a", "g722"], 16000, "wav")],
          "neural": _CODECS["neural"] + [("encodec_12k", 12.0, 24000, None), ("encodec_24k", 24.0, 24000, None)]}
CODECS["cascade"] = [(f"{m[0]}+{e[0]}", (m, e), None, None) for m in _CODECS["mp3"] for e in CODECS["neural"]]
DEMUX = {"adts": "aac"}


# ---------------------------------------------------------------- reading
def _ffmpeg_read(path, sr=SR):
    out = subprocess.run([FFMPEG, "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-ar", str(sr), "pipe:1"],
                         capture_output=True, check=True).stdout
    return np.frombuffer(out, np.float32).copy()


def read_audio(path, sr=SR):
    """Mono float32 at 16 kHz, exactly as the evaluation read it: first channel through libsndfile (soxr_hq
    resampling if needed); files libsndfile rejects (a share of the ASVspoof 2021 FLACs) are decoded by ffmpeg."""
    try:
        x, s = sf.read(path, dtype="float32", always_2d=True)
    except sf.LibsndfileError:
        return _ffmpeg_read(path, sr)
    x = x[:, 0]
    if s != sr:
        import librosa
        x = librosa.resample(x, orig_sr=s, target_sr=sr, res_type="soxr_hq")
    return x


def fit_window(x, S=WINDOW):
    """First S samples; shorter recordings are tiled; an empty one is digital silence -> (window, tiled)."""
    if len(x) >= S:
        return x[:S], False
    if not len(x):
        return np.zeros(S, np.float32), True
    return np.tile(x, S // max(len(x), 1) + 1)[:S], True


# ---------------------------------------------------------------- augmentation sources
class Sources:
    """MUSAN noise / music / speech file lists and SLR28 RIRs binned by RT60, in the evaluation's order (shipped in
    aug_sources/, paths relative to the MUSAN and RIRS_NOISES roots)."""

    def __init__(self, musan_root, rirs_root, lists=LISTS):
        self.musan_root, self.rirs_root = musan_root, rirs_root
        self.musan = {t: [l.strip() for l in open(f"{lists}/musan_{t}.txt") if l.strip()]
                      for t in ("noise", "music", "speech")}
        self.rirs = {lv: [] for lv in REVERB_LEVELS if REVERB_LEVELS[lv]}
        for line in open(f"{lists}/rir_rt60.tsv"):
            p, t = line.rstrip("\n").split("\t")
            t = float(t)
            for lv, rng in REVERB_LEVELS.items():
                if rng and rng[0] <= t < rng[1]:
                    self.rirs[lv].append((p, t))

    def musan_path(self, rel):
        return os.path.join(self.musan_root, rel) if self.musan_root else None

    def rir_path(self, rel):
        return os.path.join(self.rirs_root, rel) if self.rirs_root else None


def _segment(path, n, rng, dry=False):
    """A random n-sample segment of a MUSAN file -> (segment, offset in the 16 kHz file)."""
    try:
        info = sf.info(path)
    except sf.LibsndfileError:
        info = None
    if info is not None and info.samplerate == SR and info.frames >= n:
        o = int(rng.integers(0, info.frames - n + 1))
        if dry:
            return None, o
        x, _ = sf.read(path, frames=n, start=o, dtype="float32", always_2d=True)
        if len(x) == n:
            return x[:, 0], o
        return read_audio(path)[o:o + n], o
    x = read_audio(path)
    if len(x) < n:
        x = np.tile(x, int(np.ceil(n / max(len(x), 1))))
    o = int(rng.integers(0, len(x) - n + 1))
    return x[o:o + n], o


def add_reverb(x, rir):
    rir = rir / (np.abs(rir).max() + 1e-9)
    d = int(np.argmax(np.abs(rir)))
    y = fftconvolve(x, rir[d:])[:len(x)]
    return y * (np.sqrt(np.mean(x ** 2)) / (np.sqrt(np.mean(y ** 2)) + 1e-9))


def add_noise(x, noise, snr_db):
    px, pn = np.mean(x ** 2) + 1e-12, np.mean(noise ** 2) + 1e-12
    return x + noise * np.sqrt(px / (pn * 10 ** (snr_db / 10)))


def _fit(y, n):
    return y[:n] if len(y) >= n else np.pad(y, (0, n - len(y)))


def align(x, y, max_lag=4000):
    n = len(x) + len(y)
    c = np.fft.irfft(np.fft.rfft(y, n) * np.conj(np.fft.rfft(x, n)), n)
    lags = np.concatenate([np.arange(0, max_lag + 1), np.arange(-max_lag, 0)])
    lag = int(lags[np.argmax(c[lags])])
    y = y[lag:] if lag >= 0 else np.pad(y, (-lag, 0))
    return _fit(y, len(x))


def ffmpeg_codec(x, args, inter_sr, fmt):
    pcm = (np.clip(x, -1, 1) * 32767).astype("<i2").tobytes()
    enc = subprocess.run([FFMPEG, "-v", "error", "-f", "s16le", "-ar", str(SR), "-ac", "1", "-i", "pipe:0",
                          "-ar", str(inter_sr), *args, "-f", fmt, "pipe:1"], input=pcm, capture_output=True, check=True)
    dec_args = ["-c:a", "libspeex"] if "libspeex" in args else []
    dec = subprocess.run([FFMPEG, "-v", "error", "-f", DEMUX.get(fmt, fmt), *dec_args, "-i", "pipe:0", "-f", "s16le",
                          "-ar", str(SR), "-ac", "1", "pipe:1"], input=enc.stdout, capture_output=True, check=True)
    y = np.frombuffer(dec.stdout, "<i2").astype(np.float32) / 32767
    return align(x, y)


class EnCodec:
    """facebook/encodec_24khz (transformers), fp32 on CPU as in the evaluation."""

    def __init__(self, device="cpu"):
        import torch
        from transformers import EncodecModel
        torch.set_num_threads(1)
        self.torch, self.device = torch, device
        self.m = EncodecModel.from_pretrained("facebook/encodec_24khz").to(device).eval()

    def __call__(self, x, bandwidth):
        import librosa
        y = librosa.resample(x, orig_sr=SR, target_sr=24000, res_type="soxr_hq")
        bk = self.torch.backends
        tf32 = bk.cudnn.allow_tf32, bk.cuda.matmul.allow_tf32
        bk.cudnn.allow_tf32 = bk.cuda.matmul.allow_tf32 = False
        try:
            with self.torch.no_grad():
                t = self.torch.from_numpy(y)[None, None].to(self.device)
                out = self.m.decode(*self.m.encode(t, bandwidth=bandwidth)[:2], None)[0][0, 0].cpu().numpy()
        finally:
            bk.cudnn.allow_tf32, bk.cuda.matmul.allow_tf32 = tf32
        return align(x, librosa.resample(out, orig_sr=24000, target_sr=SR, res_type="soxr_hq"))


def augment(x, cond, src, rng, encodec=None, trace=None, dry=False):
    """Recording condition {noise_level, reverb_level, codec_kind} on the window x (float32, 16 kHz)."""
    tr = trace if trace is not None else {}
    if cond["reverb_level"] != "minimal":
        lst = src.rirs[cond["reverb_level"]]
        p, t = lst[rng.integers(len(lst))]
        tr.update(rir_file=p, rt60=t)
        if not dry:
            x = add_reverb(x, read_audio(src.rir_path(p)))
    if cond["noise_level"] != "clean":
        lo, hi = NOISE_LEVELS[cond["noise_level"]]
        snr = float(rng.uniform(lo, hi))
        ntype = ["noise", "music", "babble"][rng.integers(3)]
        files, offs, parts = [], [], []
        if ntype == "babble":
            k = int(rng.integers(3, 6))
            for _ in range(k):
                f = src.musan["speech"][rng.integers(len(src.musan["speech"]))]
                seg, o = _segment(src.musan_path(f), len(x), rng, dry)
                files.append(f), offs.append(o), parts.append(seg)
        else:
            f = src.musan[ntype][rng.integers(len(src.musan[ntype]))]
            seg, o = _segment(src.musan_path(f), len(x), rng, dry)
            files.append(f), offs.append(o), parts.append(seg)
        tr.update(snr_db=snr, noise_type=ntype, noise_files=files, noise_offsets=offs)
        if not dry:
            x = add_noise(x, sum(parts) if ntype == "babble" else parts[0], snr)
    if cond["codec_kind"] != "none":
        kind = cond["codec_kind"]
        detail, a, inter_sr, fmt = CODECS[kind][rng.integers(len(CODECS[kind]))]
        if kind == "cascade":
            (_, ma, msr, mfmt), (_, bw, _, _) = a
            steps = [lambda v: ffmpeg_codec(v, ma, msr, mfmt), lambda v: encodec(v, bw)]
            if rng.random() < 0.5:
                steps, detail = steps[::-1], "+".join(detail.split("+")[::-1])
            if not dry:
                for f in steps:
                    x = f(x)
        elif kind == "neural":
            if not dry:
                x = encodec(x, a)
        elif not dry:
            pool = CODECS[kind]
            for k in range(4):  # an ffmpeg encoder crash is retried with another setting of the same kind
                try:
                    x = ffmpeg_codec(x, a, inter_sr, fmt)
                    break
                except subprocess.CalledProcessError:
                    if k == 3:
                        raise
                    detail, a, inter_sr, fmt = pool[rng.integers(len(pool))]
        tr["codec_detail"] = detail
    if not dry:
        peak = np.abs(x).max()
        if peak > 0.99:
            x = x * (0.99 / peak)
    return x.astype(np.float32), tr


# ---------------------------------------------------------------- post-processing (spoofllm/data/processing.py)
def _trim(x, db=40.0, keep=0.05):
    f = 320
    n = len(x) // f
    if n < 2:
        return x, 0
    e = 10 * np.log10(np.mean(x[:n * f].reshape(n, f) ** 2, 1) + 1e-12)
    idx = np.where(e > e.max() - db)[0]
    if not len(idx):
        return x, 0
    pad = int(keep * SR)
    a = max(0, idx[0] * f - pad)
    return x[a:min(len(x), (idx[-1] + 1) * f + pad)], a


def proc_pre(x, c):
    return _trim(x) if c.get("silence") == "trimmed" else (x, 0)


def proc_post(x, c, rng):
    if c.get("hp") is not None:
        x = sosfilt(butter(4, c["hp"], "highpass", fs=SR, output="sos"), x)
    elif c.get("bp") is not None:
        x = sosfilt(butter(4, list(c["bp"]), "bandpass", fs=SR, output="sos"), x)
    peak = np.abs(x).max() + 1e-9
    if c.get("clip_peak") is not None:
        x = np.clip(x * (c["clip_peak"] / peak), -1, 1)
    elif c.get("gain_db") is not None:
        x = x * min(10 ** (c["gain_db"] / 20), 0.99 / peak)
    s = c.get("silence", "unchanged")
    if s in ("digital silence added", "low-level noise added"):
        S = len(x)
        n = min(int(c["sil_len"] * SR), S // 3)
        pad = lambda: np.zeros(n) if s == "digital silence added" else rng.standard_normal(n) * 10 ** (c["noise_dbfs"] / 20)  # noqa: E731
        w = c["sil_where"]
        x = np.concatenate([pad(), x[:S - n]]) if w == "start" else np.concatenate([x[:S - n], pad()]) if w == "end" \
            else np.concatenate([pad(), x[:S - 2 * n], pad()])
        return x.astype(np.float32), (0 if w == "end" else n, 0 if w == "start" else n)
    return x.astype(np.float32), (0, 0)


# ---------------------------------------------------------------- one audio of an item
def seed_of(seed_key):
    return zlib.crc32(seed_key.encode())


def realize(source, seed_key, cond=None, proc=None, src=None, encodec=None, window=WINDOW, check=None, dry=False):
    """-> (16 kHz float32 window as the model heard it, trace).

    source: path of the source recording (or a 1-D float32 array at 16 kHz); seed_key: the row's utt_id;
    cond: {noise_level, reverb_level, codec_kind} for augmented / recorded-condition rows, else None;
    proc: post-processing condition (benchmark column `proc`) or None; src: Sources (needed when cond is given);
    check: a stored realization dict, compared with the replayed draws (AssertionError on a difference);
    dry: replay the random draws only (no signal processing; noise files are only opened for their length)."""
    rng = np.random.default_rng(seed_of(seed_key))
    x = (read_audio(source) if isinstance(source, str) else np.asarray(source, np.float32)) if not dry or proc else None
    trace = {"seed": seed_of(seed_key)}
    if dry and not proc:
        x = np.zeros(window, np.float32)
        trace["dry"] = True
    trim = 0
    if proc:
        x, trim = proc_pre(x.astype(np.float32), proc)
    trace.update(trim_start=int(trim), length=int(len(x)))
    x, tiled = fit_window(x, window)
    x = x.astype(np.float32)
    trace["tiled"] = bool(tiled)
    if cond is not None:
        x, _ = augment(x, cond, src, rng, encodec, trace, dry)
    if proc:
        x, (p0, p1) = proc_post(x, proc, rng)
        trace.update(pad_start=int(p0), pad_end=int(p1))
    if check:
        for k in ("rir_file", "snr_db", "noise_type", "noise_files", "noise_offsets", "codec_detail"):
            if check.get(k) is not None or trace.get(k) is not None:
                a, b = check.get(k), trace.get(k)
                ok = np.allclose(a, b) if k == "snr_db" and a is not None and b is not None else list(np.atleast_1d(a)) == list(np.atleast_1d(b))
                assert ok, f"{seed_key}: {k} replayed {b!r}, stored {a!r}"
    return x.astype(np.float32), trace