"""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=)` 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(" 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