File size: 2,263 Bytes
b134828
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""What the app does around the Core ML model: front end id `scnet-stft-4096-v1`.

All numpy, no torch, so it's an exact spec for the Swift port (vDSP).
- STFT: rectangular window (none), n_fft 4096, hop 1024, centre=True with reflect padding of 2048,
  one-sided (2049 bins), scaled by 1/sqrt(4096) ("normalized").
- Model input `spec` [1, 4, 2049, T]: channels L.re, L.im, R.re, R.im.
- Model output `stems` [1, 16, 2049, T]: channel (source*2 + lr)*2 + (0 re | 1 im), sources drums, bass, other, vocals.
- iSTFT: irfft each frame (x sqrt(4096)), overlap-add at hop 1024, divide by the window envelope
  (how many frames cover each sample), drop 2048 samples at the start.
- Before the STFT the segment is padded at the end so T is even (see pad_amount).
"""
import numpy as np

NFFT, HOP = 4096, 1024


def pad_amount(n: int) -> int:
    pad = HOP - n % HOP
    if (n + pad) // HOP % 2 == 0:
        pad += HOP
    return pad


def frames_for(n: int) -> int:
    return (n + pad_amount(n)) // HOP + 1


def stft(x: np.ndarray) -> np.ndarray:
    """x [2, n] float32 (n already padded) -> spec [1, 4, 2049, T] float32."""
    xp = np.pad(x, ((0, 0), (NFFT // 2, NFFT // 2)), mode="reflect")
    t = 1 + (xp.shape[1] - NFFT) // HOP
    idx = np.arange(NFFT)[None, :] + HOP * np.arange(t)[:, None]
    spec = np.fft.rfft(xp[:, idx], axis=-1) / np.sqrt(NFFT)          # [2, T, 2049]
    out = np.stack([spec.real, spec.imag], axis=1)                    # [2, 2, T, 2049]
    return out.transpose(0, 1, 3, 2).reshape(1, 4, NFFT // 2 + 1, t).astype(np.float32)


def istft(stems: np.ndarray, n: int) -> np.ndarray:
    """stems [1, 16, 2049, T] -> [4, 2, n] (n = padded length given to stft)."""
    t = stems.shape[-1]
    s = stems.reshape(4, 2, 2, NFFT // 2 + 1, t)
    spec = (s[:, :, 0] + 1j * s[:, :, 1]).transpose(0, 1, 3, 2)      # [4, 2, T, 2049]
    frames = np.fft.irfft(spec * np.sqrt(NFFT), n=NFFT, axis=-1)      # [4, 2, T, 4096]
    total = NFFT + HOP * (t - 1)
    y = np.zeros((4, 2, total))
    env = np.zeros(total)
    for i in range(t):
        y[..., i * HOP:i * HOP + NFFT] += frames[:, :, i]
        env[i * HOP:i * HOP + NFFT] += 1.0
    y = y[..., NFFT // 2: NFFT // 2 + n]
    return (y / env[NFFT // 2: NFFT // 2 + n]).astype(np.float32)