Files

281 lines
9.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""YIN 基频(F0)提取 —— 向量化实现。
YIN 的差函数原始定义需要 O(N·τ) 的双重求和。这里用恒等式
d(τ) = e1 + e2(τ) − 2·A(τ)
把逐帧计算改写成「前缀和 + FFT 互相关」,整段音频一次性批量算完:
``e1`` 是帧内固定能量,``e2(τ)`` 用平方前缀和求得,``A(τ)`` 用 FFT 卷积求得。
这样避免了 Python 层的双层循环,一段 10 秒哼唱通常在几十毫秒内完成。
"""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from scipy.fft import irfft, next_fast_len, rfft
from .audio import frame_signal
from .config import DEFAULT, Config
__all__ = ["PitchTrack", "extract_pitch", "hz_to_midi", "midi_to_hz"]
_A4_HZ = 440.0
_A4_MIDI = 69.0
def hz_to_midi(f0: np.ndarray) -> np.ndarray:
"""频率(Hz) → 连续 MIDI 音高;非正频率记为 NaN。"""
f0 = np.asarray(f0, dtype=np.float64)
out = np.full(f0.shape, np.nan, dtype=np.float64)
ok = f0 > 0
out[ok] = _A4_MIDI + 12.0 * np.log2(f0[ok] / _A4_HZ)
return out
def midi_to_hz(midi: np.ndarray) -> np.ndarray:
"""连续 MIDI 音高 → 频率(Hz)。"""
midi = np.asarray(midi, dtype=np.float64)
return _A4_HZ * np.power(2.0, (midi - _A4_MIDI) / 12.0)
@dataclass
class PitchTrack:
"""逐帧基频轨迹。"""
times: np.ndarray # 帧中心时刻(秒)
f0: np.ndarray # 基频 Hz,未发声为 0
midi: np.ndarray # 连续 MIDI 音高,未发声为 NaN
conf: np.ndarray # 置信度 0..1
rms: np.ndarray # 逐帧 RMS
voiced: np.ndarray # 有声标记
sr: int
hop_s: float
frame_s: float
@property
def n_frames(self) -> int:
return int(self.times.size)
@property
def duration(self) -> float:
return float(self.times[-1] + self.hop_s) if self.times.size else 0.0
def voiced_ratio(self) -> float:
return float(self.voiced.mean()) if self.voiced.size else 0.0
# --------------------------------------------------------------------------- #
# 差函数 / CMNDF
# --------------------------------------------------------------------------- #
def _difference_functions(frames: np.ndarray, tau_max: int, window: int) -> np.ndarray:
"""批量计算 d(τ),τ ∈ [0, tau_max]。返回 (n_frames, tau_max+1)。"""
frames = np.asarray(frames, dtype=np.float64)
n_frames, frame_len = frames.shape
taus = np.arange(tau_max + 1)
# e1:积分窗内的固定能量
sq = frames * frames
cumsum = np.concatenate(
[np.zeros((n_frames, 1)), np.cumsum(sq, axis=1)], axis=1
)
e1 = cumsum[:, window]
# e2(τ):滑动窗能量
e2 = cumsum[:, taus + window] - cumsum[:, taus]
# A(τ):积分窗与整帧的互相关,用 FFT 一次算完
reversed_head = np.ascontiguousarray(frames[:, :window][:, ::-1])
fft_len = next_fast_len(frame_len + window - 1)
fa = rfft(reversed_head, fft_len, axis=1)
fb = rfft(frames, fft_len, axis=1)
conv = irfft(fb * fa, fft_len, axis=1)
acf = conv[:, taus + window - 1]
diff = e1[:, None] + e2 - 2.0 * acf
return np.maximum(diff, 0.0)
def _cmndf(diff: np.ndarray) -> np.ndarray:
"""累积均值归一化差函数 d'(τ);d'(0) 约定为 1。"""
cumsum = np.cumsum(diff, axis=1)
taus = np.arange(1, diff.shape[1], dtype=np.float64)
running = cumsum[:, 1:] / taus
out = np.ones_like(diff)
np.divide(diff[:, 1:], np.maximum(running, 1e-12), out=out[:, 1:])
return out
def _pick_tau(
cmndf: np.ndarray, tau_min: int, tau_max: int, threshold: float
) -> tuple[np.ndarray, np.ndarray]:
"""选基音周期。
低基频(如 110 Hz)的 CMNDF 谷很宽,"首次低于阈值" 的位置离真正的谷底
可能差十几个采样点,因此在 ±3 邻域内细化会系统性高估基频。这里改为
**先定位所有局部极小,再取其中最早的一个低于阈值者**;若没有低于阈值的
谷,才退化为范围内全局最小(后续由置信度门限筛除)。
返回 (tau 浮点值, 谷底 CMNDF 值)。
"""
n_frames, n_tau = cmndf.shape
# 局部极小:两侧邻点都不小于自身
is_min = np.zeros_like(cmndf, dtype=bool)
is_min[:, 1:-1] = (cmndf[:, 1:-1] <= cmndf[:, :-2]) & (
cmndf[:, 1:-1] <= cmndf[:, 2:]
)
in_range = np.zeros(n_tau, dtype=bool)
in_range[tau_min : tau_max + 1] = True
candidates = is_min & in_range[None, :]
below = candidates & (cmndf < threshold)
has_candidate = below.any(axis=1)
# 取 tau 最小的合格谷底
first_below = below.argmax(axis=1)
# 无合格谷底:在范围内取全局最小
masked = np.where(in_range[None, :], cmndf, np.inf)
fallback = masked.argmin(axis=1)
rows = np.arange(n_frames)
best = np.where(has_candidate, first_below, fallback)
# 抛物线插值,得到亚采样精度的周期与谷底值
d0 = cmndf[rows, best]
d_left = cmndf[rows, np.maximum(best - 1, tau_min)]
d_right = cmndf[rows, np.minimum(best + 1, tau_max)]
denom = d_left - 2.0 * d0 + d_right
with np.errstate(divide="ignore", invalid="ignore"):
shift = np.where(np.abs(denom) > 1e-12, 0.5 * (d_left - d_right) / denom, 0.0)
shift = np.nan_to_num(shift, nan=0.0, posinf=0.0, neginf=0.0)
shift = np.clip(shift, -1.0, 1.0)
interior = (best > tau_min) & (best < tau_max)
tau = best.astype(np.float64) + np.where(interior, shift, 0.0)
valley = d0 - 0.5 * denom * shift * shift
return tau, np.maximum(valley, 0.0)
# --------------------------------------------------------------------------- #
# 后处理
# --------------------------------------------------------------------------- #
def _nan_median_filter(values: np.ndarray, window: int) -> np.ndarray:
"""忽略 NaN 的中值滤波(用于构造局部参考音高)。"""
if window <= 1:
return values.copy()
half = window // 2
out = np.full_like(values, np.nan)
for i in range(values.size):
lo = max(0, i - half)
hi = min(values.size, i + half + 1)
seg = values[lo:hi]
seg = seg[np.isfinite(seg)]
if seg.size:
out[i] = np.median(seg)
return out
def _fold_octaves(
midi: np.ndarray, reference: np.ndarray, low: float, high: float
) -> np.ndarray:
"""把偏离局部参考达 low..high 半音的帧折叠一个八度。
YIN 最常见的错误是倍频/半频误判(±12 半音)。这里只在偏差落在一个八度附近时
才纠正,避免把真实的大跳音程(如 9 度)改坏。
"""
diff = midi - reference
magnitude = np.abs(diff)
fold = -np.round(diff / 12.0) * 12.0
mask = np.isfinite(diff) & (magnitude >= low) & (magnitude <= high)
return np.where(mask, midi + fold, midi)
def _correct_octaves(
midi: np.ndarray, voiced: np.ndarray, cfg: Config
) -> np.ndarray:
out = midi.copy()
for _ in range(2): # 两轮迭代,处理连续八度跳变
reference = _nan_median_filter(out, cfg.median_filter_frames)
corrected = _fold_octaves(out, reference, cfg.octave_fold_low, cfg.octave_fold_high)
corrected = np.where(voiced, corrected, np.nan)
if np.allclose(np.nan_to_num(corrected, nan=0.0), np.nan_to_num(out, nan=0.0)):
break
out = corrected
return out
# --------------------------------------------------------------------------- #
# 主入口
# --------------------------------------------------------------------------- #
def extract_pitch(x: np.ndarray, sr: int, cfg: Config = DEFAULT) -> PitchTrack:
"""对单声道波形提取逐帧基频。"""
x = np.asarray(x, dtype=np.float32).reshape(-1)
frame_len = max(64, int(round(cfg.frame_ms / 1000.0 * sr)))
hop = max(1, int(round(cfg.hop_ms / 1000.0 * sr)))
tau_min = max(2, int(np.floor(sr / cfg.fmax_hz)))
tau_max = int(np.ceil(sr / cfg.fmin_hz))
# 固定积分窗长度,保证 e1 与 τ 无关(YIN 原文做法)
tau_max = min(tau_max, frame_len // 2 - 1)
window = frame_len - tau_max
if window < tau_max or window < 8:
raise ValueError(
f"帧长过短:frame_len={frame_len}, tau_max={tau_max}, window={window}"
)
frames = frame_signal(x, frame_len, hop)
n_frames = frames.shape[0]
times = (np.arange(n_frames) * hop + frame_len / 2.0) / sr
if n_frames == 0:
empty = np.zeros(0)
return PitchTrack(
times=empty,
f0=empty,
midi=empty,
conf=empty,
rms=empty,
voiced=np.zeros(0, dtype=bool),
sr=sr,
hop_s=hop / sr,
frame_s=frame_len / sr,
)
diff = _difference_functions(frames, tau_max, window)
cmndf = _cmndf(diff)
tau, cmndf_at_tau = _pick_tau(cmndf, tau_min, tau_max, cfg.yin_threshold)
f0 = sr / np.maximum(tau, 1e-9)
conf = np.clip(1.0 - cmndf_at_tau, 0.0, 1.0)
rms = np.sqrt(np.mean(np.square(frames, dtype=np.float64), axis=1))
# 双重有声判定:置信度 + 相对峰值能量
peak_rms = float(rms.max()) if rms.size else 0.0
# 绝对静音门限:全零/极低电平信号上 YIN 的 CMNDF 恒为 0,会被误判为满置信度
silence = peak_rms < 1e-5
energy_floor = peak_rms * (10.0 ** (cfg.voicing_db_below_peak / 20.0))
voiced = (
(conf >= cfg.voicing_conf)
& (cmndf_at_tau <= cfg.yin_max_cmndf)
& (rms > energy_floor)
)
if silence:
voiced[:] = False
midi = hz_to_midi(f0)
midi = np.where(voiced, midi, np.nan)
midi = _correct_octaves(midi, voiced, cfg)
return PitchTrack(
times=times,
f0=np.where(voiced, f0, 0.0),
midi=midi,
conf=conf,
rms=rms,
voiced=voiced,
sr=sr,
hop_s=hop / sr,
frame_s=frame_len / sr,
)