← zidingz.com

core.py

← Gallery · core.py · scenes.py · render.py · fidelity.py · export_live.py

"""Core: audio -> features. Same toolkit as doppler-geo/code/dg.py (STFT, whitening,
log-frequency resampling, Viterbi ridge), retuned from aircraft (20-500 Hz, 4 s windows)
to a piano (27.5-4186 Hz, 90-370 ms windows)."""
import subprocess, numpy as np
from scipy import signal, ndimage

SR = 22050
HOP = 441            # 20 ms -> 50 feature frames per second
FPS_A = SR / HOP
BPS = 3              # log-frequency bins per semitone
A0 = 27.5
NKEY = 88
NB = NKEY * BPS


def load(path, t0=0.0, dur=None, sr=SR):
    cmd = ["ffmpeg", "-v", "error", "-ss", str(t0)] + (["-t", str(dur)] if dur else []) + \
          ["-i", path, "-ac", "1", "-ar", str(sr), "-f", "f32le", "-"]
    return np.frombuffer(subprocess.run(cmd, capture_output=True, check=True).stdout, np.float32).copy()


def _stft(x, n):
    f, t, Z = signal.stft(x, SR, window="hann", nperseg=n, noverlap=n - HOP, boundary="zeros", padded=True)
    return f, np.abs(Z).astype(np.float32) * (n ** 0.5)


def logspec(x, bps=BPS):
    """Log-frequency magnitude, NB bins x T frames. Long window below A4, short above:
    the Gabor limit (dt*df >= 1/4pi) means no single window resolves both a low A0-A#0
    semitone (1.6 Hz apart) and a 20 ms attack."""
    nb = NKEY * bps
    fc = A0 * 2 ** ((np.arange(nb) - (bps - 1) / 2) / (12 * bps))
    out = None
    for n, lo, hi in ((8192, 0, 440.0), (2048, 440.0, 1e9)):
        f, M = _stft(x, n)
        sel = (fc >= lo) & (fc < hi)
        idx = np.interp(fc[sel], f, np.arange(len(f)))
        i0 = np.floor(idx).astype(int); w = (idx - i0)[:, None]
        part = M[i0] * (1 - w) + M[np.minimum(i0 + 1, len(f) - 1)] * w
        if out is None: out = np.zeros((nb, M.shape[1]), np.float32)
        out[sel, :part.shape[1]] = part[:, :out.shape[1]]
    return fc, out


def whiten(L, tmed=401, fmed=25):
    """dg.Spec-style whitening: divide by the per-bin time median (kills steady hiss / hum /
    the shellac surface) then by a local along-frequency median (flattens spectral tilt)."""
    P = np.log(L + 1e-6)
    P -= np.median(P, axis=1, keepdims=True)
    P -= ndimage.median_filter(P, size=(fmed, 1), mode="nearest")
    return np.maximum(P, 0)


class Analysis:
    def __init__(s, x):
        s.x = x; s.dur = len(x) / SR
        s.fc, s.L = logspec(x)
        s.W = whiten(s.L)
        T = s.L.shape[1]; s.T = T
        # 88 key energies, with lateral inhibition: a Hann main lobe is wider than a low semitone,
        # so a key only counts if it beats both neighbours
        K = s.W.reshape(NKEY, BPS, T).max(1)
        nb = np.maximum(np.pad(K, ((1, 0), (0, 0)))[:-1], np.pad(K, ((0, 1), (0, 0)))[1:])
        s.K = K * (K >= nb)
        # overtone suppression: discount a key by the louder lower keys it could be partial 2..7 of
        Kc = s.K.copy()
        for st, g in ((12, .7), (19, .7), (24, .5), (28, .5), (31, .4), (34, .4)):
            Kc[st:] -= g * s.K[:-st]
        s.Kc = np.maximum(Kc, 0)
        s.rms = np.sqrt((np.pad(x, (0, T * HOP))[:T * HOP].reshape(T, HOP).astype(np.float64) ** 2).mean(1))
        s.loud = ndimage.gaussian_filter1d(s.rms, 12) / (np.percentile(s.rms, 99) + 1e-9)
        # spectral flux onset strength
        d = np.diff(np.log1p(20 * s.L / (s.L.mean() + 1e-9)), axis=1, prepend=0)
        s.flux = np.maximum(d, 0).sum(0); s.flux /= np.percentile(s.flux, 99) + 1e-9
        # chroma (A=0) and Harte tonal centroid (fifths, minor-thirds, major-thirds circles)
        s.chroma = s.Kc[:84].reshape(7, 12, T).sum(0)
        c = ndimage.gaussian_filter1d(s.chroma, 30, axis=1); c = c / (c.sum(0) + 1e-9)
        s.chroma_s = c
        # harmony chroma from the UN-whitened log magnitude, C2..C6. Whitening removes whatever is
        # steady, which is right for propeller hum and wrong here: the steady thing is the tonic pedal.
        Lm = np.log1p(50 * s.L / s.L.max()).reshape(NKEY, BPS, T).max(1)
        h = np.zeros((12, T), np.float32)
        for kk in range(15, 63): h[kk % 12] += Lm[kk]
        h = ndimage.gaussian_filter1d(h, 40, axis=1); h -= h.min(0, keepdims=True)
        s.chroma_h = h / (h.max(0, keepdims=True) + 1e-9)
        k = np.arange(12)[:, None]
        s.tc = np.stack([(c * f(k * a)).sum(0) for a in (7 * np.pi / 6, 3 * np.pi / 2, 2 * np.pi / 3) for f in (np.sin, np.cos)])

    def at(s, arr, t):
        """Linear sample of a feature array (last axis = time) at time t (seconds)."""
        i = np.clip(t * FPS_A, 0, s.T - 1.001); i0 = int(i); w = i - i0
        return arr[..., i0] * (1 - w) + arr[..., i0 + 1] * w


def ridge(W, f_lo, f_hi, max_jump=6, jump_cost=0.6):
    """dg.ridge: Viterbi path through the whitened spectrogram. For a flyover it follows one
    Doppler-sliding propeller harmonic; here it follows the top voice."""
    S = W[f_lo:f_hi]; nf, nt = S.shape
    cost = np.full(nf, 0.0); back = np.zeros((nt, nf), np.int16)
    offs = np.arange(-max_jump, max_jump + 1)
    for t in range(nt):
        cand = np.stack([np.roll(cost, o) - jump_cost * abs(o) for o in offs])
        for j, o in enumerate(offs):
            if o > 0: cand[j, :o] = -1e9
            elif o < 0: cand[j, o:] = -1e9
        b = cand.argmax(0); back[t] = b
        cost = cand[b, np.arange(nf)] + S[:, t]
    path = np.zeros(nt, int); path[-1] = cost.argmax()
    for t in range(nt - 1, 0, -1):
        path[t - 1] = path[t] - offs[back[t, path[t]]]
    return path + f_lo, S[path, np.arange(nt)]


# ---------- rendering helpers ----------
def cmap(stops):
    xs = np.array([s[0] for s in stops]); cs = np.array([s[1] for s in stops], float)
    lut = np.stack([np.interp(np.linspace(0, 1, 1024), xs, cs[:, i]) for i in range(3)], 1)
    return lambda v: lut[(np.clip(v, 0, 1) * 1023).astype(int)]


# icon palette: lampblack -> oxblood -> bronze -> gold leaf -> candle white
GOLD = cmap([(0, (6, 7, 12)), (.25, (48, 14, 22)), (.5, (128, 52, 24)), (.75, (214, 150, 52)), (.92, (250, 220, 150)), (1, (255, 250, 235))])
# night sea: for the negative half of signed fields
SEA = cmap([(0, (6, 7, 12)), (.4, (14, 34, 66)), (.8, (60, 120, 160)), (1, (190, 230, 240))])
MAGMA = cmap([(0, (4, 3, 14)), (.3, (60, 16, 96)), (.6, (182, 54, 96)), (.85, (250, 150, 80)), (1, (252, 250, 200))])


def signed(u):
    """Signed field -> RGB: crests gold, troughs sea."""
    return np.where((u >= 0)[..., None], GOLD(u), SEA(-u))


class Video:
    def __init__(s, path, w, h, fps, audio=None, t0=0, dur=None):
        cmd = ["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{w}x{h}", "-r", str(fps), "-i", "-"]
        if audio: cmd += ["-ss", str(t0)] + (["-t", str(dur)] if dur else []) + ["-i", audio, "-c:a", "aac", "-b:a", "192k", "-shortest"]
        cmd += ["-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p", "-movflags", "+faststart", path]
        s.p = subprocess.Popen(cmd, stdin=subprocess.PIPE)

    def write(s, rgb):
        s.p.stdin.write(np.clip(rgb, 0, 255).astype(np.uint8).tobytes())

    def close(s):
        s.p.stdin.close(); s.p.wait()


def save_png(path, rgb):
    from PIL import Image
    Image.fromarray(np.clip(rgb, 0, 255).astype(np.uint8)).save(path)