File size: 7,635 Bytes
16231ab | 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 | from __future__ import annotations
import hashlib
import json
from pathlib import Path
import librosa
import numpy as np
import pyloudnorm as pyln
import soundfile as sf
SOUNDAQNET_FEATURE_KEYS = (
"feature_profile",
"sample_rate",
"n_fft",
"win_length",
"hop_length",
"n_mels",
"f_min",
"f_max",
"window",
"center",
"pad_mode",
"power",
"ref",
"amin",
"top_db",
)
def audio_feature_signature(config: dict) -> str:
canonical = {key: config.get(key) for key in SOUNDAQNET_FEATURE_KEYS}
payload = json.dumps(canonical, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(payload.encode()).hexdigest()[:16]
def load_mono_audio(path: str | Path, sample_rate: int) -> np.ndarray:
waveform, source_rate = sf.read(path, dtype="float32", always_2d=True)
waveform = waveform.mean(axis=1)
if source_rate != sample_rate:
waveform = librosa.resample(
waveform, orig_sr=source_rate, target_sr=sample_rate, res_type="soxr_hq"
)
return np.asarray(waveform, dtype=np.float32)
def fix_duration(
waveform: np.ndarray,
target_samples: int,
mode: str,
identifier: str,
seed: int,
) -> tuple[np.ndarray, int]:
if waveform.size < target_samples:
return np.pad(waveform, (0, target_samples - waveform.size)), 0
if waveform.size == target_samples:
return waveform, 0
maximum_start = waveform.size - target_samples
if mode == "start":
start = 0
elif mode == "center":
start = maximum_start // 2
elif mode == "deterministic-random":
digest = hashlib.sha256(f"{identifier}:{seed}".encode()).digest()
start = int.from_bytes(digest[:8], "little") % (maximum_start + 1)
else:
raise ValueError(f"Unknown crop mode: {mode}")
return waveform[start : start + target_samples], start
def log_mel_spectrogram(
waveform: np.ndarray,
sample_rate: int,
n_fft: int,
hop_length: int,
win_length: int,
n_mels: int,
f_min: float,
f_max: float,
window: str = "hann",
center: bool = True,
pad_mode: str = "reflect",
power: float = 2.0,
ref: float = 1.0,
amin: float = 1e-10,
top_db: float | None = None,
) -> np.ndarray:
mel_power = librosa.feature.melspectrogram(
y=waveform,
sr=sample_rate,
n_fft=n_fft,
hop_length=hop_length,
win_length=win_length,
n_mels=n_mels,
fmin=f_min,
fmax=f_max,
window=window,
power=power,
center=center,
pad_mode=pad_mode,
)
return librosa.power_to_db(
mel_power,
ref=ref,
amin=amin,
top_db=top_db,
).astype(np.float32)
def frame_loudness_db(
waveform: np.ndarray, n_fft: int, hop_length: int, floor_db: float
) -> np.ndarray:
rms = librosa.feature.rms(
y=waveform,
frame_length=n_fft,
hop_length=hop_length,
center=True,
pad_mode="reflect",
)[0]
db = 20.0 * np.log10(np.maximum(rms, 10 ** (floor_db / 20.0)))
return np.maximum(db, floor_db).astype(np.float32)
def integrated_lufs(waveform: np.ndarray, sample_rate: int) -> float:
if not np.any(np.abs(waveform) > 1e-8):
return float("nan")
meter = pyln.Meter(sample_rate)
try:
value = float(meter.integrated_loudness(waveform.astype(np.float64)))
except Exception:
return float("nan")
if np.isfinite(value):
return value
# BS.1770 uses an absolute gate, so a valid but unusually low-level recording can
# be reported as -inf. Measure a temporarily boosted copy and subtract the exact
# boost afterward. Targeting a -20 dBFS peak leaves ample headroom and does not
# alter ordinary recordings, which already returned a finite value above.
peak = float(np.max(np.abs(waveform)))
if not np.isfinite(peak) or peak <= 1e-8:
return float("nan")
peak_db = float(20.0 * np.log10(peak))
boost_db = min(100.0, max(0.0, -20.0 - peak_db))
if boost_db <= 0.0:
return float("nan")
boosted = waveform.astype(np.float64) * (10.0 ** (boost_db / 20.0))
try:
boosted_value = float(meter.integrated_loudness(boosted))
except Exception:
return float("nan")
return boosted_value - boost_db if np.isfinite(boosted_value) else float("nan")
def analyze_audio(
path: str | Path,
identifier: str,
config: dict,
crop_mode: str,
seed: int,
) -> dict[str, np.ndarray | float | int]:
sample_rate = int(config["sample_rate"])
target_samples = int(round(sample_rate * float(config["duration_seconds"])))
waveform = load_mono_audio(path, sample_rate)
original_samples = int(waveform.size)
waveform, crop_start = fix_duration(
waveform, target_samples, crop_mode, identifier=identifier, seed=seed
)
waveform = np.nan_to_num(waveform, nan=0.0, posinf=1.0, neginf=-1.0)
waveform = np.clip(waveform, -1.0, 1.0).astype(np.float32)
source_lufs = integrated_lufs(waveform, sample_rate)
level_gain_db, peak_limited = 0.0, False
target_lufs = config.get("level_normalization_lufs")
mode = config.get("level_normalization_mode", "clip")
if mode == "group" and config.get("fixed_gain_db") is not None:
# One gain per recording group (e.g. city/recorder): keeps loudness differences between
# places, removes only the group's recorder gain. Set per clip by extract_audio_targets.
level_gain_db = float(config["fixed_gain_db"])
elif mode == "clip" and target_lufs is not None and np.isfinite(source_lufs):
# Remove uncalibrated recording gain: bring every clip to the same integrated loudness.
level_gain_db = float(target_lufs) - source_lufs
if level_gain_db != 0.0:
waveform = waveform * np.float32(10.0 ** (level_gain_db / 20.0))
peak = float(np.max(np.abs(waveform)))
if peak > 0.999:
waveform = waveform * np.float32(0.999 / peak)
level_gain_db += float(20.0 * np.log10(0.999 / peak))
peak_limited = True
waveform = waveform.astype(np.float32)
mel = log_mel_spectrogram(
waveform,
sample_rate,
int(config["n_fft"]),
int(config["hop_length"]),
int(config["win_length"]),
int(config["n_mels"]),
float(config["f_min"]),
float(config["f_max"]),
str(config.get("window", "hann")),
bool(config.get("center", True)),
str(config.get("pad_mode", "reflect")),
float(config.get("power", 2.0)),
float(config.get("ref", 1.0)),
float(config.get("amin", 1e-10)),
config.get("top_db"),
)
loudness = frame_loudness_db(
waveform,
int(config["n_fft"]),
int(config["hop_length"]),
float(config["loudness_floor_db"]),
)
frames = min(mel.shape[1], loudness.shape[0])
mel = mel[:, :frames]
loudness = loudness[:frames]
return {
"waveform": waveform,
"mel": mel,
"loudness_db": loudness,
"lufs": integrated_lufs(waveform, sample_rate),
"source_lufs": source_lufs,
"level_gain_db": level_gain_db,
"peak_limited": peak_limited,
"crop_start_sample": crop_start,
"original_samples": original_samples,
"sample_rate": sample_rate,
}
def write_float_wav(path: str | Path, waveform: np.ndarray, sample_rate: int) -> None:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
sf.write(path, waveform, sample_rate, subtype="FLOAT")
|