Back to Drift City
SOURCE / PINNED RELEASE

Made of little things.

Drift City

Release
098731aa0f0f…
Author-recorded commit
2822ea0a4f5b…
License
LICENSE
Author’s source reference
nostr://npub12lm3rxsva8kfempyjkxupt09e02n3fezurkyadyqfejdc5e0r2kscqty6r/wss%3A%2F%2Fgit.napplet.soy%2F/n-a4c0039c855

Archive hash verified: b3323e408235502b…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/game/sound.ts
/*
 * Car sounds through Web Audio, built from real recordings (all CC0, bundled with the
 * game; sources in napplet.assets.json):
 *
 * - Engine: real exhaust pulses cut from the idle moments of a recorded sports car (a
 *   V8, between its revs) and fired at the engine's true firing rate (see
 *   engine-voice.ts), so it keeps that car's sound at every rpm and gets much louder
 *   with the revs and the throttle. Through an exhaust's resonances and a touch of rasp;
 *   muffled from inside the car. Ignition cuts on gear changes, a rev limiter, and real
 *   V8 backfires (a Chevrolet 350's) on the overrun. The rivals have engines of their own,
 *   heard from where they are.
 * - Tyres: real squeal recordings in layers driven by the slip (scrub, squeal,
 *   wheelspin), seamlessly looped; tyre roar on tarmac that grows with
 *   speed; recorded gravel crunch off the road.
 * - Impacts: recorded collisions, a metal pole's clang, a cracking branch and a bush hit.
 *
 * Until the recordings are decoded a synthesized engine and squeal stand in. Silent until
 * unlockAudio() runs from a user gesture, or while sound is off.
 */

import { assetBlob } from '../../soy-assets.js';
import { EngineVoice, IDLE_RPM, REDLINE_RPM } from './engine-voice.js';
import type { PropKind } from './world.js';

let audio: AudioContext | null = null;
/**
 * The mix: every sound goes through one of three buses (music, the engines, and the
 * effects: tyres, crashes, backfires, the interface), each with its own volume, into the
 * master volume. ('master' is the effects bus, as most one-shots go there.)
 */
let master: GainNode | null = null;
let mainOut: GainNode | null = null;
let engineBus: GainNode | null = null;
let musicBus: GainNode | null = null;
/** The player's volume settings, 0..1 each. */
export type VolumeKind = 'master' | 'music' | 'engine' | 'effects';
const volumes: Record<VolumeKind, number> = { master: 1, music: 1, engine: 1, effects: 1 };

/** A slider's 0..1 to a gain: squared, so the slider feels even to the ear. */
const curve = (v: number) => v * v;

function applyVolumes(): void {
  if (!audio || !mainOut || !master || !engineBus || !musicBus) return;
  const t = audio.currentTime;
  mainOut.gain.setTargetAtTime(enabled ? MASTER * curve(volumes.master) : 0, t, 0.03);
  master.gain.setTargetAtTime(curve(volumes.effects), t, 0.03);
  engineBus.gain.setTargetAtTime(curve(volumes.engine), t, 0.03);
  musicBus.gain.setTargetAtTime(curve(volumes.music), t, 0.03);
}

/** Set one of the volumes (0..1). */
export function setVolume(kind: VolumeKind, v: number): void {
  volumes[kind] = Math.max(0, Math.min(1, v));
  applyVolumes();
}
let noiseBuf: AudioBuffer | null = null;
let enabled = true;
const MASTER = 0.6;

/** In the engine recording: the idle stretches (seconds), each between two revs. */
const ENGINE_SEGMENTS: [number, number][] = [
  [0, 0.3],
  [0.35, 0.75],
  [0.8, 1.05],
  [1.1, 1.38],
  [1.43, 1.88],
  [1.93, 2.28],
];
/**
 * In the backfire recording: each bang (seconds). Real backfires of a Chevrolet 350 V8,
 * each lifted out of the recording without the idling engine under it: the engine heard
 * just before subtracted from its spectrum, then what runs on steadily in time (the
 * engine) told apart from what stands up across all frequencies at once (the bang), and
 * kept only that, ending when the bang's crack has died away.
 */
const BACKFIRE_CLIPS: [number, number][] = [
  [0, 0.1348],
  [0.1448, 0.3448],
  [0.3548, 0.4796],
  [0.4896, 0.5995],
  [0.6095, 0.6994],
  [0.7094, 0.8143],
  [0.8243, 0.9192],
  [0.9292, 1.0141],
];
/** Each bang's own low note, the thump (Hz): played back pitched up, if need be, to sit with the revs. */
const BACKFIRE_PITCH = [221, 135, 167, 156, 377, 371, 371, 221];
/**
 * How close under the engine's own note a bang's thump is played (the engine's note being
 * its firing rate: a V8 fires rpm / 15 times a second).
 */
const BACKFIRE_MATCH = 0.6;
/** The engine's cylinders (the recording is a V8: it fires four times a revolution). */
const CYLINDERS = 8;
/** The engines' pitch, against the recording's (0.92: about a semitone and a half lower). */
const ENGINE_PITCH = 0.92;

/** What the car is doing, for its sound. */
export interface CarSound {
  /** Engine revs as the car models them: about 0.2 at idle to 1 at the red line. */
  rev: number;
  gear: number;
  /** Seconds left in a gear change (the throttle is eased while the clutch is in). */
  shifting: number;
  throttle: number;
  /** Tyres scrubbing at the edge of grip, 0..1 (a low rubbery moan). */
  scrub: number;
  /** Tyres sliding, 0..1 (the full squeal). 0 in the air. */
  slide: number;
  /** Driven wheels spinning (power slides, donuts, burnouts), 0..1. */
  spin: number;
  /** Road speed, m/s. */
  speed: number;
  /** On tarmac (or paving) rather than grass and dirt. */
  paved: boolean;
  /** Heard from the driver's seat. */
  inside: boolean;
  /** Driving (false fades it all out: menus, pause). */
  running: boolean;
}

// ---------------------------------------------------------------------------
// Set-up

export function setSoundEnabled(v: boolean): void {
  enabled = v;
  applyVolumes();
}

export function soundEnabled(): boolean {
  return enabled;
}

/**
 * Create or resume the audio context. Browsers let it play at once only if the page may
 * play sound without being clicked first (or the host passes that on); otherwise it waits
 * suspended, and this resumes it from the first click, tap or key press.
 */
export function unlockAudio(): void {
  if (!audio) {
    const Ctor: typeof AudioContext | undefined =
      window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
    if (!Ctor) return;
    try {
      audio = new Ctor();
    } catch {
      audio = null;
      return;
    }
    const comp = audio.createDynamicsCompressor();
    comp.threshold.value = -14;
    comp.knee.value = 10;
    comp.ratio.value = 3;
    comp.connect(audio.destination);
    mainOut = audio.createGain();
    mainOut.connect(comp);
    master = audio.createGain();
    engineBus = audio.createGain();
    musicBus = audio.createGain();
    for (const bus of [master, engineBus, musicBus]) bus.connect(mainOut);
    mainOut.gain.value = 0;
    applyVolumes();
    const len = audio.sampleRate * 2;
    noiseBuf = audio.createBuffer(1, len, audio.sampleRate);
    const d = noiseBuf.getChannelData(0);
    for (let i = 0; i < len; i++) d[i] = Math.random() * 2 - 1;
    stand = startStandIns(audio, master, noiseBuf);
    road = startRoad(audio, master, noiseBuf);
    void loadRecordings(audio, master);
  }
  if (audio.state === 'suspended') void audio.resume().catch(() => undefined);
}

async function decode(ac: AudioContext, id: string): Promise<AudioBuffer> {
  const bytes = await (await assetBlob(id)).arrayBuffer();
  return ac.decodeAudioData(bytes);
}

/** A soft overdrive curve: the rasp of an old exhaust. */
function rasp(amount: number): Float32Array<ArrayBuffer> {
  const n = 1024;
  const curve = new Float32Array(new ArrayBuffer(n * 4));
  for (let i = 0; i < n; i++) {
    const x = (i / (n - 1)) * 2 - 1;
    curve[i] = ((1 + amount) * x) / (1 + amount * Math.abs(x));
  }
  return curve;
}

function filter(ac: AudioContext, type: BiquadFilterType, freq: number, q = 0.7, gain = 0): BiquadFilterNode {
  const f = ac.createBiquadFilter();
  f.type = type;
  f.frequency.value = freq;
  f.Q.value = q;
  f.gain.value = gain;
  return f;
}

function gainNode(ac: AudioContext, value = 0): GainNode {
  const g = ac.createGain();
  g.gain.value = value;
  return g;
}

// ---------------------------------------------------------------------------
// Recorded sounds

interface Recorded {
  /** The engine's controls, read by its audio callback. */
  engine: { rpm: number; load: number; ignition: boolean };
  drive: GainNode;
  muffle: BiquadFilterNode;
  engineGain: GainNode;
  tyres: Tyres;
  gravel: AudioBufferSourceNode;
  gravelGain: GainNode;
  hits: Partial<Record<'crash-heavy' | 'crash-light' | 'hit-pole' | 'hit-wood' | 'hit-bush', AudioBuffer>>;
}
let recorded: Recorded | null = null;
/** Kept alive here: some browsers stop a ScriptProcessor nothing refers to. */
let engineNode: ScriptProcessorNode | null = null;
let lastGear = 1;

/**
 * A seamless loop from a stretch of a recording (mono): its last part is crossfaded,
 * at equal power, into its start, so it can repeat without a seam.
 */
function loopOf(ac: AudioContext, buf: AudioBuffer, from: number, to: number, fade = 0.3): AudioBuffer {
  const sr = buf.sampleRate;
  const a = Math.round(from * sr);
  const f = Math.round(fade * sr);
  const len = Math.min(buf.length - a, Math.round((to - from) * sr)) - f;
  const mono = (i: number) => {
    let v = 0;
    for (let c = 0; c < buf.numberOfChannels; c++) v += buf.getChannelData(c)[a + i]!;
    return v / buf.numberOfChannels;
  };
  const out = ac.createBuffer(1, len, sr);
  const d = out.getChannelData(0);
  for (let i = 0; i < len; i++) d[i] = mono(i);
  // The tail beyond the loop fades in over its head.
  for (let i = 0; i < f; i++) {
    const x = i / f;
    d[i] = d[i]! * Math.sin((x * Math.PI) / 2) + mono(len + i) * Math.cos((x * Math.PI) / 2);
  }
  return out;
}

/**
 * Tyre noise from real recordings, in layers driven by how the tyres are slipping:
 * a low rubbery scrub at the edge of grip, the full squeal in a slide (two takes of a
 * real car's squeal, so it never repeats audibly), and a higher, steadier wheelspin
 * squeal from a burnout for power slides and donuts. Pitch rises with the slip; levels
 * follow quick attack and slower release so the squeal never chatters at the limit.
 */
interface Tyres {
  bus: GainNode;
  tone: BiquadFilterNode;
  squealA: AudioBufferSourceNode;
  squealB: AudioBufferSourceNode;
  squealGain: GainNode;
  scrub: AudioBufferSourceNode;
  scrubGain: GainNode;
  spin: AudioBufferSourceNode;
  spinGain: GainNode;
  /** Smoothed levels. */
  level: { scrub: number; slide: number; spin: number };
  last: number;
}

function startTyres(ac: AudioContext, out: GainNode, main: AudioBuffer, burnout: AudioBuffer): Tyres {
  const takeA = loopOf(ac, main, 3.6, 8.5);
  const takeB = loopOf(ac, main, 10.1, 14.1);
  const spinLoop = loopOf(ac, burnout, 3.6, 5.8, 0.25);
  const source = (buf: AudioBuffer, at: number) => {
    const s = ac.createBufferSource();
    s.buffer = buf;
    s.loop = true;
    s.start(ac.currentTime, at % buf.duration);
    return s;
  };
  const bus = gainNode(ac, 1);
  const tone = filter(ac, 'lowpass', 12000, 0.5);
  bus.connect(filter(ac, 'highpass', 250)).connect(tone).connect(out);
  const squealGain = gainNode(ac);
  squealGain.connect(bus);
  const squealA = source(takeA, Math.random() * 4);
  const squealB = source(takeB, Math.random() * 3);
  const half = gainNode(ac, 0.6);
  squealA.connect(half).connect(squealGain);
  const half2 = gainNode(ac, 0.6);
  squealB.connect(half2).connect(squealGain);
  // The scrub: the same squeal, an octave and a bit down and muffled, like rubber moaning.
  const scrubGain = gainNode(ac);
  const scrub = source(takeB, 1.3);
  scrub.playbackRate.value = 0.62;
  scrub.connect(filter(ac, 'lowpass', 1000, 0.7)).connect(scrubGain).connect(bus);
  const spinGain = gainNode(ac);
  const spin = source(spinLoop, Math.random());
  spin.connect(spinGain).connect(bus);
  return { bus, tone, squealA, squealB, squealGain, scrub, scrubGain, spin, spinGain, level: { scrub: 0, slide: 0, spin: 0 }, last: ac.currentTime };
}

function updateTyres(ac: AudioContext, ty: Tyres, s: CarSound): void {
  const t = ac.currentTime;
  const dt = Math.min(0.1, Math.max(0.001, t - ty.last));
  ty.last = t;
  const on = s.running && s.paved;
  const follow = (cur: number, want: number) => cur + (want - cur) * (1 - Math.exp(-dt / (want > cur ? 0.04 : 0.15)));
  const L = ty.level;
  L.scrub = follow(L.scrub, on ? s.scrub : 0);
  L.slide = follow(L.slide, on ? s.slide : 0);
  L.spin = follow(L.spin, on ? s.spin : 0);
  const k = 0.03;
  ty.squealGain.gain.setTargetAtTime(L.slide * 0.85, t, k);
  // The scrub gives way as the full squeal takes over.
  ty.scrubGain.gain.setTargetAtTime(L.scrub * (1 - L.slide * 0.8) * 0.5, t, k);
  ty.spinGain.gain.setTargetAtTime(L.spin * 0.55, t, k);
  // Harder slides, and faster ones, squeal higher; the two takes drift apart a touch.
  const pitch = 0.86 + L.slide * 0.22 + Math.min(1, s.speed / 40) * 0.08;
  ty.squealA.playbackRate.setTargetAtTime(pitch, t, 0.08);
  ty.squealB.playbackRate.setTargetAtTime(pitch * 1.03, t, 0.08);
  ty.scrub.playbackRate.setTargetAtTime(0.55 + L.scrub * 0.15, t, 0.1);
  ty.spin.playbackRate.setTargetAtTime(0.92 + L.spin * 0.16, t, 0.08);
  // From inside, the cabin takes the edge off.
  ty.tone.frequency.setTargetAtTime(s.inside ? 5000 : 12000, t, 0.1);
}

/** An engine voice from the recording's idle stretches (mixed to mono), at the context's rate. */
function engineVoice(buf: AudioBuffer): EngineVoice {
  const segs = ENGINE_SEGMENTS.map(([a, b]) => {
    const from = Math.round(a * buf.sampleRate);
    const out = new Float32Array(Math.min(buf.length, Math.round(b * buf.sampleRate)) - from);
    for (let c = 0; c < buf.numberOfChannels; c++) {
      const d = buf.getChannelData(c);
      for (let i = 0; i < out.length; i++) out[i] = out[i]! + d[from + i]! / buf.numberOfChannels;
    }
    return out;
  });
  // (Decoded at the context's own rate; its idle fires at 40 to 57 times a second.) Each
  // stretch's pulses are averaged into one clean pulse, one for each cylinder: picking a
  // raw, hissy pulse at random for every firing is what made it sound grainy.
  const voice = EngineVoice.fromSegments(segs, buf.sampleRate, CYLINDERS, 35, 65, 1);
  // A touch deeper than the recording: about a semitone and a half down.
  voice.pitch = ENGINE_PITCH;
  return voice;
}
let engineBuf: AudioBuffer | null = null;
/** The recorded backfires, one buffer each (null until loaded: synthesized ones till then). */
let recordedPops: AudioBuffer[] | null = null;

async function loadRecordings(ac: AudioContext, out: GainNode): Promise<void> {
  try {
    const [idle, squealMain, squealSpin, gravelBuf] = await Promise.all([
      decode(ac, 'engine-sport'),
      decode(ac, 'squeal-main'),
      decode(ac, 'squeal-spin'),
      decode(ac, 'tyres-gravel'),
    ]);
    // Engine: pulses fired from an audio callback, then the exhaust.
    const voice = engineVoice(idle);
    const engine = { rpm: IDLE_RPM, load: 0, ignition: true };
    const node = ac.createScriptProcessor(1024, 0, 1);
    node.onaudioprocess = (e) => voice.render(e.outputBuffer.getChannelData(0), engine);
    // Into the rasp harder on the throttle; then the exhaust's body and its pipe
    // resonance; muffled through the cabin from inside.
    const drive = gainNode(ac, 1);
    const shaper = ac.createWaveShaper();
    shaper.curve = rasp(1.2);
    shaper.oversample = '2x';
    // (The recorded car's deep exhaust: a big body round 150 Hz, the pipe ringing higher.)
    const body = filter(ac, 'peaking', 150, 0.8, 5);
    const pipe = filter(ac, 'peaking', 420, 1.2, 3);
    const muffle = filter(ac, 'lowpass', 9000, 0.6);
    const engineGain = gainNode(ac);
    node.connect(drive).connect(shaper).connect(body).connect(pipe).connect(muffle).connect(engineGain).connect(engineBus!);
    engineNode = node;
    // Gravel under the tyres off the road: the recording looped, skipping its edges.
    const gravel = ac.createBufferSource();
    gravel.buffer = gravelBuf;
    gravel.loop = true;
    gravel.loopStart = 0.4;
    gravel.loopEnd = gravelBuf.duration - 0.4;
    const gravelGain = gainNode(ac);
    gravel.connect(filter(ac, 'highpass', 90)).connect(gravelGain).connect(out);
    gravel.start(ac.currentTime, 0.4 + Math.random() * 5);
    const tyres = startTyres(ac, out, squealMain, squealSpin);
    recorded = { engine, drive, muffle, engineGain, tyres, gravel, gravelGain, hits: {} };
    if (stand) {
      stand.engineGain.gain.setTargetAtTime(0, ac.currentTime, 0.1);
      stand.skidGain.gain.setTargetAtTime(0, ac.currentTime, 0.1);
    }
    // The rivals' engines, from the same pulses; and the recorded backfires.
    engineBuf = idle;
    decode(ac, 'backfires')
      .then((b) => {
        recordedPops = BACKFIRE_CLIPS.map(([a, z]) => {
          const n = Math.round((z - a) * b.sampleRate);
          const clip = ac.createBuffer(1, n, b.sampleRate);
          const d = clip.getChannelData(0);
          for (let c = 0; c < b.numberOfChannels; c++) {
            const from = b.getChannelData(c);
            const at = Math.round(a * b.sampleRate);
            for (let i = 0; i < n; i++) d[i] = d[i]! + from[at + i]! / b.numberOfChannels;
          }
          return clip;
        });
      })
      .catch(() => undefined);
    // The one-shots can come in their own time.
    for (const id of ['crash-heavy', 'crash-light', 'hit-pole', 'hit-wood', 'hit-bush'] as const)
      decode(ac, id)
        .then((b) => {
          if (recorded) recorded.hits[id] = b;
        })
        .catch(() => undefined);
  } catch {
    // Keep the synthesized stand-ins.
    recorded = null;
  }
}

/**
 * A backfire, as a recording would have it: unburnt fuel going off in the hot exhaust.
 * Each is made sample by sample from what such a bang is made of:
 *
 * - the blast itself: a pressure wave that jumps up in a fraction of a millisecond and
 *   falls away below zero after it (a Friedlander wave, a few milliseconds long), which
 *   is the sharp crack;
 * - the exhaust it goes off in ringing: the pipe's own low notes, a deep thump, dying away
 *   over a tenth of a second or so;
 * - the hot gas rushing out after it: a burst of rough noise, a few tens of milliseconds;
 *
 * all pushed through a hard saturation, as a real one overloads the air (and the
 * microphone) for an instant. A bank of a dozen, each a little different, made once.
 */
function backfireBank(ac: AudioContext): AudioBuffer[] {
  const rate = ac.sampleRate;
  const bank: AudioBuffer[] = [];
  for (let k = 0; k < 12; k++) {
    const len = Math.round(rate * 0.32);
    const buf = ac.createBuffer(1, len, rate);
    const d = buf.getChannelData(0);
    // The blast: positive phase t* long, then the suction after it.
    const tStar = 0.0025 + Math.random() * 0.0035;
    const b = 1.2 + Math.random() * 0.8;
    // The pipe's resonances: a fundamental and a couple of overtones (not quite in tune).
    const f0 = 70 + Math.random() * 45;
    const modes = [
      { f: f0, a: 0.9, tau: 0.06 + Math.random() * 0.05 },
      { f: f0 * (2.7 + Math.random() * 0.4), a: 0.45, tau: 0.03 + Math.random() * 0.02 },
      { f: f0 * (4.9 + Math.random() * 0.6), a: 0.25, tau: 0.015 + Math.random() * 0.01 },
    ];
    const ph = modes.map(() => Math.random() * 0.4);
    // Rough gas noise: white noise through a simple one-pole low-pass, its own envelope.
    let lp = 0;
    const tauGas = 0.018 + Math.random() * 0.02;
    const bright = 0.35 + Math.random() * 0.3;
    for (let i = 0; i < len; i++) {
      const t = i / rate;
      const x = t / tStar;
      // Rising in a quarter of a millisecond, so it isn't a digital click.
      const rise = Math.min(1, t / 0.00025);
      const blast = rise * (1 - x) * Math.exp(-b * x);
      let ring = 0;
      for (let m = 0; m < modes.length; m++) {
        const mo = modes[m]!;
        ring += mo.a * Math.sin(2 * Math.PI * mo.f * t + ph[m]!) * Math.exp(-t / mo.tau);
      }
      ring *= Math.min(1, t / 0.0015);
      lp += bright * ((Math.random() * 2 - 1) - lp);
      const gas = lp * Math.exp(-t / tauGas) * Math.min(1, t / 0.001);
      const v = 1.6 * blast + 0.75 * ring + 0.55 * gas;
      // Overloaded for an instant.
      d[i] = Math.tanh(v * 2.2) / Math.tanh(2.2);
    }
    // A gentle fade at the end.
    for (let i = len - 400; i < len; i++) d[i] = d[i]! * ((len - i) / 400);
    bank.push(buf);
  }
  return bank;
}
let backfires: AudioBuffer[] | null = null;
/** Outside, each bang comes back off the buildings: a short, dull slap of an echo. */
let slap: { input: GainNode } | null = null;

function slapback(ac: AudioContext): { input: GainNode } {
  if (slap) return slap;
  const input = gainNode(ac, 1);
  const delay = ac.createDelay(0.5);
  delay.delayTime.value = 0.085;
  const fb = gainNode(ac, 0.28);
  const dull = filter(ac, 'lowpass', 1800, 0.5);
  const out = gainNode(ac, 0.35);
  input.connect(delay).connect(dull).connect(out).connect(master!);
  dull.connect(fb).connect(delay);
  slap = { input };
  return slap;
}

/** One bang, v loud, after delay; dulled through the cabin from inside. */
function backfire(ac: AudioContext, v: number, delay: number, inside: boolean, out: AudioNode = master!, rpm = 4500): void {
  const t = ac.currentTime + delay;
  const src = ac.createBufferSource();
  // The recorded car's own bangs, each a touch higher or lower; synthesized ones until
  // they've loaded.
  if (recordedPops) {
    const k = Math.floor(Math.random() * recordedPops.length);
    src.buffer = recordedPops[k]!;
    // Pitched up so its thump sits just under the engine's note at these revs (as the
    // bangs come from the same exhaust), a touch higher or lower each time.
    const want = (BACKFIRE_MATCH * Math.max(IDLE_RPM, rpm)) / 15 / BACKFIRE_PITCH[k]!;
    src.playbackRate.value = Math.max(0.9, Math.min(2.2, want)) * (0.96 + Math.random() * 0.08);
    // (Just the bang now, no engine under it: a little louder to sound as big.)
    v *= 1.4;
  } else {
    backfires ??= backfireBank(ac);
    src.buffer = backfires[Math.floor(Math.random() * backfires.length)]!;
    src.playbackRate.value = 0.9 + Math.random() * 0.2;
  }
  const g = gainNode(ac, v);
  if (out !== master) {
    src.connect(g).connect(out);
    src.start(t);
    return;
  }
  if (inside) {
    // Through the body and glass: the crack mostly gone, the thump left.
    src.connect(filter(ac, 'lowpass', 1400, 0.6)).connect(g).connect(master!);
  } else {
    src.connect(g).connect(master!);
    g.connect(slapback(ac).input);
  }
  src.start(t);
}

/**
 * When an exhaust pops, timed the way real ones are. Measured on three recordings (a
 * sports car blipping its throttle, a Mercedes-AMG V8 and a Chevrolet 350 V8 crackling
 * on the overrun): a good share of lift-offs give no pop at all; the rest give one or
 * two, now and then up to five or six; the first comes either straight away (20-90 ms
 * after lifting) or a little later (150-450 ms); they're never closer than about 70 ms
 * apart (typically 100-230 ms, the gaps lengthening as the burst goes on); each is
 * louder or quieter than the last (0.4 to 1 of the loudest); and getting back on the
 * throttle ends them. Upshifts on the throttle pop now and then, once; and coasting at
 * high revs crackles only occasionally.
 */
export class PopTimer {
  /** Pops waiting to go off (audio time), with their loudness (0..1). */
  private queue: { at: number; v: number }[] = [];
  private last = -1;
  private lastThrottle = 0;
  private lastGear = 1;

  /** Follow the car; play(v, when) is called for each pop as its moment comes. */
  update(now: number, throttle: number, rpmN: number, gear: number, play: (v: number, at: number) => void): void {
    // Back on the gas: the overrun's over.
    if (throttle > 0.4) this.queue = this.queue.filter((p) => p.at - now < 0.02);
    const lifted = this.lastThrottle > 0.5 && throttle < 0.1;
    if (lifted && rpmN > 0.35 && Math.random() < 0.3 + 0.4 * rpmN) {
      const r = Math.random();
      let n = r < 0.4 ? 1 : r < 0.72 ? 2 : r < 0.88 ? 3 : 4 + Math.floor(Math.random() * 3);
      // (Fewer from lower revs.)
      if (rpmN < 0.55 && n > 2) n = 2;
      let at = now + (Math.random() < 0.6 ? 0.02 + Math.random() * 0.07 : 0.15 + Math.random() * 0.3);
      const loudest = Math.floor(Math.random() * n);
      for (let k = 0; k < n; k++) {
        this.push(at, k === loudest ? 1 : 0.4 + Math.random() * 0.5);
        // The gaps: 70 ms at the least, mostly 90-250, lengthening through the burst.
        at += (0.07 + Math.random() * 0.15) * (1 + k * 0.25) + (Math.random() < 0.15 ? 0.15 + Math.random() * 0.2 : 0);
      }
    }
    // An upshift on the throttle: now and then one pop, as the ignition cuts.
    if (gear > this.lastGear && this.lastGear > 0 && this.lastThrottle > 0.5 && Math.random() < 0.4) this.push(now + 0.03 + Math.random() * 0.05, 0.5 + Math.random() * 0.5);
    // Coasting at high revs: the odd one, about every three seconds.
    if (throttle < 0.1 && rpmN > 0.5 && !this.queue.length && Math.random() < 0.006) this.push(now + 0.01, 0.35 + Math.random() * 0.4);
    this.lastThrottle = throttle;
    this.lastGear = gear;
    // Those due in the next moment, at their exact time.
    while (this.queue.length && this.queue[0]!.at < now + 0.05) {
      const p = this.queue.shift()!;
      play(p.v, Math.max(now, p.at));
    }
  }

  private push(at: number, v: number): void {
    // Never closer than 70 ms to the one before.
    const prev = Math.max(this.last, this.queue.length ? this.queue[this.queue.length - 1]!.at : -1);
    if (at < prev + 0.07) at = prev + 0.07;
    this.queue.push({ at, v });
    this.queue.sort((a, b) => a.at - b.at);
    this.last = Math.max(this.last, at);
  }
}
const playerPops = new PopTimer();

/** Play a one-shot recording (from a start point, for a length), at a rate and volume. */
function play(ac: AudioContext, buf: AudioBuffer | undefined, volume: number, rate = 1, from = 0, length?: number): boolean {
  if (!buf) return false;
  const src = ac.createBufferSource();
  src.buffer = buf;
  src.playbackRate.value = rate;
  const g = gainNode(ac, volume);
  src.connect(g).connect(master!);
  src.start(ac.currentTime, from, length);
  return true;
}

function updateRecorded(ac: AudioContext, r: Recorded, s: CarSound): void {
  const t = ac.currentTime;
  const rv = Math.max(0, s.rev);
  // The car's revs, to rpm: 0.2 is idle, 0.95 the red line (a slide can push past it,
  // into the limiter).
  const rpm = IDLE_RPM + ((rv - 0.2) / 0.75) * (REDLINE_RPM - IDLE_RPM);
  const onLimiter = rpm >= REDLINE_RPM * 0.995 && s.throttle > 0.5;
  // The limiter cuts the sparks in quick bursts, which bounces the revs off it.
  const chop = onLimiter && t % 0.11 < 0.045;
  r.engine.rpm = Math.min(REDLINE_RPM, rpm) - (chop ? 250 : 0);
  // A gear change never silences it: the engine keeps firing while the throttle is
  // eased with the clutch in and the revs fall to the new gear, then it pulls again.
  const easing = s.shifting > 0 ? 0.45 : 1;
  r.engine.load = s.running ? s.throttle * easing : 0;
  r.engine.ignition = s.running && !chop;
  // Harder into the rasp on the throttle at high revs; from inside, the cabin dulls it.
  const rpmN = Math.min(1, Math.max(0, (rpm - IDLE_RPM) / (REDLINE_RPM - IDLE_RPM)));
  r.drive.gain.setTargetAtTime(0.9 + s.throttle * rpmN * 0.5, t, 0.05);
  r.muffle.frequency.setTargetAtTime(s.inside ? 2400 : 5500, t, 0.1);
  r.engineGain.gain.setTargetAtTime(s.running ? (s.inside ? 0.7 : 0.68) : 0, t, 0.08);
  // Tyres: squeal on tarmac; off it the gravel crunches instead, harder in a slide.
  updateTyres(ac, r.tyres, s);
  const crunch = s.running && !s.paved ? Math.min(1, s.speed / 25) * (0.5 + s.slide * 0.8) : 0;
  r.gravelGain.gain.setTargetAtTime(crunch * 0.95, t, 0.08);
  r.gravel.playbackRate.setTargetAtTime(0.75 + Math.min(1, s.speed / 40) * 0.5, t, 0.1);
  pops(ac, s);
}

/** Lifting off at high revs, every gear change, and now and then on the overrun: backfires. */
function pops(ac: AudioContext, s: CarSound): void {
  const rpmN = Math.min(1, Math.max(0, (Math.max(0, s.rev) - 0.2) / 0.75));
  const rpm = IDLE_RPM + rpmN * (REDLINE_RPM - IDLE_RPM);
  if (s.running && enabled) {
    const v0 = s.inside ? 0.45 : 0.75;
    playerPops.update(ac.currentTime, s.throttle, rpmN, s.gear, (v, at) => backfire(ac, v * v0, at - ac.currentTime, s.inside, master!, rpm));
    // The gear lever's clack, from inside.
    if (s.gear !== lastGear && s.gear > 0 && lastGear > 0 && s.inside) burst(ac, 2200, 3, 0.05, 0.03, 0.05);
  }
  lastGear = s.gear;
}

// ---------------------------------------------------------------------------
// Tyre roar (filtered noise, which is what it is)

interface Road {
  roarGain: GainNode;
  roarTone: BiquadFilterNode;
}
let road: Road | null = null;

function startRoad(ac: AudioContext, out: GainNode, noise: AudioBuffer): Road {
  // Tyres rolling on tarmac: a low rumble that opens up with speed.
  const a = ac.createBufferSource();
  a.buffer = noise;
  a.loop = true;
  const roarTone = filter(ac, 'lowpass', 300, 0.8);
  const roarGain = gainNode(ac);
  a.connect(filter(ac, 'lowpass', 1200)).connect(roarTone).connect(roarGain).connect(out);
  a.start();
  return { roarGain, roarTone };
}

function updateRoad(ac: AudioContext, rd: Road, s: CarSound): void {
  const t = ac.currentTime;
  const v = Math.min(1.2, s.speed / 45);
  rd.roarGain.gain.setTargetAtTime(s.running && s.paved ? v * (s.inside ? 0.16 : 0.1) : 0, t, 0.1);
  rd.roarTone.frequency.setTargetAtTime(160 + v * 700, t, 0.1);
}

// ---------------------------------------------------------------------------
// Stand-ins until the recordings are ready

interface StandIns {
  engineA: OscillatorNode;
  engineFilter: BiquadFilterNode;
  engineGain: GainNode;
  skidGain: GainNode;
}
let stand: StandIns | null = null;

function startStandIns(ac: AudioContext, out: GainNode, noise: AudioBuffer): StandIns {
  const engineGain = gainNode(ac);
  const engineFilter = filter(ac, 'lowpass', 600, 2);
  const engineA = ac.createOscillator();
  engineA.type = 'sawtooth';
  engineA.connect(engineFilter).connect(engineGain).connect(engineBus ?? out);
  engineA.start();
  const src = ac.createBufferSource();
  src.buffer = noise;
  src.loop = true;
  const skidGain = gainNode(ac);
  src.connect(filter(ac, 'bandpass', 2000, 5)).connect(skidGain).connect(out);
  src.start();
  return { engineA, engineFilter, engineGain, skidGain };
}

// ---------------------------------------------------------------------------
// Menu music

/** The menu's music: loaded the first time it's wanted, then looped. */
let music: { src: AudioBufferSourceNode; gain: GainNode } | null = null;
let musicLoading = false;
let musicWanted = false;
/** The MP3 encoder's lead-in (seconds of silence before the music starts), skipped on each loop. */
const MUSIC_LEAD = 1524 / 44100;
const MUSIC_LEVEL = 0.5;
/**
 * The music's own length, to the loop point: 55 beats at 67.4 BPM, so it comes round
 * again on the beat. (Not the decoded file's length, which has the encoder's padding on
 * the end: looping there would leave a gap.)
 */
const MUSIC_LENGTH = 49.0;

/**
 * Music in the menus: on (fading in) while wanted, fading out when not. It loops for as
 * long as the menus are up, and carries on from where it was when they come back.
 */
export function setMenuMusic(on: boolean): void {
  musicWanted = on;
  const ac = audio;
  if (!ac || !master) return;
  if (!music) {
    if (!on || musicLoading) return;
    musicLoading = true;
    decode(ac, 'menu-music')
      .then((buf) => {
        const src = ac.createBufferSource();
        src.buffer = buf;
        src.loop = true;
        src.loopStart = MUSIC_LEAD;
        src.loopEnd = Math.min(buf.duration, MUSIC_LEAD + MUSIC_LENGTH);
        const gain = gainNode(ac, 0);
        src.connect(gain).connect(musicBus!);
        src.start(ac.currentTime, MUSIC_LEAD);
        music = { src, gain };
        setMenuMusic(musicWanted);
      })
      .catch(() => {
        musicLoading = false;
      });
    return;
  }
  music.gain.gain.setTargetAtTime(on ? MUSIC_LEVEL : 0, ac.currentTime, on ? 0.35 : 0.2);
}

// ---------------------------------------------------------------------------
// The rivals' engines

/** What a rival's engine is doing, and where it is from the listener. */
export interface RivalSound {
  rev: number;
  throttle: number;
  gear: number;
  shifting: number;
  /** Metres from the listener, and how far to its right (-1 left to 1 right). */
  dist: number;
  pan: number;
}

interface RivalVoice {
  engine: { rpm: number; load: number; ignition: boolean };
  node: ScriptProcessorNode;
  muffle: BiquadFilterNode;
  gain: GainNode;
  pan: StereoPannerNode;
  /** Where its backfires go in (so they come from where the car is). */
  pops: GainNode;
  popMuffle: BiquadFilterNode;
  popGain: GainNode;
  popPan: StereoPannerNode;
  timer: PopTimer;
}
const rivalVoices: RivalVoice[] = [];

function rivalVoice(ac: AudioContext, buf: AudioBuffer): RivalVoice {
  const voice = engineVoice(buf);
  const engine = { rpm: IDLE_RPM, load: 0, ignition: true };
  const node = ac.createScriptProcessor(1024, 0, 1);
  node.onaudioprocess = (e) => voice.render(e.outputBuffer.getChannelData(0), engine);
  const shaper = ac.createWaveShaper();
  shaper.curve = rasp(1.2);
  const body = filter(ac, 'peaking', 150, 0.8, 5);
  const muffle = filter(ac, 'lowpass', 8000, 0.6);
  const gain = gainNode(ac);
  const pan = ac.createStereoPanner();
  node.connect(shaper).connect(body).connect(muffle).connect(gain).connect(pan).connect(engineBus!);
  // Its backfires are effects: duller and quieter with distance, from its side, like the engine.
  const pops = gainNode(ac, 1);
  const popMuffle = filter(ac, 'lowpass', 8000, 0.6);
  const popGain = gainNode(ac);
  const popPan = ac.createStereoPanner();
  pops.connect(popMuffle).connect(popGain).connect(popPan).connect(master!);
  return { engine, node, muffle, gain, pan, pops, popMuffle, popGain, popPan, timer: new PopTimer() };
}

/**
 * The rivals' engines, each heard from where it is: quieter and duller further off, from
 * the side it's on, with its own revs and its own backfires. An empty list (no race, or
 * paused) fades them out. Call every frame.
 */
export function updateRivalSounds(list: RivalSound[]): void {
  const ac = audio;
  if (!ac || !master || !engineBuf) return;
  const t = ac.currentTime;
  while (rivalVoices.length < list.length) rivalVoices.push(rivalVoice(ac, engineBuf));
  rivalVoices.forEach((v, i) => {
    const s = list[i];
    if (!s) {
      v.gain.gain.setTargetAtTime(0, t, 0.15);
      v.popGain.gain.setTargetAtTime(0, t, 0.15);
      v.engine.load = 0;
      return;
    }
    const rv = Math.max(0, s.rev);
    const rpm = IDLE_RPM + ((rv - 0.2) / 0.75) * (REDLINE_RPM - IDLE_RPM);
    v.engine.rpm = Math.min(REDLINE_RPM, rpm);
    v.engine.load = s.throttle * (s.shifting > 0 ? 0.45 : 1);
    v.engine.ignition = true;
    // Falling off with distance (a little under the inverse square, as a road's echoes
    // carry it), and duller the further it is.
    const near = 1 / (1 + (s.dist / 14) ** 2);
    v.gain.gain.setTargetAtTime(s.dist > 220 ? 0 : 0.7 * near, t, 0.08);
    v.muffle.frequency.setTargetAtTime(1200 + 7000 * Math.max(near, 1 / (1 + s.dist / 40)), t, 0.1);
    v.pan.pan.setTargetAtTime(Math.max(-0.9, Math.min(0.9, s.pan)), t, 0.08);
    v.popGain.gain.setTargetAtTime(s.dist > 220 ? 0 : 0.7 * near, t, 0.08);
    v.popMuffle.frequency.setTargetAtTime(1200 + 7000 * Math.max(near, 1 / (1 + s.dist / 40)), t, 0.1);
    v.popPan.pan.setTargetAtTime(Math.max(-0.9, Math.min(0.9, s.pan)), t, 0.08);
    // Its backfires: lifting off at high revs, and on a gear change.
    const rpmN = Math.min(1, Math.max(0, (rpm - IDLE_RPM) / (REDLINE_RPM - IDLE_RPM)));
    if (enabled && s.dist < 120) {
      v.timer.update(t, s.throttle, rpmN, s.gear, (lv, at) => backfire(ac, 0.85 * lv, at - t, false, v.pops, rpm));
    }
  });
}

/** Follow the car. Call every frame. */
export function updateCarSound(s: CarSound): void {
  if (!audio || !stand) return;
  if (road) updateRoad(audio, road, s);
  if (recorded) {
    updateRecorded(audio, recorded, s);
    return;
  }
  const t = audio.currentTime;
  const f = 30 + Math.min(1.15, s.rev) * 230;
  stand.engineA.frequency.setTargetAtTime(f, t, 0.05);
  stand.engineFilter.frequency.setTargetAtTime(300 + s.rev * 900 + s.throttle * 700, t, 0.06);
  stand.engineGain.gain.setTargetAtTime(s.running ? (0.04 + s.throttle * 0.05) * (s.inside ? 1 : 0.8) : 0, t, 0.08);
  stand.skidGain.gain.setTargetAtTime(s.running && s.paved ? Math.min(1, Math.max(s.slide, s.spin)) * 0.2 : 0, t, 0.05);
  pops(audio, s);
}

// ---------------------------------------------------------------------------
// One-shots

function ready(): AudioContext | null {
  return enabled && audio && master && noiseBuf ? audio : null;
}

function burst(ac: AudioContext, freq: number, q: number, peak: number, decay: number, delay = 0): void {
  const t = ac.currentTime + delay;
  const src = ac.createBufferSource();
  src.buffer = noiseBuf;
  const f = filter(ac, 'bandpass', freq, q);
  const g = ac.createGain();
  g.gain.setValueAtTime(0, t);
  g.gain.linearRampToValueAtTime(peak, t + 0.005);
  g.gain.exponentialRampToValueAtTime(0.0001, t + decay);
  src.connect(f).connect(g).connect(master!);
  src.start(t, Math.random() * 1.5);
  src.stop(t + decay + 0.05);
}

function tone(ac: AudioContext, type: OscillatorType, f0: number, f1: number, peak: number, decay: number, delay = 0): void {
  const t = ac.currentTime + delay;
  const o = ac.createOscillator();
  o.type = type;
  o.frequency.setValueAtTime(f0, t);
  o.frequency.exponentialRampToValueAtTime(f1, t + decay);
  const g = ac.createGain();
  g.gain.setValueAtTime(0, t);
  g.gain.linearRampToValueAtTime(peak, t + 0.005);
  g.gain.exponentialRampToValueAtTime(0.0001, t + decay);
  o.connect(g).connect(master!);
  o.start(t);
  o.stop(t + decay + 0.05);
}

const vary = () => 0.92 + Math.random() * 0.16;

/** Hitting a wall or a tree; power is the impact speed in m/s. */
export function sfxCrash(power: number): void {
  const ac = ready();
  if (!ac) return;
  const v = Math.min(1, power / 25);
  if (v < 0.08) return;
  const hits = recorded?.hits;
  // A real collision: the heavy one for big hits, the light one for knocks and scrapes,
  // pitched down a little the harder it is. A low thump under it for weight.
  const heavy = v > 0.45;
  const played = play(ac, hits?.[heavy ? 'crash-heavy' : 'crash-light'], 0.35 + v * 0.65, (heavy ? 1.05 - v * 0.2 : 1.15 - v * 0.2) * vary());
  tone(ac, 'sine', 95, 38, (played ? 0.35 : 0.5) * v, 0.3);
  if (!played) {
    burst(ac, 500, 0.8, 0.45 * v, 0.25);
    burst(ac, 2600, 1.5, 0.2 * v, 0.18, 0.02);
  }
}

/** Landing a jump; fall is how fast it was coming down (m/s). */
export function sfxLand(fall: number): void {
  const ac = ready();
  if (!ac) return;
  const v = Math.min(1, fall / 18);
  // The suspension bottoming out: a deep thud with a muffled knock of the body on top.
  tone(ac, 'sine', 80, 32, 0.55 * v, 0.35);
  if (!play(ac, recorded?.hits['crash-light'], 0.25 * v, 0.62 * vary())) burst(ac, 400, 0.8, 0.3 * v, 0.2);
  burst(ac, 180, 0.7, 0.25 * v, 0.25);
}

/** Knocking something over: a clang for a lamp post, a crack for a tree, a rustle for a bush. */
export function sfxKnock(kind: PropKind, power: number): void {
  const ac = ready();
  if (!ac) return;
  const v = Math.min(1, 0.35 + power / 25);
  const hits = recorded?.hits;
  if (kind === 'lamp') {
    // The pole's ring, and the knock of the car hitting it.
    if (!play(ac, hits?.['hit-pole'], 0.8 * v, 0.85 * vary())) {
      tone(ac, 'triangle', 620, 560, 0.16 * v, 0.6);
      burst(ac, 3000, 2, 0.12 * v, 0.08);
    }
    play(ac, hits?.['crash-light'], 0.35 * v, 1.1 * vary());
  } else if (kind === 'tree') {
    // The trunk cracking (just the first crack of the recording), then it hitting the ground.
    if (!play(ac, hits?.['hit-wood'], 0.9 * v, 0.8 * vary(), 0, 0.7)) {
      burst(ac, 1800, 1.2, 0.3 * v, 0.07);
      burst(ac, 900, 0.8, 0.2 * v, 0.12, 0.03);
    }
    play(ac, hits?.['hit-bush'], 0.45 * v, 0.8 * vary());
    burst(ac, 300, 0.7, 0.3 * v, 0.3, 0.75);
  } else if (kind === 'sign' || kind === 'mailbox') {
    // A thinner steel post: the pole's ring pitched up, and a tinny knock.
    if (!play(ac, hits?.['hit-pole'], 0.55 * v, 1.35 * vary())) tone(ac, 'triangle', 900, 820, 0.12 * v, 0.4);
    play(ac, hits?.['crash-light'], 0.3 * v, 1.35 * vary());
  } else if (kind === 'hydrant') {
    // Cast iron: a dull clank, then the gush of water.
    play(ac, hits?.['hit-pole'], 0.7 * v, 0.6 * vary(), 0, 0.5);
    play(ac, hits?.['crash-light'], 0.55 * v, 0.8 * vary());
    burst(ac, 1800, 0.5, 0.12 * v, 1.6, 0.1);
  } else if (kind === 'trash' || kind === 'barrier') {
    // Hollow metal or plastic, bouncing away.
    play(ac, hits?.['crash-light'], 0.45 * v, (kind === 'trash' ? 1.45 : 1.25) * vary());
    play(ac, hits?.['crash-light'], 0.2 * v, 1.6 * vary(), 0, 0.2);
  } else if (kind === 'fence' || kind === 'bench') {
    // Wooden slats splintering.
    play(ac, hits?.['hit-wood'], 0.7 * v, (kind === 'fence' ? 1.1 : 0.95) * vary(), 0, 0.6);
  } else if (kind === 'cone') {
    // A soft plastic thwack.
    tone(ac, 'sine', 220, 120, 0.18 * v, 0.08);
    burst(ac, 1400, 1.5, 0.12 * v, 0.06);
  } else if (kind === 'box' || kind === 'hay') {
    // Cardboard crumpling, or a bale thumping away.
    play(ac, hits?.['hit-bush'], 0.6 * v, (kind === 'box' ? 1.25 : 0.7) * vary());
    if (kind === 'hay') tone(ac, 'sine', 90, 50, 0.25 * v, 0.2);
  } else if (!play(ac, hits?.['hit-bush'], 0.75 * v, vary())) {
    burst(ac, 5000, 0.6, 0.18 * v, 0.35);
  }
}

/** A drift banked: a bright rising chime, higher for bigger scores. */
export function sfxBank(size: number): void {
  const ac = ready();
  if (!ac) return;
  const base = 523 * Math.pow(2, Math.min(1, size) * 0.5);
  tone(ac, 'triangle', base, base, 0.14, 0.18);
  tone(ac, 'triangle', base * 1.5, base * 1.5, 0.14, 0.3, 0.08);
}

/** The drift was lost to a crash. */
export function sfxLost(): void {
  const ac = ready();
  if (!ac) return;
  tone(ac, 'square', 300, 120, 0.06, 0.35);
}

export function sfxClick(): void {
  const ac = ready();
  if (!ac) return;
  tone(ac, 'triangle', 1200, 900, 0.08, 0.05);
  burst(ac, 3000, 4, 0.05, 0.02);
}

/** Which sounds are playing: the recordings, the synthesized stand-ins, or none yet. */
export function soundStatus(): { source: 'recorded' | 'synth' | 'off'; hits: string[]; engineRunning: boolean } {
  return {
    source: recorded ? 'recorded' : audio ? 'synth' : 'off',
    hits: Object.keys(recorded?.hits ?? {}),
    engineRunning: !!engineNode,
  };
}