#!/usr/bin/env python3
"""Generates every sound of "Experience - Rob revisited" (games/alis/assets/revisited/sfx/ and music/).

All ORIGINAL: synthesised here from noise, oscillators, formant voices and convolution reverbs. No sample, no
download, no outside recording. Deterministic (fixed seeds). Run from anywhere:

    python3 -I games/alis/tools/reborn/sounds.py

Needs numpy; ffmpeg (libvorbis) for the music. Outputs:
  sfx/<name>.wav    22050 Hz, mono, 16-bit PCM (what SoundManager AND Audio3d both read: Audio3d wants PCM WAV)
  music/<name>.ogg  22050 Hz stereo Vorbis loops (SoundManager::loadMusic)

Loops (bed_*, *_loop, music) are built CIRCULARLY (noise shaped in the frequency domain of exactly the loop length,
events wrapped modulo the length, circular reverbs, LFOs with whole cycles): they are seamless by construction, and
checked. At the end every file is analysed (peak, loudness, clipping, loop seam) and the script fails on a problem.
"""
import math
import os
import shutil
import subprocess
import sys
import tempfile
import wave

import numpy as np

ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'assets', 'revisited')
SFX = os.path.join(ROOT, 'sfx')
MUSIC = os.path.join(ROOT, 'music')
SR = 22050
PEAK = 10 ** (-1.0 / 20)          # -1 dBFS ceiling

# loudness targets (dBFS of the loud part, 95th percentile of 50 ms RMS frames) by family
TARGET = {
    'step': -21, 'stepsoft': -29, 'land': -20, 'body': -22, 'voice': -20, 'ui': -26, 'chime': -22,
    'action': -21, 'thunder': -16, 'bed': -22, 'loop': -20, 'creature': -15, 'howl': -14, 'stinger': -17,
    'call': -18, 'music': -36,
}

REPORT = []


# ------------------------------------------------------------------------------------------ basics

def rng(seed):
    return np.random.default_rng(seed)


def n_of(d):
    return int(round(d * SR))


def tt(n):
    return np.arange(n) / SR


def mag_band(f, lo=None, hi=None, order=2.0):
    """Smooth Butterworth-like magnitude."""
    m = np.ones_like(f)
    ff = np.maximum(f, 1e-3)
    if lo:
        m /= np.sqrt(1 + (lo / ff) ** (2 * order))
    if hi:
        m /= np.sqrt(1 + (ff / hi) ** (2 * order))
    return m


def ffilt(x, lo=None, hi=None, order=2.0, circular=False, extra=None):
    """Zero-phase FFT filter. circular=True for loops (wraps), else padded."""
    n = len(x)
    pad = 0 if circular else min(4096, n)
    y = np.concatenate([x, np.zeros(pad)]) if pad else x
    X = np.fft.rfft(y)
    f = np.fft.rfftfreq(len(y), 1 / SR)
    m = mag_band(f, lo, hi, order)
    if extra is not None:
        m = m * extra(f)
    out = np.fft.irfft(X * m, len(y))
    return out[:n]


def peaky(f, centre, q, gain=1.0):
    """A resonance (for formants / whistles)."""
    bw = centre / q
    return gain / (1 + ((f - centre) / bw) ** 2)


def noise(n, r, colour='white', circular=False):
    w = r.standard_normal(n)
    if colour == 'white':
        return w
    X = np.fft.rfft(w)
    f = np.maximum(np.fft.rfftfreq(n, 1 / SR), 10.0)
    X *= {'pink': 1 / np.sqrt(f), 'brown': 1 / f}[colour]
    y = np.fft.irfft(X, n)
    return y / (np.std(y) + 1e-12)


def penv(n, rate, r, lo=0.0, hi=1.0):
    """A smooth random envelope, periodic over n (for loops), changing about `rate` times a second."""
    w = r.standard_normal(n)
    X = np.fft.rfft(w)
    f = np.fft.rfftfreq(n, 1 / SR)
    X *= np.exp(-(f / max(rate, 0.01)) ** 2)
    X[0] = 0
    y = np.fft.irfft(X, n)
    y = (y - y.min()) / (y.max() - y.min() + 1e-12)
    return lo + (hi - lo) * y


def env_ad(n, attack, decay_tau, hold=0.0):
    t = tt(n)
    a = np.clip(t / max(attack, 1e-4), 0, 1)
    d = np.where(t < attack + hold, 1.0, np.exp(-(t - attack - hold) / decay_tau))
    return a * d


def fade(x, fin=0.003, fout=0.02):
    x = x.copy()
    a, b = n_of(fin), n_of(fout)
    if a:
        x[:a] *= np.linspace(0, 1, a)
    if b:
        x[-b:] *= np.linspace(1, 0, b)
    return x


def ir(seconds, tau, r, lo=None, hi=6000, early=None):
    """A reverb impulse response: decaying filtered noise (+ discrete early echoes)."""
    n = n_of(seconds)
    h = noise(n, r) * np.exp(-tt(n) / tau)
    h = ffilt(h, lo, hi)
    if early:
        for d, g in early:
            i = n_of(d)
            if i < n:
                h[i] += g * 3
    h[0] += 0.0
    return h / np.sqrt(np.sum(h ** 2) + 1e-12)


def convolve(x, h, circular=False):
    if circular:
        n = len(x)
        hh = np.zeros(n)
        m = min(n, len(h))
        hh[:m] = h[:m]
        return np.fft.irfft(np.fft.rfft(x) * np.fft.rfft(hh), n)
    n = len(x) + len(h) - 1
    size = 1 << (n - 1).bit_length()
    return np.fft.irfft(np.fft.rfft(x, size) * np.fft.rfft(h, size), size)[:n]


def reverb(x, h, wet, circular=False):
    if circular:
        return (1 - wet) * x + wet * convolve(x, h, True) * (np.std(x) / (np.std(convolve(x, h, True)) + 1e-12))
    y = convolve(x, h)
    dry = np.concatenate([x, np.zeros(len(y) - len(x))])
    wy = y * (np.std(x) / (np.std(y[:len(x)]) + 1e-12))
    return (1 - wet) * dry + wet * wy


def place(buf, ev, at, circular=True, gain=1.0):
    """Adds an event into buf at sample `at` (wrapping for loops)."""
    n = len(buf)
    ev = ev * gain
    if circular:
        idx = (np.arange(len(ev)) + at) % n
        np.add.at(buf, idx, ev)
    else:
        end = min(n, at + len(ev))
        if end > at:
            buf[at:end] += ev[:end - at]
    return buf


def osc(freq, n, shape='sine', phase0=0.0):
    """freq: scalar or array (per sample)."""
    f = np.full(n, float(freq)) if np.isscalar(freq) else freq
    ph = phase0 + 2 * np.pi * np.cumsum(f) / SR
    if shape == 'sine':
        return np.sin(ph)
    if shape == 'tri':
        return 2 / np.pi * np.arcsin(np.sin(ph))
    if shape == 'saw':     # band-limited by additive (cheap enough for low notes)
        out = np.zeros(n)
        k = 1
        fmax = np.max(f)
        while k * fmax < SR / 2 * 0.9 and k < 60:
            out += np.sin(k * ph) / k
            k += 1
        return out * 0.6
    raise ValueError(shape)


def voice(f0, formants, r, breath=0.08, jitter=0.0, tilt=1.0, rough=0.0, kmax=48):
    """A wordless formant voice: harmonics of f0 (per-sample array) weighted by moving formants.
    formants: list of (freq array or scalar, Q, gain)."""
    n = len(f0)
    if jitter:
        f0 = f0 * (1 + jitter * ffilt(r.standard_normal(n), None, 30, circular=True) / 0.15)
    if rough:   # vocal fry / growl: fast random AM + subharmonic
        am = 1 + rough * ffilt(r.standard_normal(n), 15, 80, circular=True) * 4
    else:
        am = 1.0
    ph = 2 * np.pi * np.cumsum(f0) / SR
    out = np.zeros(n)
    fsr = [(np.full(n, float(F)) if np.isscalar(F) else F, q, g) for F, q, g in formants]
    for k in range(1, kmax + 1):
        fk = k * f0
        ok = fk < SR * 0.45
        if not ok.any():
            break
        a = np.zeros(n)
        for F, q, g in fsr:
            a += g / (1 + ((fk - F) / (F / q)) ** 2)
        a *= ok / (k ** tilt)
        out += a * np.sin(k * ph)
    if rough:
        out += rough * 0.5 * np.sin(ph / 2) * np.mean([g for _, _, g in fsr])
    out *= am
    if breath:
        w = r.standard_normal(n)
        b = np.zeros(n)
        # breath through the average formant positions
        X = np.fft.rfft(np.concatenate([w, np.zeros(2048)]))
        f = np.fft.rfftfreq(n + 2048, 1 / SR)
        m = np.zeros_like(f)
        for F, q, g in fsr:
            m += peaky(f, float(np.mean(F)), q * 0.7, g)
        b = np.fft.irfft(X * m, n + 2048)[:n]
        out += breath * b * np.std(out) / (np.std(b) + 1e-12)
    return out


def glide(n, points):
    """Piecewise curve: points = [(t 0..1, value), ...] smoothed (cosine)."""
    x = np.linspace(0, 1, n)
    ts = [p[0] for p in points]
    vs = [p[1] for p in points]
    y = np.interp(x, ts, vs)
    k = max(1, n // 200)
    return np.convolve(np.pad(y, (k, k), mode='edge'), np.ones(2 * k + 1) / (2 * k + 1), mode='same')[k:-k]


# ------------------------------------------------------------------------------------------ output + analysis

def loudness(x):
    fr = n_of(0.05)
    if len(x) < fr:
        return 20 * math.log10(np.sqrt(np.mean(x ** 2)) + 1e-12)
    m = len(x) // fr
    rms = np.sqrt(np.mean(x[:m * fr].reshape(m, fr) ** 2, axis=1))
    return 20 * math.log10(np.percentile(rms, 95) + 1e-12)


def normalise(x, family):
    x = x - np.mean(x)
    target = TARGET[family]
    knee = 0.5
    for _ in range(4):            # loudness, then a soft limiter on the peaks above the knee (transients)
        x = x * 10 ** ((target - loudness(x)) / 20)
        a = np.abs(x)
        over = a > knee
        if not over.any():
            break
        a[over] = knee + (PEAK - knee) * np.tanh((a[over] - knee) / (PEAK - knee))
        x = np.sign(x) * a
    p = np.max(np.abs(x))
    if p > PEAK:
        x = x * (PEAK / p)
    return x


def trim(x, floor_db=-50.0):
    """Cuts the silent tail (reverbs leave long near-silent ends)."""
    lim = np.max(np.abs(x)) * 10 ** (floor_db / 20)
    idx = np.nonzero(np.abs(x) > lim)[0]
    end = min(len(x), (idx[-1] if len(idx) else len(x)) + n_of(0.02))
    return x[:end]


def seam(x):
    """Loop seam: the jump at the wrap compared with the typical sample-to-sample step, and the RMS on each side."""
    d = np.abs(np.diff(x))
    jump = abs(x[0] - x[-1]) / (np.percentile(d, 99) + 1e-9)
    w = n_of(0.4)
    a = np.sqrt(np.mean(x[-w:] ** 2)) + 1e-9
    b = np.sqrt(np.mean(x[:w] ** 2)) + 1e-9
    return jump, abs(20 * math.log10(a / b))


def save_wav(name, x, family, loop=False):
    x = normalise(np.asarray(x, dtype=np.float64), family)
    if not loop:
        x = fade(trim(x), 0.002, 0.03)
    data = np.round(x * 32767).astype('<i2')
    path = os.path.join(SFX, name + '.wav')
    with wave.open(path, 'wb') as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(SR)
        w.writeframes(data.tobytes())
    REPORT.append(analyse(name + '.wav', x, family, loop, os.path.getsize(path)))


def save_ogg(name, left, right):
    st = np.stack([left, right], axis=1)
    st -= st.mean(axis=0)
    loud = loudness((left + right) / 2)
    st *= 10 ** ((TARGET['music'] - loud) / 20)
    p = np.max(np.abs(st))
    if p > PEAK:
        st *= PEAK / p
    data = np.round(st * 32767).astype('<i2')
    tmp = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
    tmp.close()
    with wave.open(tmp.name, 'wb') as w:
        w.setnchannels(2)
        w.setsampwidth(2)
        w.setframerate(SR)
        w.writeframes(data.tobytes())
    path = os.path.join(MUSIC, name + '.ogg')
    subprocess.run(['ffmpeg', '-loglevel', 'error', '-y', '-i', tmp.name, '-c:a', 'libvorbis', '-q:a', '3', path], check=True)
    os.unlink(tmp.name)
    REPORT.append(analyse(name + '.ogg', st.mean(axis=1), 'music', True, os.path.getsize(path)))


def analyse(fname, x, family, loop, size):
    peak = 20 * math.log10(np.max(np.abs(x)) + 1e-12)
    clip = int(np.sum(np.abs(x) >= 0.999))
    row = {'file': fname, 'sec': len(x) / SR, 'peak': peak, 'loud': loudness(x), 'target': TARGET[family], 'clip': clip,
           'size': size, 'loop': loop, 'jump': 0.0, 'step': 0.0}
    if loop:
        row['jump'], row['step'] = seam(x)
    return row


# ------------------------------------------------------------------------------------------ footsteps

def thump(n, f0, r, tau=0.04):
    t = tt(n)
    f = f0 * (1 + 0.8 * np.exp(-t / 0.015))
    return osc(f, n) * np.exp(-t / tau)


def grains(n, density, r, lo, hi, length=0.004, tau=None, amp_spread=1.0):
    """A cloud of tiny filtered clicks (crunch, crackle, rustle). density: per second (scalar or array)."""
    out = np.zeros(n)
    dens = np.full(n, float(density)) if np.isscalar(density) else density
    p = dens / SR
    hits = np.nonzero(r.random(n) < p)[0]
    gl = max(8, n_of(length))
    g = np.exp(-tt(gl) / (tau or length / 3))
    for h in hits:
        a = r.random() ** amp_spread
        e = r.standard_normal(gl) * g * a
        place(out, e, int(h), circular=False)
    return ffilt(out, lo, hi)


def step(ground, var, soft):
    r = rng(1000 + var * 17 + sum(map(ord, ground)) * 3)   # soft = the same step, filtered (same seed)
    d = {'cave': 0.22, 'water': 0.42, 'mud': 0.38, 'leaves': 0.34, 'snow': 0.32}.get(ground, 0.26)
    n = n_of(d)
    t = tt(n)
    e = env_ad(n, 0.004, d / 4)
    heel = np.exp(-t / 0.03)
    toe = np.exp(-np.maximum(t - 0.07 - r.random() * 0.03, 0) / 0.04) * (t > 0.07)
    if ground == 'grass':
        x = 0.5 * thump(n, 70 + 10 * var, r) + grains(n, 900 * (heel + 0.6 * toe), r, 1500, 7000, 0.006) * 1.2
        x += 0.3 * ffilt(noise(n, r), 2000, 6000) * e
    elif ground == 'leaves':
        x = 0.4 * thump(n, 65, r) + grains(n, 600 * (heel + 0.8 * toe) + 80, r, 900, 6500, 0.01, amp_spread=3) * 1.6
        x += 0.25 * ffilt(noise(n, r), 1200, 5000) * env_ad(n, 0.01, 0.12)
    elif ground == 'mud':
        sweep = osc(glide(n, [(0, 380), (0.3, 180), (1, 120)]), n) * env_ad(n, 0.02, 0.08, 0.05)
        x = 0.5 * thump(n, 55, r, 0.06) + 0.6 * ffilt(noise(n, r), 150, 900) * env_ad(n, 0.01, 0.1) + 0.3 * sweep
        pop = osc(glide(n, [(0, 700), (1, 1400)]), n) * np.exp(-np.maximum(t - 0.22, 0) / 0.02) * (t > 0.22)
        x += 0.25 * pop
    elif ground == 'water':
        x = 0.3 * thump(n, 60, r) + 0.9 * ffilt(noise(n, r), 600, 6000) * env_ad(n, 0.008, 0.09)
        for _ in range(5 + var):
            bn = n_of(0.05)
            b0 = 500 + r.random() * 1200
            bub = osc(np.linspace(b0, b0 * 1.8, bn), bn) * np.exp(-tt(bn) / 0.015)
            place(x, bub * 0.25, int(r.random() * n * 0.7), circular=False)
    elif ground == 'sand':
        x = 0.25 * thump(n, 60, r) + grains(n, 2500 * (heel + 0.7 * toe), r, 2500, 9000, 0.002) * 0.8
        x += 0.35 * ffilt(noise(n, r), 1500, 5000) * env_ad(n, 0.01, 0.07)
    elif ground in ('rock', 'cave'):
        click = ffilt(r.standard_normal(n) * np.exp(-t / 0.004), 800, 5000)
        x = 0.6 * thump(n, 90 + 15 * var, r, 0.025) + 0.8 * click + grains(n, 300 * heel, r, 2000, 7000, 0.002) * 0.5
        tick = ffilt(r.standard_normal(n) * np.exp(-np.maximum(t - 0.08, 0) / 0.004) * (t > 0.08), 1500, 6000)
        x += 0.4 * tick
    elif ground == 'snow':
        dens = 2200 * (np.exp(-t / 0.06) + 0.8 * np.exp(-np.maximum(t - 0.09, 0) / 0.07) * (t > 0.09))
        x = 0.35 * thump(n, 55, r, 0.05) + grains(n, dens, r, 600, 4500, 0.004, amp_spread=1.5) * 1.3
    else:
        raise ValueError(ground)
    x = x * (0.9 + 0.2 * r.random())
    if ground == 'cave':
        x = reverb(x, ir(0.9, 0.22, rng(5), 200, 4000, [(0.09, 0.5), (0.17, 0.3)]), 0.45)
    if soft:
        x = ffilt(x, None, 2500)
    return x


# ------------------------------------------------------------------------------------------ body, voices

def breath(var):
    r = rng(300 + var)
    n = n_of(1.15)
    t = tt(n)
    inh = np.sin(np.clip(t / 0.42, 0, 1) * np.pi) ** 2 * (t < 0.42)
    exh = np.sin(np.clip((t - 0.5) / 0.55, 0, 1) * np.pi) ** 1.5 * (t > 0.5)
    w = noise(n, r)
    a = ffilt(w, 900, 3500, extra=lambda f: peaky(f, 1800, 2) + 0.3) * inh
    b = ffilt(w, 300, 2200, extra=lambda f: peaky(f, 900, 2) + peaky(f, 1300, 3)) * exh * (1.3 if var == 2 else 1.0)
    return a * 0.7 + b


def heartbeat():
    n = n_of(0.62)
    t = tt(n)
    x = np.zeros(n)
    for at, f0, g in [(0.0, 58, 1.0), (0.26, 70, 0.65)]:
        m = n - n_of(at)
        tl = tt(m)
        b = osc(f0 * (1 + 0.6 * np.exp(-tl / 0.02)), m) * (1 - np.exp(-tl / 0.004)) * np.exp(-tl / 0.07)
        x[n_of(at):] += g * b
    return ffilt(x + 0.15 * ffilt(noise(n, rng(9)), 30, 150) * np.exp(-t / 0.08), None, 220)


def pain(var):
    r = rng(400 + var)
    d = [0.38, 0.5, 0.3][var - 1]
    n = n_of(d)
    f0 = glide(n, [(0, [150, 170, 135][var - 1]), (0.2, [165, 190, 150][var - 1]), (1, [110, 120, 100][var - 1])])
    v = voice(f0, [(glide(n, [(0, 650), (1, 550)]), 5, 1.0), (1100, 6, 0.6), (2500, 8, 0.25)], r, breath=0.35, jitter=0.01, rough=0.2)
    e = env_ad(n, 0.015, d * 0.35, d * 0.25)
    return v * e


def death_voice():
    r = rng(450)
    n = n_of(1.6)
    f0 = glide(n, [(0, 160), (0.15, 175), (1, 70)])
    v = voice(f0, [(glide(n, [(0, 700), (1, 450)]), 5, 1.0), (glide(n, [(0, 1100), (1, 800)]), 6, 0.6)], r, breath=0.5, jitter=0.02, rough=0.4)
    return v * env_ad(n, 0.03, 0.5, 0.6)


def jump_voice():
    r = rng(460)
    n = n_of(0.22)
    f0 = glide(n, [(0, 140), (1, 160)])
    v = voice(f0, [(550, 4, 1.0), (1000, 5, 0.5)], r, breath=0.8)
    return v * env_ad(n, 0.01, 0.06, 0.05) * 0.7 + 0.4 * ffilt(noise(n, r), 300, 2000) * env_ad(n, 0.005, 0.05)


def land(hard):
    r = rng(470 + hard)
    n = n_of(0.5 if hard else 0.32)
    t = tt(n)
    x = (1.0 if hard else 0.6) * thump(n, 48, r, 0.09 if hard else 0.06)
    x += grains(n, 1500 * np.exp(-t / 0.05), r, 600, 5000, 0.004) * (1.2 if hard else 0.8)
    x += 0.4 * ffilt(noise(n, r), 80, 600) * np.exp(-t / 0.05)
    return x


def swim(var):
    r = rng(500 + var)
    n = n_of(0.9)
    t = tt(n)
    sw = np.sin(np.clip(t / 0.7, 0, 1) * np.pi) ** 2
    x = np.zeros(n)
    centre = glide(n, [(0, 500), (0.5, 1400), (1, 700)])
    w = noise(n, r)
    # a moving band: three fixed bands cross-faded by the centre frequency
    for c in (500, 900, 1500):
        g = np.exp(-((centre - c) / 400) ** 2)
        x += ffilt(w, c * 0.6, c * 1.6) * g
    x *= sw
    for _ in range(8):
        bn = n_of(0.04)
        b0 = 600 + r.random() * 1500
        place(x, osc(np.linspace(b0, b0 * 2, bn), bn) * np.exp(-tt(bn) / 0.012) * 0.3, int((0.3 + 0.6 * r.random()) * n * 0.8), circular=False)
    return x


def splash_big():
    r = rng(520)
    n = n_of(1.2)
    t = tt(n)
    x = 0.6 * thump(n, 50, r, 0.1) + 1.2 * ffilt(noise(n, r), 400, 8000) * env_ad(n, 0.01, 0.2)
    for _ in range(30):
        bn = n_of(0.05)
        b0 = 400 + r.random() * 1800
        place(x, osc(np.linspace(b0, b0 * 1.9, bn), bn) * np.exp(-tt(bn) / 0.015) * 0.3, int(r.random() * n * 0.85), circular=False)
    return x


# ------------------------------------------------------------------------------------------ ui, actions

def bell(freq, d, r, partials=((1, 1.0, 1.0), (2.0, 0.5, 0.6), (3.01, 0.25, 0.4), (4.2, 0.12, 0.25)), strike=0.002):
    n = n_of(d)
    t = tt(n)
    x = np.zeros(n)
    for ratio, g, dec in partials:
        x += g * np.sin(2 * np.pi * freq * ratio * t + r.random() * 6) * np.exp(-t / (d * 0.35 * dec))
    return x * np.clip(t / strike, 0, 1)


def arpeggio(notes, gap, d, seed, wet=0.35, partials=None):
    r = rng(seed)
    n = n_of(gap * len(notes) + d)
    x = np.zeros(n)
    for i, f in enumerate(notes):
        b = bell(f, d, r) if partials is None else bell(f, d, r, partials)
        place(x, b * (1 - 0.08 * i), n_of(i * gap), circular=False)
    return reverb(x, ir(1.6, 0.45, rng(seed + 1), 200, 7000), wet)


def ui_click():
    r = rng(600)
    n = n_of(0.05)
    t = tt(n)
    return osc(2200, n) * np.exp(-t / 0.006) + 0.3 * ffilt(r.standard_normal(n) * np.exp(-t / 0.002), 2000, 8000)


def ui_tones(fs, seed):
    r = rng(seed)
    x = np.zeros(n_of(0.3))
    for i, f in enumerate(fs):
        m = n_of(0.16)
        place(x, bell(f, 0.16, r, ((1, 1, 1), (2, 0.3, 0.5))), n_of(i * 0.07), circular=False)
    return x


def eat():
    r = rng(620)
    n = n_of(1.0)
    x = np.zeros(n)
    for i in range(3):
        m = n_of(0.16)
        tl = tt(m)
        c = grains(m, 1800 * np.exp(-tl / 0.05), r, 800, 6000, 0.003) + 0.4 * ffilt(noise(m, r), 200, 1200) * np.exp(-tl / 0.05)
        place(x, c * (1 - 0.2 * i), n_of(0.05 + i * 0.3), circular=False)
    return x


def drink():
    r = rng(630)
    n = n_of(1.1)
    x = np.zeros(n)
    for i in range(3):
        m = n_of(0.14)
        tl = tt(m)
        f = glide(m, [(0, 220 + 20 * i), (1, 480 + 30 * i)])
        g = osc(f, m) * np.sin(np.clip(tl / 0.12, 0, 1) * np.pi) + 0.2 * ffilt(noise(m, r), 200, 1500) * np.exp(-tl / 0.04)
        place(x, g, n_of(0.08 + i * 0.32), circular=False)
    return x + 0.08 * ffilt(noise(n, r), 1500, 5000) * env_ad(n, 0.05, 0.4)


def knock(f, d, r, q=8):
    n = n_of(d)
    t = tt(n)
    exc = r.standard_normal(n) * np.exp(-t / 0.003)
    return ffilt(exc, None, None, extra=lambda fr: peaky(fr, f, q) + peaky(fr, f * 2.3, q, 0.5) + 0.05) * np.exp(-t / (d / 3))


def chop():
    r = rng(640)
    n = n_of(0.6)
    t = tt(n)
    x = knock(240, 0.6, r, 6) * 1.5 + 0.6 * thump(n, 80, r, 0.05) + 0.5 * ffilt(r.standard_normal(n) * np.exp(-t / 0.01), 1500, 6000)
    crack = grains(n, 2000 * np.exp(-np.maximum(t - 0.03, 0) / 0.04) * (t > 0.03), r, 1500, 6000, 0.003)
    return x + crack * 0.6


def mine():
    r = rng(650)
    n = n_of(0.8)
    t = tt(n)
    x = np.zeros(n)
    for ratio, g in [(1, 1), (2.7, 0.6), (5.1, 0.35), (8.3, 0.2)]:
        x += g * np.sin(2 * np.pi * 1450 * ratio * t) * np.exp(-t / (0.12 / ratio ** 0.3))
    x += 0.8 * ffilt(r.standard_normal(n) * np.exp(-t / 0.005), 1000, 8000)
    x += grains(n, 600 * np.exp(-t / 0.15), r, 1500, 7000, 0.003) * 0.5
    return x


def craft():
    r = rng(660)
    n = n_of(1.2)
    x = np.zeros(n)
    for i, (f, at) in enumerate([(320, 0.0), (420, 0.28), (300, 0.5), (500, 0.85)]):
        place(x, knock(f, 0.25, r, 6), n_of(at), circular=False)
    x += 0.35 * ffilt(noise(n, r), 1500, 6000) * penv(n, 6, r, 0.1, 1.0) * env_ad(n, 0.05, 0.5, 0.4)
    return x


def pickup():
    r = rng(670)
    n = n_of(0.35)
    t = tt(n)
    x = 0.5 * ffilt(noise(n, r), 1200, 5000) * env_ad(n, 0.02, 0.06)
    x += 0.5 * osc(glide(n, [(0, 300), (1, 520)]), n) * np.exp(-np.maximum(t - 0.08, 0) / 0.04) * (t > 0.08)
    return x


def swing():
    r = rng(680)
    n = n_of(0.35)
    t = tt(n)
    e = np.sin(np.clip(t / 0.3, 0, 1) * np.pi) ** 3
    w = noise(n, r)
    return ffilt(w, 300, 900) * e * 0.6 + ffilt(w, 900, 3000) * e * np.clip(t / 0.15, 0, 1) * 0.5


def hit():
    r = rng(690)
    n = n_of(0.3)
    t = tt(n)
    return thump(n, 75, r, 0.05) + 0.7 * ffilt(noise(n, r), 200, 2500) * np.exp(-t / 0.03)


def bow():
    r = rng(695)
    n = n_of(0.7)
    t = tt(n)
    x = 0.8 * osc(glide(n, [(0, 190), (1, 175)]), n, 'tri') * np.exp(-t / 0.12) + 0.4 * osc(380, n) * np.exp(-t / 0.06)
    place(x, swing() * 0.6, 0, circular=False)
    return x


def fire_light():
    r = rng(700)
    n = n_of(1.6)
    t = tt(n)
    sw = np.clip(t / 0.5, 0, 1) ** 2 * np.exp(-np.maximum(t - 0.5, 0) / 0.5)
    x = 0.9 * ffilt(noise(n, r, 'pink'), 150, 2500) * sw
    x += grains(n, 400 * sw + 20, r, 1000, 6000, 0.003) * 1.2
    return x


def sleep_sound():
    return arpeggio([392.0, 329.6, 261.6, 196.0], 0.22, 2.0, 710, wet=0.5, partials=((1, 1, 1), (2, 0.2, 0.5)))


def win_sound():
    r = rng(720)
    n = n_of(4.0)
    x = np.zeros(n)
    t = tt(n)
    for f in (220.0, 277.2, 329.6, 440.0, 554.4):
        x += osc(f * (1 + 0.002 * r.standard_normal()), n, 'saw') * 0.25
    x = ffilt(x, None, 2000) * np.clip(t / 1.2, 0, 1) * np.exp(-np.maximum(t - 2.2, 0) / 0.7)
    x += arpeggio([880.0, 1108.7, 1318.5, 1760.0], 0.18, 2.5, 721)[:n] * 0.6
    return x


# ------------------------------------------------------------------------------------------ weather

def thunder(near):
    r = rng(800 + near)
    d = 6.0 if near else 5.0
    n = n_of(d)
    t = tt(n)
    rumble = noise(n, r, 'brown')
    rumble = ffilt(rumble, 25, 180 if not near else 400)
    rolls = penv(n, 2.5, r, 0.15, 1.0) ** 2
    e = (1 - np.exp(-t / (0.02 if near else 0.4))) * np.exp(-t / (1.6 if near else 1.8))
    x = rumble * rolls * e
    if near:
        crack = ffilt(noise(n, r), 300, 7000) * np.exp(-t / 0.08) * 2.2
        crack += grains(n, 3000 * np.exp(-t / 0.15), r, 500, 6000, 0.003) * 2
        x += crack
    return reverb(x, ir(2.0, 0.6, rng(801), 30, 3000), 0.4)


# ------------------------------------------------------------------------------------------ creatures and people

def howl(var, far):
    """The night predator's howl: a wolf-like glide with a ghostly fifth above and a slow beating (alien)."""
    r = rng(900 + var)
    d = [3.6, 4.2, 3.0][var - 1]
    n = n_of(d)
    base = [250, 230, 280][var - 1]
    top = [520, 470, 600][var - 1]
    f0 = glide(n, [(0, base), (0.18, top), (0.55, top * 1.04), (0.8, top * 0.97), (1, base * 1.35)])
    vib = 1 + 0.018 * np.sin(2 * np.pi * 5.2 * tt(n)) * np.clip(tt(n) / 0.8, 0, 1)
    f0 = f0 * vib
    F1 = glide(n, [(0, 350), (0.3, 620), (0.8, 560), (1, 420)])
    v = voice(f0, [(F1, 4, 1.0), (glide(n, [(0, 800), (0.3, 1050), (1, 900)]), 5, 0.6), (2600, 7, 0.12)], r, breath=0.12, jitter=0.004, tilt=1.4)
    ghost = voice(f0 * 1.498 + 3.0, [(900, 3, 1.0), (1600, 5, 0.4)], rng(950 + var), breath=0.0, tilt=1.6, kmax=12) * 0.22
    e = np.clip(tt(n) / 0.35, 0, 1) ** 1.5 * np.clip((d - tt(n)) / 0.9, 0, 1) ** 1.2
    x = (v + ghost) * e
    if far:
        x = ffilt(x, 150, 1700)
        x = reverb(x, ir(3.0, 0.9, rng(960), 100, 2500, [(0.35, 0.4), (0.8, 0.25)]), 0.65)
    else:
        x = reverb(x, ir(2.0, 0.5, rng(961), 100, 5000), 0.25)
    return x


def growl():
    r = rng(1000)
    n = n_of(1.8)
    f0 = glide(n, [(0, 75), (0.4, 90), (1, 70)])
    v = voice(f0, [(500, 3, 1.0), (1100, 4, 0.7), (2400, 6, 0.25)], r, breath=0.6, jitter=0.03, rough=0.7, tilt=0.9)
    e = np.clip(tt(n) / 0.3, 0, 1) * np.clip((1.8 - tt(n)) / 0.4, 0, 1)
    return v * e * (0.7 + 0.3 * penv(n, 3, r))


def snarl():
    r = rng(1010)
    n = n_of(0.9)
    f0 = glide(n, [(0, 160), (0.2, 260), (1, 140)])
    v = voice(f0, [(800, 3, 1.0), (1700, 4, 0.8), (3000, 5, 0.4)], r, breath=1.2, jitter=0.05, rough=0.9, tilt=0.8)
    return v * env_ad(n, 0.02, 0.3, 0.25)


def grazer(var):
    r = rng(1100 + var)
    if var == 3:      # alarm: sharp, high, rising
        n = n_of(0.55)
        f0 = glide(n, [(0, 520), (0.3, 760), (1, 600)])
        return voice(f0, [(900, 4, 1.0), (2100, 5, 0.6)], r, breath=0.4, jitter=0.02) * env_ad(n, 0.01, 0.15, 0.15)
    n = n_of(0.9)
    x = np.zeros(n)
    for s, (at, fb) in enumerate([(0.0, 300), (0.42, 340 if var == 1 else 270)]):
        m = n_of(0.38)
        f0 = fb * (1 + 0.07 * np.sin(2 * np.pi * 9 * tt(m))) * glide(m, [(0, 1.0), (1, 0.88)])
        syl = voice(f0, [(700, 4, 1.0), (1600, 5, 0.7), (2600, 6, 0.2)], r, breath=0.2) * env_ad(m, 0.02, 0.12, 0.12)
        place(x, syl, n_of(at), circular=False)
    return x


def chirp(var, r=None, freq=None):
    r = r if r is not None else rng(1200 + var)
    x = np.zeros(n_of(0.6))
    f = freq or [2600, 3300, 2100][var - 1]
    count = [3, 2, 4][var - 1]
    for i in range(count):
        m = n_of(0.07 + 0.03 * r.random())
        fc = glide(m, [(0, f), (0.4, f * 1.35), (1, f * 0.9)]) * (1 + 0.05 * i)
        mod = 1 + 0.4 * np.sin(2 * np.pi * 70 * tt(m))
        c = osc(fc * mod, m) * np.sin(np.linspace(0, np.pi, m)) ** 2
        place(x, c, n_of(i * 0.11), circular=False)
    return x


def crawler_click():
    r = rng(1300)
    n = n_of(0.8)
    x = np.zeros(n)
    at = 0.0
    while at < 0.7:
        m = n_of(0.006)
        c = ffilt(r.standard_normal(m) * np.exp(-tt(m) / 0.001), 2500, 7000) * (0.5 + r.random() * 0.5)
        place(x, c, n_of(at), circular=False)
        at += 0.018 + r.random() * 0.05
    return ffilt(x, 1500, 9000, extra=lambda f: peaky(f, 4200, 3) + 0.3)


def hiss():
    r = rng(1310)
    n = n_of(1.0)
    t = tt(n)
    x = ffilt(noise(n, r), 2500, 9000, extra=lambda f: peaky(f, 5000, 2) + 0.4) * env_ad(n, 0.05, 0.3, 0.3)
    c = crawler_click()
    return place(x, 0.4 * c * np.exp(-tt(len(c)) / 0.3), 0, circular=False)


def burrower_rumble():
    r = rng(1400)
    n = n_of(2.6)
    t = tt(n)
    x = ffilt(noise(n, r, 'brown'), 20, 140) * penv(n, 4, r, 0.3, 1.0) * np.sin(np.clip(t / 2.6, 0, 1) * np.pi)
    x += grains(n, 120 * np.sin(np.clip(t / 2.6, 0, 1) * np.pi), r, 300, 2500, 0.006) * 0.6
    return x


def burrower_burst():
    r = rng(1410)
    n = n_of(1.4)
    t = tt(n)
    x = 1.0 * thump(n, 45, r, 0.12) + grains(n, 2500 * np.exp(-t / 0.25), r, 400, 5000, 0.004) * 1.5
    place(x, snarl() * 0.6, n_of(0.05), circular=False)
    return x


def brute_roar():
    r = rng(1500)
    n = n_of(2.4)
    f0 = glide(n, [(0, 80), (0.25, 110), (0.7, 95), (1, 65)])
    v = voice(f0, [(glide(n, [(0, 500), (0.3, 750), (1, 600)]), 3, 1.0), (1200, 4, 0.8), (2500, 5, 0.3)], r, breath=0.7,
              jitter=0.04, rough=1.0, tilt=0.8)
    e = env_ad(n, 0.12, 0.6, 1.0)
    return reverb(v * e, ir(2.0, 0.6, rng(1501), 60, 4000), 0.3)


def creature_death():
    r = rng(1600)
    n = n_of(1.0)
    f0 = glide(n, [(0, 420), (0.15, 520), (1, 160)])
    return voice(f0, [(700, 4, 1.0), (1500, 5, 0.6)], r, breath=0.5, jitter=0.03, rough=0.4) * env_ad(n, 0.01, 0.3, 0.2)


def human_shout(var):
    r = rng(1700 + var)
    if var == 3:      # attack: a long war cry
        n = n_of(1.3)
        f0 = glide(n, [(0, 190), (0.2, 240), (0.8, 250), (1, 200)])
        F1 = glide(n, [(0, 700), (1, 750)])
        v = voice(f0, [(F1, 5, 1.0), (1250, 6, 0.8), (2600, 8, 0.4)], r, breath=0.35, jitter=0.015, rough=0.25)
        return v * env_ad(n, 0.04, 0.3, 0.8)
    n = n_of(0.75)
    f0 = glide(n, [(0, 170), (0.3, 215 if var == 1 else 180), (1, 160)])
    F1 = glide(n, [(0, 480), (0.45, 520), (0.55, 680), (1, 650)])
    F2 = glide(n, [(0, 850), (0.45, 900), (0.55, 1500), (1, 1700)])
    v = voice(f0, [(F1, 5, 1.0), (F2, 6, 0.7), (2600, 8, 0.3)], r, breath=0.3, jitter=0.01)
    h = ffilt(noise(n, r), 500, 3000) * np.exp(-tt(n) / 0.03) * 0.5
    return (v + h) * env_ad(n, 0.02, 0.2, 0.35)


def haldi(var):
    """Friendly greeting: hummed, sung, two or three notes, mouth closed then open (wordless)."""
    r = rng(1800 + var)
    base = [205, 135, 240][var - 1]
    n = n_of(1.1)
    f0 = glide(n, [(0, base), (0.4, base), (0.5, base * 1.26), (0.85, base * 1.2), (1, base * 1.12)])
    F1 = glide(n, [(0, 260), (0.45, 270), (0.55, 650), (1, 520)])     # "mm" -> "ah-o"
    F2 = glide(n, [(0, 1900), (0.45, 1900), (0.55, 1100), (1, 900)])
    v = voice(f0 * (1 + 0.01 * np.sin(2 * np.pi * 5 * tt(n))), [(F1, 5, 1.0), (F2, 6, 0.5), (2800, 8, 0.15)], r, breath=0.1)
    return reverb(v * env_ad(n, 0.08, 0.25, 0.65), ir(1.0, 0.25, rng(1850), 150, 5000), 0.2)


def stinger(var):
    r = rng(1900 + var)
    d = 3.5 if var == 1 else 2.6
    n = n_of(d)
    t = tt(n)
    x = np.zeros(n)
    notes = (55.0, 58.27, 82.41, 87.31) if var == 1 else (73.42, 77.78, 110.0)
    for f in notes:
        x += osc(f * (1 + 0.003 * r.standard_normal()), n, 'saw')
    x = ffilt(x, 30, 900) * np.clip(t / (0.35 if var == 1 else 0.08), 0, 1) ** 2 * np.exp(-np.maximum(t - 0.5, 0) / 0.9)
    scrape = ffilt(noise(n, r), 2000, 7000, extra=lambda f: peaky(f, 3300, 20, 3) + peaky(f, 4700, 25, 2) + 0.1)
    x += scrape * np.clip(t / 0.25, 0, 1) * np.exp(-t / 0.7) * 0.5
    x += 0.8 * thump(n, 38, r, 0.4)
    return reverb(x, ir(2.2, 0.6, rng(1950), 40, 5000), 0.45)


def call_far(var, night):
    """Distant calls of the jungle (day: whooping; night: a slow descending eerie whistle)."""
    r = rng(2000 + var + (10 if night else 0))
    if night:
        n = n_of(2.2)
        f = glide(n, [(0, 1250 + 100 * var), (0.25, 1400 + 80 * var), (1, 700)])
        x = osc(f * (1 + 0.012 * np.sin(2 * np.pi * 6 * tt(n))), n) * env_ad(n, 0.2, 0.5, 1.0)
        x += 0.3 * osc(f * 0.5, n) * env_ad(n, 0.3, 0.5, 0.9)
    else:
        n = n_of(1.6)
        x = np.zeros(n)
        for i in range(3 + var):
            m = n_of(0.22)
            f = glide(m, [(0, 600 + 60 * var), (0.5, 1100 + 80 * var), (1, 800)])
            place(x, osc(f, m, 'tri') * np.sin(np.linspace(0, np.pi, m)), n_of(i * 0.26), circular=False)
    x = ffilt(x, 200, 3000)
    return reverb(x, ir(2.5, 0.7, rng(2050), 150, 3000), 0.55)


def drip(var):
    r = rng(2100 + var)
    n = n_of(0.25)
    t = tt(n)
    f0 = [1300, 1700, 2100][var - 1]
    x = osc(f0 * (1 + 0.9 * (1 - np.exp(-t / 0.03))), n) * np.exp(-t / 0.04)
    x += 0.4 * ffilt(r.standard_normal(n) * np.exp(-t / 0.002), 1000, 6000)
    return reverb(x, ir(1.6, 0.45, rng(2150), 200, 5000, [(0.11, 0.6), (0.23, 0.4), (0.41, 0.2)]), 0.6)


def pebbles():
    r = rng(2200)
    n = n_of(1.4)
    t = tt(n)
    x = np.zeros(n)
    at = 0.0
    k = 0
    while at < 1.0:
        place(x, knock(1500 + r.random() * 2500, 0.06, r, 10) * (1 - at) ** 0.5, n_of(at), circular=False)
        at += 0.03 + r.random() * 0.12 * (1 + k * 0.15)
        k += 1
    return reverb(x, ir(1.5, 0.4, rng(2201), 200, 6000), 0.4)


def ice_creak():
    r = rng(2300)
    n = n_of(1.6)
    t = tt(n)
    f0 = glide(n, [(0, 60), (0.5, 95), (1, 70)])
    pulses = np.zeros(n)
    ph = np.cumsum(f0) / SR
    idx = np.nonzero(np.diff(np.floor(ph)) > 0)[0]
    pulses[idx] = 1
    x = ffilt(pulses, 300, 4000, extra=lambda f: peaky(f, 1200, 4) + peaky(f, 2300, 6, 0.6)) * np.sin(np.clip(t / 1.6, 0, 1) * np.pi)
    return reverb(x, ir(2.0, 0.7, rng(2301), 100, 4000), 0.5)


# ------------------------------------------------------------------------------------------ beds (loops)

def bed_jungle_day():
    L = n_of(10.0)
    r = rng(3000)
    x = ffilt(noise(L, r, 'pink', True), 1500, 8000, circular=True) * penv(L, 0.3, r, 0.2, 1.0) * 0.35
    # insects: two narrow buzzing bands
    for fc, am, g in ((4600, 31.0, 0.35), (6200, 47.0, 0.2)):
        b = ffilt(noise(L, r, 'white', True), fc * 0.93, fc * 1.07, order=4, circular=True)
        x += g * b * (0.6 + 0.4 * np.sin(2 * np.pi * am * tt(L))) * penv(L, 0.2, r, 0.4, 1.0)
    # birds and calls (wrapped)
    for i in range(14):
        c = chirp(1 + i % 3, r, 1800 + r.random() * 2600)
        place(x, ffilt(c, 800, 7000) * (0.15 + 0.35 * r.random()), int(r.random() * L))
    for v in (1, 2):
        place(x, call_far(v, False) * 0.25, int(r.random() * L))
    x = reverb(x, ir(1.5, 0.4, rng(3001), 200, 7000), 0.25, circular=True)
    return x


def bed_jungle_night():
    L = n_of(10.0)
    r = rng(3100)
    t = tt(L)
    x = ffilt(noise(L, r, 'pink', True), 80, 1200, circular=True) * penv(L, 0.2, r, 0.3, 1.0) * 0.3
    # crickets: carrier tones pulsed in trains (whole number of trains per loop)
    for fc, train, pulses, g in ((4300, 1.5, 4, 0.5), (5100, 1.0, 6, 0.35), (3700, 0.75, 3, 0.25)):
        gate = np.zeros(L)
        period = 1 / train
        for k in range(int(round(L / SR * train))):
            for p in range(pulses):
                at = k * period + p * 0.028
                m = n_of(0.018)
                place(gate, np.sin(np.linspace(0, np.pi, m)), n_of(at))
        x += g * gate * np.sin(2 * np.pi * fc * t) * penv(L, 0.15, r, 0.5, 1.0)
    # frogs: low croaks
    for i in range(9):
        m = n_of(0.25)
        f0 = 160 + r.random() * 120
        cro = voice(np.full(m, f0) * glide(m, [(0, 1.0), (1, 0.9)]), [(450, 4, 1.0), (1100, 5, 0.5)], r, breath=0.1) * \
            (0.5 + 0.5 * np.sign(np.sin(2 * np.pi * 28 * tt(m)))) * np.sin(np.linspace(0, np.pi, m))
        place(x, cro * (0.25 + 0.25 * r.random()), int(r.random() * L))
    for v in (1, 2):
        place(x, call_far(v, True) * 0.25, int(r.random() * L))
    return reverb(x, ir(2.0, 0.5, rng(3101), 150, 6000), 0.3, circular=True)


def wind(L, r, bands, gust_rate, whistle=None):
    x = np.zeros(L)
    w = noise(L, r, 'pink', True)
    for lo, hi, g in bands:
        x += g * ffilt(w, lo, hi, circular=True) * penv(L, gust_rate, r, 0.15, 1.0) ** 1.5
    if whistle:
        fc, g = whistle
        s = ffilt(noise(L, r, 'white', True), None, None, circular=True, extra=lambda f: peaky(f, fc, 60) + peaky(f, fc * 1.5, 70, 0.5))
        x += g * s / (np.std(s) + 1e-9) * penv(L, gust_rate * 1.5, r, 0.0, 1.0) ** 3 * np.std(x)
    return x


def bed_wind_plateau():
    L = n_of(10.0)
    return wind(L, rng(3200), [(60, 300, 1.0), (300, 1200, 0.7), (1200, 4000, 0.35)], 0.25, (880, 0.5))


def bed_wind_canyon():
    L = n_of(10.0)
    r = rng(3300)
    x = wind(L, r, [(80, 400, 0.6), (2000, 7000, 0.35)], 0.2, (1500, 0.25))
    for _ in range(2):
        place(x, pebbles() * 0.15, int(r.random() * L))
    return x


def bed_cave():
    L = n_of(10.0)
    r = rng(3400)
    t = tt(L)
    x = ffilt(noise(L, r, 'brown', True), 18, 110, circular=True) * penv(L, 0.15, r, 0.5, 1.0) * 1.0
    x += 0.04 * ffilt(noise(L, r, 'pink', True), 300, 3000, circular=True)
    x += 0.15 * np.sin(2 * np.pi * (round(36.7 * 12) / 12) * t) * (0.6 + 0.4 * np.sin(2 * np.pi * t / 6))
    for i in range(6):
        place(x, drip(1 + i % 3) * (0.15 + 0.25 * r.random()), int(r.random() * L))
    return x


def bed_village():
    """A far murmur of voices (wordless babble), chores knocks, a goat-like grazer, fire's low roar."""
    L = n_of(10.0)
    r = rng(3500)
    x = 0.15 * ffilt(noise(L, r, 'brown', True), 40, 300, circular=True)
    vowels = [(700, 1200), (400, 2000), (500, 900), (300, 2300), (600, 1700)]
    for sp in range(5):
        at = r.random() * 10.0
        f0b = r.choice([120, 140, 190, 220])
        for _ in range(6):
            m = n_of(0.8 + r.random() * 1.6)
            f0 = f0b * glide(m, [(0, 1.0), (0.3, 1.1 + 0.1 * r.random()), (0.7, 0.95), (1, 0.85)])
            ks = r.integers(0, len(vowels), 6)
            F1 = glide(m, [(i / 5, vowels[k][0]) for i, k in enumerate(ks)])
            F2 = glide(m, [(i / 5, vowels[k][1]) for i, k in enumerate(ks)])
            syl = 0.5 + 0.5 * np.sin(2 * np.pi * 4.5 * tt(m) + r.random() * 6) ** 2
            v = voice(f0, [(F1, 5, 1.0), (F2, 6, 0.6)], r, breath=0.15, kmax=20) * syl * np.sin(np.linspace(0, np.pi, m))
            place(x, ffilt(v, 100, 2200) * 0.25, n_of(at))
            at += m / SR + 0.3 + r.random() * 1.2
    for _ in range(4):
        place(x, knock(300 + r.random() * 200, 0.25, r, 6) * 0.3, int(r.random() * L))
    return reverb(x, ir(1.8, 0.5, rng(3501), 100, 4000), 0.4, circular=True)


def bed_rain():
    L = n_of(8.0)
    r = rng(3600)
    x = ffilt(noise(L, r, 'pink', True), 800, 9000, circular=True) * penv(L, 0.4, r, 0.7, 1.0)
    drops = np.zeros(L)
    hits = np.nonzero(r.random(L) < 400 / SR)[0]
    for h in hits:
        m = n_of(0.01)
        place(drops, r.standard_normal(m) * np.exp(-tt(m) / 0.0015) * r.random(), int(h))
    x += 1.5 * ffilt(drops, 1500, 8000, circular=True)
    x += 0.4 * ffilt(noise(L, r, 'brown', True), 60, 400, circular=True)
    return x


def bed_water():
    L = n_of(8.0)
    r = rng(3700)
    t = tt(L)
    w = noise(L, r, 'pink', True)
    waves = np.zeros(L)
    for k, at in enumerate((0.3, 2.9, 5.2, 7.1)):
        m = n_of(1.8)
        e = np.sin(np.linspace(0, np.pi, m)) ** 2 * (1 - np.linspace(0, 1, m)) ** 0.5
        place(waves, e * (0.7 + 0.3 * r.random()), n_of(at))
    x = ffilt(w, 150, 1400, circular=True) * (0.2 + waves)
    for _ in range(14):
        bn = n_of(0.05)
        b0 = 300 + r.random() * 800
        place(x, osc(np.linspace(b0, b0 * 1.6, bn), bn) * np.exp(-tt(bn) / 0.02) * 0.15, int(r.random() * L))
    return x


def waterfall_loop():
    """A waterfall: a deep roar of falling water (low rumble, broad hiss), its slow swell, and the splashes of the
    plunge pool (built circularly: seamless)."""
    L = n_of(8.0)
    r = rng(3750)
    x = 0.55 * ffilt(noise(L, r, 'brown', True), 40, 260, circular=True) * penv(L, 0.3, r, 0.75, 1.0)
    x += 0.9 * ffilt(noise(L, r, 'pink', True), 300, 2600, circular=True) * penv(L, 0.6, r, 0.7, 1.0)
    x += 0.35 * ffilt(noise(L, r, 'white', True), 2500, 7500, circular=True) * penv(L, 1.1, r, 0.6, 1.0)
    for _ in range(90):
        m = n_of(0.03 + 0.05 * r.random())
        b0 = 400 + r.random() * 1600
        place(x, ffilt(r.standard_normal(m), b0 * 0.6, b0 * 2.0) * np.exp(-tt(m) / 0.012) * (0.2 + 0.3 * r.random()), int(r.random() * L))
    return reverb(x, ir(1.2, 0.35, rng(3751), 80, 5000), 0.3, circular=True)


def bed_drone():
    """Tension: two low tones beating, a breathing noise, a thin high tone (whole cycles in 8 s: seamless)."""
    L = n_of(8.0)
    r = rng(3800)
    t = tt(L)

    def q(f):
        return round(f * 8.0) / 8.0
    x = 0.8 * np.sin(2 * np.pi * q(41.25) * t) + 0.7 * np.sin(2 * np.pi * q(43.75) * t)
    x += 0.35 * np.sin(2 * np.pi * q(82.5) * t + 0.3) * (0.5 + 0.5 * np.sin(2 * np.pi * t / 4))
    x += 0.5 * ffilt(noise(L, r, 'pink', True), 60, 500, circular=True) * (0.5 + 0.5 * np.sin(2 * np.pi * t / 8) ** 2)
    x += 0.06 * np.sin(2 * np.pi * q(1318.5) * t) * (0.5 + 0.5 * np.sin(2 * np.pi * 3 * t / 8))
    x += 0.04 * np.sin(2 * np.pi * q(1396.9) * t) * (0.5 + 0.5 * np.sin(2 * np.pi * 2 * t / 8 + 1))
    return x


def fire_loop():
    L = n_of(6.0)
    r = rng(3900)
    x = 0.6 * ffilt(noise(L, r, 'brown', True), 40, 500, circular=True) * penv(L, 1.5, r, 0.6, 1.0)
    x += 0.15 * ffilt(noise(L, r, 'pink', True), 500, 3000, circular=True) * penv(L, 3, r, 0.3, 1.0)
    pops = np.zeros(L)
    hits = np.nonzero(r.random(L) < 14 / SR)[0]
    for h in hits:
        m = n_of(0.012)
        place(pops, r.standard_normal(m) * np.exp(-tt(m) / 0.002) * r.random() ** 2.5 * 3, int(h))
    for _ in range(5):
        m = n_of(0.03)
        place(pops, r.standard_normal(m) * np.exp(-tt(m) / 0.004) * 4, int(r.random() * L))
    return x + ffilt(pops, 700, 7000, circular=True)


def swarm_loop():
    L = n_of(4.0)
    r = rng(4000)
    t = tt(L)
    x = np.zeros(L)
    for i in range(9):
        f = round((170 + r.random() * 110) * 4) / 4
        wob = 1 + 0.02 * np.sin(2 * np.pi * (1 + i % 3) * t / 4.0 * 2 + r.random() * 6)
        ph = 2 * np.pi * np.cumsum(np.full(L, f) * wob) / SR
        s = np.zeros(L)
        for k in range(1, 14):
            s += np.sin(k * ph) / k
        x += s * (0.4 + 0.6 * penv(L, 2, r))
    # make the phase wrap exact: crossfade 30 ms around the seam (only the oscillators' drift can break it)
    x = ffilt(x, 150, 4000, circular=True)
    return seamless(x, n_of(0.05))


def seamless(x, k):
    """Crossfades the last k samples into the first k (for signals whose phase may not wrap exactly)."""
    y = x[:-k].copy()
    a = np.linspace(0, 1, k)
    y[:k] = x[:k] * a + x[-k:] * (1 - a)
    return y


# ------------------------------------------------------------------------------------------ music (circular loops)

def midi(m):
    return 440.0 * 2 ** ((m - 69) / 12)


def pad_note(f, n, r, bright=1200, detune=0.004):
    x = np.zeros(n)
    for d in (-detune, 0, detune):
        x += osc(f * (1 + d), n, 'saw')
    return ffilt(x, None, bright)


def music(name, L_sec, chords, bright, plucks, pluck_scale, seed, extra=None, bell_like=False):
    L = n_of(L_sec)
    r = rng(seed)
    out = [np.zeros(L), np.zeros(L)]
    seg = L_sec / len(chords)
    for i, chord in enumerate(chords):
        d = seg + 3.0
        m = n_of(d)
        tl = tt(m)
        e = np.clip(tl / 2.2, 0, 1) ** 2 * np.clip((d - tl) / 3.0, 0, 1)
        for ch in (0, 1):
            s = np.zeros(m)
            for note in chord:
                s += pad_note(midi(note), m, r, bright, 0.003 + 0.002 * ch)
            place(out[ch], s * e * 0.25, n_of(i * seg))
    for _ in range(plucks):
        note = r.choice(pluck_scale)
        m = n_of(2.5)
        b = bell(midi(note), 2.5, r, ((1, 1, 1), (2, 0.25, 0.5), (3, 0.08, 0.3))) if bell_like else \
            osc(midi(note), m, 'tri') * np.exp(-tt(m) / 0.6) * np.clip(tt(m) / 0.005, 0, 1)
        at = int(r.random() * L)
        pan = r.random()
        place(out[0], b * 0.35 * (1 - pan * 0.6), at)
        place(out[1], b * 0.35 * (0.4 + pan * 0.6), at)
    if extra is not None:
        extra(out, L, r)
    h = ir(3.5, 1.0, rng(seed + 1), 80, 6000)
    out = [reverb(o, h, 0.45, circular=True) for o in out]
    save_ogg(name, out[0], out[1])


def danger_extra(out, L, r):
    t = tt(L)
    beat = 0.75
    for k in range(int(round(L / SR / beat))):
        for at, g in ((0.0, 1.0), (0.22, 0.6)):
            m = n_of(0.4)
            b = osc(midi(26) * (1 + 0.5 * np.exp(-tt(m) / 0.03)), m) * np.exp(-tt(m) / 0.12)
            for ch in (0, 1):
                place(out[ch], b * 0.9 * g, n_of(k * beat + at))
    for k in range(int(round(L / SR / (beat / 2)))):
        m = n_of(0.05)
        tick = ffilt(r.standard_normal(m) * np.exp(-tt(m) / 0.006), 4000, 9000) * (0.12 if k % 2 else 0.2)
        place(out[k % 2], tick, n_of(k * beat / 2))
    sw = 0.5 + 0.5 * np.sin(2 * np.pi * t / (L / SR))
    for ch in (0, 1):
        out[ch] += 0.15 * ffilt(noise(L, r, 'pink', True), 2500, 6000, circular=True) * sw ** 2


def night_extra(out, L, r):
    t = tt(L)
    f = round(midi(88) * (L / SR)) / (L / SR)
    g = 0.04 * np.sin(2 * np.pi * f * t) * (0.5 + 0.5 * np.sin(2 * np.pi * 3 * t / (L / SR)))
    out[0] += g
    out[1] += 0.8 * g


def cave_extra(out, L, r):
    for _ in range(6):
        d = drip(1 + int(r.random() * 3))
        place(out[int(r.random() * 2)], d * 0.25, int(r.random() * L))


# ------------------------------------------------------------------------------------------ main

def main():
    if shutil.which('ffmpeg') is None:
        sys.exit('ffmpeg is needed for the music (libvorbis)')
    os.makedirs(SFX, exist_ok=True)
    os.makedirs(MUSIC, exist_ok=True)
    for d in (SFX, MUSIC):
        for f in os.listdir(d):
            os.unlink(os.path.join(d, f))

    for g in ('grass', 'leaves', 'mud', 'water', 'sand', 'rock', 'snow', 'cave'):
        for v in range(1, 5):
            save_wav(f'step_{g}_{v}', step(g, v, False), 'step')
            save_wav(f'stepsoft_{g}_{v}', step(g, v, True), 'stepsoft')
    save_wav('land_soft', land(0), 'land')
    save_wav('land_hard', land(1), 'land')
    save_wav('jump', jump_voice(), 'body')
    for v in (1, 2, 3):
        save_wav(f'swim_{v}', swim(v), 'body')
    save_wav('splash', splash_big(), 'action')
    save_wav('breath_1', breath(1), 'body')
    save_wav('breath_2', breath(2), 'body')
    save_wav('heartbeat', heartbeat(), 'land')
    for v in (1, 2, 3):
        save_wav(f'pain_{v}', pain(v), 'voice')
    save_wav('death', death_voice(), 'voice')

    save_wav('ui_click', ui_click(), 'ui')
    save_wav('ui_open', ui_tones([660, 990], 610), 'ui')
    save_wav('ui_close', ui_tones([880, 587], 611), 'ui')
    save_wav('ui_message', ui_tones([1320], 612), 'ui')
    save_wav('discover', arpeggio([880.0, 1108.7, 1318.5], 0.12, 1.6, 613), 'chime')
    save_wav('quest', arpeggio([440.0, 587.3, 740.0, 880.0], 0.15, 2.0, 614), 'chime')
    save_wav('zone', arpeggio([146.8, 220.0, 293.7, 440.0, 587.3], 0.25, 3.0, 615, wet=0.55), 'chime')
    save_wav('eat', eat(), 'action')
    save_wav('drink', drink(), 'action')
    save_wav('craft', craft(), 'action')
    save_wav('chop', chop(), 'action')
    save_wav('mine', mine(), 'action')
    save_wav('pickup', pickup(), 'action')
    save_wav('swing', swing(), 'action')
    save_wav('hit', hit(), 'action')
    save_wav('bow', bow(), 'action')
    save_wav('fire_light', fire_light(), 'action')
    save_wav('sleep', sleep_sound(), 'chime')
    save_wav('win', win_sound(), 'chime')
    save_wav('thunder_far', thunder(0), 'thunder')
    save_wav('thunder_near', thunder(1), 'thunder')

    for v in (1, 2, 3):
        save_wav(f'howl_{v}', howl(v, False), 'howl')
        save_wav(f'howl_far_{v}', howl(v, True), 'howl')
    save_wav('stalker_growl', growl(), 'creature')
    save_wav('stalker_snarl', snarl(), 'creature')
    save_wav('grazer_1', grazer(1), 'creature')
    save_wav('grazer_2', grazer(2), 'creature')
    save_wav('grazer_alarm', grazer(3), 'creature')
    for v in (1, 2, 3):
        save_wav(f'bird_{v}', chirp(v), 'call')
    save_wav('crawler_click', crawler_click(), 'creature')
    save_wav('crawler_hiss', hiss(), 'creature')
    save_wav('burrower_rumble', burrower_rumble(), 'creature')
    save_wav('burrower_burst', burrower_burst(), 'creature')
    save_wav('brute_roar', brute_roar(), 'creature')
    save_wav('creature_death', creature_death(), 'creature')
    save_wav('rodeur_shout_1', human_shout(1), 'creature')
    save_wav('rodeur_shout_2', human_shout(2), 'creature')
    save_wav('rodeur_attack', human_shout(3), 'creature')
    for v in (1, 2, 3):
        save_wav(f'haldi_{v}', haldi(v), 'call')
    save_wav('stinger_1', stinger(1), 'stinger')
    save_wav('stinger_2', stinger(2), 'stinger')
    for v in (1, 2):
        save_wav(f'call_day_{v}', call_far(v, False), 'call')
        save_wav(f'call_night_{v}', call_far(v, True), 'call')
    for v in (1, 2, 3):
        save_wav(f'drip_{v}', drip(v), 'call')
    save_wav('pebbles', pebbles(), 'call')
    save_wav('ice_creak', ice_creak(), 'call')

    save_wav('bed_jungle_day', bed_jungle_day(), 'bed', loop=True)
    save_wav('bed_jungle_night', bed_jungle_night(), 'bed', loop=True)
    save_wav('bed_wind_plateau', bed_wind_plateau(), 'bed', loop=True)
    save_wav('bed_wind_canyon', bed_wind_canyon(), 'bed', loop=True)
    save_wav('bed_cave', bed_cave(), 'bed', loop=True)
    save_wav('bed_village', bed_village(), 'bed', loop=True)
    save_wav('bed_rain', bed_rain(), 'bed', loop=True)
    save_wav('bed_water', bed_water(), 'bed', loop=True)
    save_wav('waterfall_loop', waterfall_loop(), 'loop', loop=True)
    save_wav('bed_drone', bed_drone(), 'bed', loop=True)
    save_wav('fire_loop', fire_loop(), 'loop', loop=True)
    save_wav('swarm_loop', swarm_loop(), 'loop', loop=True)

    # music: D major-ish calm day, E minor night, a pulsing danger, a hollow cave
    music('music_day', 32.0, [[50, 57, 62, 66, 69], [47, 54, 59, 62, 66], [43, 50, 55, 59, 66], [45, 52, 57, 61, 64]],
          1400, 10, [74, 76, 78, 81, 83, 86], 5000)
    music('music_night', 32.0, [[40, 47, 52, 54, 59], [36, 43, 52, 54, 59], [45, 52, 55, 59, 62], [47, 54, 57, 60, 63]],
          900, 6, [71, 74, 76, 79, 83], 5100, night_extra, bell_like=True)
    music('music_danger', 12.0, [[38, 39, 45, 51], [38, 44, 45, 50]], 700, 0, [62], 5200, danger_extra)
    music('music_cave', 24.0, [[33, 40, 45, 52], [34, 41, 45, 53], [33, 40, 47, 52]], 600, 4, [69, 72, 76], 5300, cave_extra,
          bell_like=True)

    # ---- analysis
    bad = []
    total = 0
    print(f"{'file':28s} {'sec':>5s} {'peak':>6s} {'loud':>6s} {'tgt':>4s} {'clip':>4s} {'seam':>10s} {'KB':>6s}")
    for row in REPORT:
        total += row['size']
        s = f"{row['jump']:.2f}/{row['step']:.1f}dB" if row['loop'] else ''
        print(f"{row['file']:28s} {row['sec']:5.2f} {row['peak']:6.1f} {row['loud']:6.1f} {row['target']:4d} {row['clip']:4d} {s:>10s} {row['size'] // 1024:6d}")
        if row['clip'] > 0 or row['peak'] > -0.9:
            bad.append(row['file'] + ': clipping')
        if row['loud'] < row['target'] - 6:
            bad.append(row['file'] + f": too quiet for its family ({row['loud']:.1f} < {row['target']})")
        if row['loop'] and (row['jump'] > 1.5 or row['step'] > 4.0):
            bad.append(row['file'] + ': loop seam')
    print(f"{len(REPORT)} files, {total / 1048576:.2f} MB")
    if total > 12 * 1048576:
        bad.append('total size over 12 MB')
    if bad:
        print('PROBLEMS:\n  ' + '\n  '.join(bad))
        sys.exit(1)


if __name__ == '__main__':
    main()
