File size: 2,560 Bytes
2469e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Audio decoding and log-Mel features.

Frame rate is fixed at 100 fps (24 kHz, hop 240) so a frame index is time in 10 ms units.
"""

from __future__ import annotations

import subprocess

import numpy as np

SAMPLE_RATE = 24_000
HOP = 240
N_FFT = 2048
N_MELS = 128
FMIN, FMAX = 20.0, 12_000.0
FPS = SAMPLE_RATE // HOP  # 100


def decode_audio(path_or_bytes: str | bytes, sr: int = SAMPLE_RATE) -> np.ndarray:
    """Decode to mono float32 with ffmpeg. ffmpeg applies gapless trimming of MP3 encoder delay
    when a LAME/Xing header is present; any remaining offset is measured in Stage 0."""
    src = "pipe:0" if isinstance(path_or_bytes, bytes) else path_or_bytes
    out = subprocess.run(
        ["ffmpeg", "-v", "error", "-i", src, "-vn", "-ac", "1", "-ar", str(sr), "-f", "f32le", "pipe:1"],
        input=path_or_bytes if isinstance(path_or_bytes, bytes) else None,
        capture_output=True,
        check=False,
    )
    if out.returncode != 0:
        raise RuntimeError(out.stderr.decode(errors="replace")[:300])
    return np.frombuffer(out.stdout, dtype=np.float32).copy()


def _hz_to_mel(f):
    # Slaney scale
    f = np.asarray(f, dtype=np.float64)
    lin = f / (200.0 / 3)
    log = 15.0 + np.log(np.maximum(f, 1e-10) / 1000.0) / (np.log(6.4) / 27.0)
    return np.where(f >= 1000.0, log, lin)


def _mel_to_hz(m):
    m = np.asarray(m, dtype=np.float64)
    lin = m * (200.0 / 3)
    log = 1000.0 * np.exp((np.log(6.4) / 27.0) * (m - 15.0))
    return np.where(m >= 15.0, log, lin)


def mel_filterbank(sr=SAMPLE_RATE, n_fft=N_FFT, n_mels=N_MELS, fmin=FMIN, fmax=FMAX) -> np.ndarray:
    freqs = np.linspace(0, sr / 2, n_fft // 2 + 1)
    pts = _mel_to_hz(np.linspace(_hz_to_mel(fmin), _hz_to_mel(fmax), n_mels + 2))
    fb = np.zeros((n_mels, len(freqs)), dtype=np.float32)
    for i in range(n_mels):
        lo, c, hi = pts[i], pts[i + 1], pts[i + 2]
        up = (freqs - lo) / (c - lo)
        down = (hi - freqs) / (hi - c)
        fb[i] = np.maximum(0, np.minimum(up, down)) * (2.0 / (hi - lo))
    return fb


def log_mel(audio: np.ndarray, device: str = "cpu") -> np.ndarray:
    """Return log-Mel [frames, N_MELS] float16, frame k centered at k * 10 ms."""
    import torch

    x = torch.from_numpy(audio).to(device)
    win = torch.hann_window(N_FFT, device=device)
    spec = torch.stft(x, N_FFT, HOP, window=win, center=True, return_complex=True).abs() ** 2
    fb = torch.from_numpy(mel_filterbank()).to(device)
    mel = torch.log(fb @ spec + 1e-6).T  # [frames, mels]
    return mel.to(torch.float16).cpu().numpy()