Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
synthesize SongBook drum play-along through selectable TR-909/TR-808/Acoustic kits with a punchy kick
[._.]/ Adam Eivyee14e149c59f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b4fc78b7e0..6085ca6500 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -44,6 +44,8 @@## SongBook+- **Drum charts now play through a real drum-machine kit, with a punchy kick.** The play-along kit was synthesized from a single generic recipe, and the kick came out weak: its pitch slid from the attack all the way down across its whole (very short) tail, so it never settled on a fundamental and never developed any body — on a phone or laptop speaker it barely registered under the hats. The kit has been rebuilt as three you can choose between from the practice settings: **TR-909** (the new default — attack-forward kick, bright snare crack, tight hats), **TR-808** (deep sub kick with a long tail, thin snare, metallic square-cluster hats), and **Acoustic** (rounder, closer to a studio kit). Every drum now snaps to its pitch in the first few hundredths of a second and then rings out, the way a real drum machine does, and the low drums are saturated so the harmonics carry the kick on small speakers that can't reproduce a 48 Hz fundamental at all — measured, that puts about 9 dB more of the kick through a small-speaker response than the old recipe. The whole kit runs into a soft limiter, so a downbeat stacking kick, crash and metronome no longer clips. Swapping kits applies immediately without stopping playback, and your choice is remembered on that machine.+- **[issue-3222] Drum-chart previews are now audible while you write or import.** The editor and import preview both include the full practice transport, animate the sounding chart's playhead, and keep playing the snapshot captured at Play even as you continue typing; a clear reload notice appears when the draft changes.- **Drum charts now play the whole song as one continuous, phone-readable strip.** The kit sheet was a vertical stack of per-bar grids — on a phone, two transport rows and a controls row pushed all but a bar and a half below the fold, and reading a groove meant scrolling down between bars. The whole song is now a single horizontal lane that scrolls under a playhead as it plays, with the kit-piece labels frozen in their own column so "which row is the snare" survives scrolling to bar 30, and A−/A+ zooming the grid. The playhead glides off the audio clock instead of hopping between hits, so it keeps moving across rests and through a bar with no hits at all. The transport is split for a phone: play, tempo (with ± steppers), the metronome and a live beat-pulse/bar readout stay visible, while practice speed, count-in and the loop range collapse behind a settings button until there's room for them. The metronome now defaults on and remembers being switched off, and a drum chart no longer shows the vertical autoscroll transport — its rival "play" button that scrolled the page instead of the song.diff --git a/client/src/components/songbook/DrumPreview.jsx b/client/src/components/songbook/DrumPreview.jsxindex ecfbb614da..771e8fe65c 100644--- a/client/src/components/songbook/DrumPreview.jsx+++ b/client/src/components/songbook/DrumPreview.jsx@@ -57,6 +57,12 @@ export default function DrumPreview({player.setClickEnabled(enabled);settingsMirror?.setClickEnabled(enabled);}, [player.setClickEnabled, settingsMirror]);+ // The kit persists globally, but the viewer's transport already read it at+ // mount — mirror the change so the two don't disagree until a reload.+ const setKitId = useCallback((next) => {+ player.setKitId(next);+ settingsMirror?.setKitId(next);+ }, [player.setKitId, settingsMirror]);const toggle = useCallback(() => {player.toggle();@@ -85,6 +91,8 @@ export default function DrumPreview({barCount={player.barCount}clickEnabled={player.clickEnabled}onClickToggle={setClickEnabled}+ kitId={player.kitId}+ onKitChange={setKitId}beatsPerBar={player.beatsPerBar}pulse={player.pulse}currentBar={player.currentBar}diff --git a/client/src/components/songbook/DrumTransportBar.jsx b/client/src/components/songbook/DrumTransportBar.jsxindex 48b355f2ff..f79771ee27 100644--- a/client/src/components/songbook/DrumTransportBar.jsx+++ b/client/src/components/songbook/DrumTransportBar.jsx@@ -4,9 +4,10 @@* Purely presentational over `useDrumPlayer`: play/stop, a practice-tempo* stepper + number input (slider on wider screens, clamped by `clampBpm`,* 20–320), percent-of-written quick buttons that recompute BPM from the chart's- * `tempo:` marking, a count-in select, a loop toggle with a from/to bar range,- * a metronome-click toggle, and a live beat/bar readout. All state and audio- * live in the hook — this file only renders and calls back.+ * `tempo:` marking, a kit picker (TR-909 / TR-808 / Acoustic), a count-in select,+ * a loop toggle with a from/to bar range, a metronome-click toggle, and a live+ * beat/bar readout. All state and audio live in the hook — this file only+ * renders and calls back.** PHONE-FIRST LAYOUT. A phone is the primary SongBook surface, and the previous* one-flat-wrapping-row bar cost three stacked rows (~330px) before the sheet@@ -24,6 +25,7 @@import { useMemo, useState } from 'react';import { Play, Square, Repeat, Timer, Minus, Plus, SlidersHorizontal } from 'lucide-react';import { METRONOME_BPM_MIN, METRONOME_BPM_MAX } from '../../lib/metronome.js';+import { DRUM_KIT_LIST, resolveDrumKit } from '../../lib/drumKits.js';import { ctrlBtnClass, activeCtrlClass } from './constants.js';// Practice speeds as a percentage of the chart's written tempo.@@ -66,6 +68,7 @@ export default function DrumTransportBar({countInBars, onCountInChange,loopEnabled, onLoopToggle, loopFrom, loopTo, onLoopRangeChange, barCount,clickEnabled, onClickToggle,+ kitId, onKitChange,beatsPerBar = 4, pulse = null, currentBar = null,}) {// Setup controls: collapsed by default on a phone, always shown from `sm` up.@@ -207,6 +210,24 @@ export default function DrumTransportBar({))}</div>+ {/* Which synthesized kit sounds the chart. A taste setting rather than a+ practice one, so it sits with the setup controls — but it applies+ live, without stopping playback. */}+ <div className="flex items-center gap-2">+ <label htmlFor="drum-kit" className="text-xs text-gray-400">Kit</label>+ <select+ id="drum-kit"+ value={kitId}+ onChange={(e) => onKitChange(e.target.value)}+ className={smallSelectClass}+ title={resolveDrumKit(kitId).description}+ >+ {DRUM_KIT_LIST.map((kit) => (+ <option key={kit.id} value={kit.id}>{kit.label}</option>+ ))}+ </select>+ </div>+<div className="flex items-center gap-2"><label htmlFor="drum-countin" className="text-xs text-gray-400">Count-in</label><selectdiff --git a/client/src/components/songbook/DrumTransportBar.test.jsx b/client/src/components/songbook/DrumTransportBar.test.jsxindex 610d50c7fd..d68c56d493 100644--- a/client/src/components/songbook/DrumTransportBar.test.jsx+++ b/client/src/components/songbook/DrumTransportBar.test.jsx@@ -1,6 +1,7 @@import { describe, it, expect, vi, afterEach } from 'vitest';import { render, screen, fireEvent, cleanup } from '@testing-library/react';import DrumTransportBar from './DrumTransportBar.jsx';+import { DRUM_KIT_IDS } from '../../lib/drumKits.js';// The phone-first split (primary controls always visible, setup behind a// disclosure under `sm`) is the whole point of this bar — pin it, plus the@@ -23,6 +24,8 @@ const props = (extra = {}) => ({barCount: 4,clickEnabled: true,onClickToggle: vi.fn(),+ kitId: '909',+ onKitChange: vi.fn(),beatsPerBar: 4,pulse: null,currentBar: 1,@@ -80,6 +83,16 @@ describe('DrumTransportBar', () => {expect(screen.getByRole('status').querySelectorAll('span')).toHaveLength(6);});+ it('picks the kit from the setup row, listing every kit', () => {+ const p = props();+ render(<DrumTransportBar {...p} />);+ const select = screen.getByLabelText('Kit');+ expect(select.value).toBe('909');+ expect([...select.options].map((o) => o.value)).toEqual(DRUM_KIT_IDS);+ fireEvent.change(select, { target: { value: '808' } });+ expect(p.onKitChange).toHaveBeenCalledWith('808');+ });+it('marks the percent button matching the current BPM', () => {render(<DrumTransportBar {...props({ bpm: 48, writtenTempo: 96 })} />);expect(screen.getByRole('button', { name: '50%' }).getAttribute('aria-pressed')).toBe('true');diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 8d8f2df888..8601593fea 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -180,5 +180,5 @@ grep -i "what you want to do" client/src/hooks/README.md| `useCanvasDprSize` | DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers (`<PianoRoll>`, `<MidiPianoRoll>`): sizes the bitmap to container-width × height at the DPR, applies the transform, and redraws via a `drawRef` on mount + every `ResizeObserver` resize (observer created once per height, never churned by draw-closure changes). Returns a ref holding the current CSS width so draw code doesn't measure the DOM per frame. | Both piano-roll canvases. || `useCanvasRollPalette` | Resolves the roll canvas palette (theme-following `--port-accent` + roll bg via `rollPalette`) into a ref, re-resolving on theme switch (`data-port-theme` MutationObserver) and repainting through a `drawRef`. Hands back a ref, not state, so a theme swap redraws the imperative canvas without a React re-render. | Both piano-roll canvases need theme-aware accent/bg colors that canvas `fillStyle` can't read from CSS vars. || `useMidiNotes` | Fetch + parse a transcribed `.mid` file into the piano-roll view-model (`parseMidiFile` in `lib/midiNotes.js`), with a module-level per-URL cache so remounts (collapse, tab switches) don't refetch/reparse. Returns `{ status: 'idle'\|'loading'\|'ready'\|'error', data, error, reload }`; a generation counter drops stale in-flight responses on URL change/unmount. Plain `fetch` of the static file URL — errors surface inline, never as toasts (#2477). | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |-| `useDrumPlayer` | Drum play-along transport for a SongBook `drum` chart (#3115): parses the chart (`lib/drumNotation.js`), owns one `createDrumPlayer` per chart plus the practice settings and the sheet playhead. Returns `{ chart, barCount, writtenTempo, bpm, setBpm, setBpmPercent, countInBars, setCountInBars, loopEnabled, setLoopEnabled, loopFrom, loopTo, setLoopRange, clickEnabled, setClickEnabled, playing, activeStep, currentBar, toggle, stop }`. The practice tempo persists per song in `safeStorage` (never into the record); a timing-critical edit (tempo / count-in / loop) STOPS playback rather than re-timing already-scheduled audio, while the click toggle applies live; the player + its interval + scheduled hits tear down on stop, chart change and unmount. | The SongBook viewer and snapshot-based drum previews. Don't hand-wire `createDrumPlayer` + BPM persistence + playhead state again. |+| `useDrumPlayer` | Drum play-along transport for a SongBook `drum` chart (#3115): parses the chart (`lib/drumNotation.js`), owns one `createDrumPlayer` per chart plus the practice settings and the sheet playhead. Returns `{ chart, barCount, writtenTempo, bpm, setBpm, setBpmPercent, countInBars, setCountInBars, loopEnabled, setLoopEnabled, loopFrom, loopTo, setLoopRange, clickEnabled, setClickEnabled, kitId, setKitId, playing, activeStep, currentBar, toggle, stop }`. The practice tempo persists per song in `safeStorage` (never into the record) and the selected kit (`songbook:drumKit`) persists per MACHINE; a timing-critical edit (tempo / count-in / loop) STOPS playback rather than re-timing already-scheduled audio, while the click toggle and the kit swap apply live; the player + its interval + scheduled hits tear down on stop, chart change and unmount. | The SongBook viewer and snapshot-based drum previews. Don't hand-wire `createDrumPlayer` + BPM persistence + playhead state again. || `useMidiPlayer` | React wrapper over `lib/midiPlayback.js` (#2490): one synth player per parsed MIDI view-model, torn down when the data changes/unmounts so oscillators never outlive the roll. Returns `{ playing, toggle, seek(sec), getPosition }` — `getPosition` is the stable ref the `<MidiPianoRoll>` rAF playhead reads; no AudioContext is touched until the first toggle. A resume failure resets `playing` instead of lying. | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |diff --git a/client/src/hooks/useDrumPlayer.js b/client/src/hooks/useDrumPlayer.jsindex c0483e8878..4243d42835 100644--- a/client/src/hooks/useDrumPlayer.js+++ b/client/src/hooks/useDrumPlayer.js@@ -1,10 +1,14 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { parseDrumChart, chartHasMusic } from '../lib/drumNotation.js';import { createDrumPlayer, resolveLoopRange, resolvePlayhead } from '../lib/drumPlayback.js';+import { resolveDrumKit } from '../lib/drumKits.js';import { clampBpm } from '../lib/metronome.js';import { useLocalStorageBool } from './useLocalStorageBool.js';import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';+// The selected kit is global to the machine (see the `kitId` state below).+const KIT_STORAGE_KEY = 'songbook:drumKit';+/*** Drum play-along transport for a SongBook `drum` chart (#3115) — React wrapper* over `lib/drumPlayback.js`. Owns the player lifecycle, the practice settings@@ -20,8 +24,9 @@ import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';* A timing-critical edit (tempo, count-in, loop range) while playing STOPS* playback rather than re-timing a running schedule — already-scheduled audio* can't be moved, so a live rebase would desync the position from what you hear.- * The user presses play again at the new setting. The click toggle is the- * exception: it only gates FUTURE scheduling, so it applies live.+ * The user presses play again at the new setting. The click toggle and the kit+ * selection are the exceptions: they only gate FUTURE scheduling, so they apply+ * live.** Settings live in state AND are pushed into the player by a sync effect, so the* order the seeding effects happen to run in can't leave the player holding a@@ -74,6 +79,11 @@ export default function useDrumPlayer(text, { songId, initialSettings } = {}) {// against no pulse is the unusual case, and "never chosen" must not read as// "chosen off" (the hook's own default handles that distinction).const [clickEnabled, setClickEnabled] = useLocalStorageBool('songbook:drumClick', true);+ // Which synth kit sounds the chart (909 / 808 / acoustic). Like the metronome+ // it's a taste setting global to the MACHINE, not per song — and it changes no+ // timing, so unlike the tempo/loop settings it applies without stopping+ // playback. `resolveDrumKit` normalizes a missing or stale stored id.+ const [kitId, setKitIdState] = useState(() => resolveDrumKit(safeReadStorage(KIT_STORAGE_KEY)).id);const [playing, setPlaying] = useState(false);const [pulse, setPulse] = useState(null);@@ -138,6 +148,12 @@ export default function useDrumPlayer(text, { songId, initialSettings } = {}) {player.setClick(clickEnabled);}, [chart, bpm, countInBars, loopEnabled, loopFrom, loopTo, clickEnabled]);+ // The kit gets its OWN effect rather than joining the one above: each timing+ // setter there rebuilds the schedule while idle, so folding the kit in would+ // re-flatten and re-sort every event three times over to deliver what is+ // really a one-line assignment.+ useEffect(() => { playerRef.current?.setKit(kitId); }, [chart, kitId]);+// Live playhead read — the source both consumers below share. Stable identity// so a caller's animation-frame loop can depend on it without restarting.const getPlayhead = useCallback(() => {@@ -203,6 +219,14 @@ export default function useDrumPlayer(text, { songId, initialSettings } = {}) {if (storageKey) safeWriteStorage(storageKey, String(clamped));}, [stopIfPlaying, storageKey]);+ // Kit swaps affect no timing, so playback keeps running — the sync effect above+ // hands the new kit to the live player and the next scheduled hit uses it.+ const setKitId = useCallback((next) => {+ const id = resolveDrumKit(next).id;+ setKitIdState(id);+ safeWriteStorage(KIT_STORAGE_KEY, id);+ }, []);+// Percent of the chart's WRITTEN tempo (the practice-slower control).const setBpmPercent = useCallback((percent) => {setBpm(Math.round((writtenTempo * percent) / 100));@@ -249,6 +273,8 @@ export default function useDrumPlayer(text, { songId, initialSettings } = {}) {setLoopRange,clickEnabled,setClickEnabled,+ kitId,+ setKitId,playing,pulse,currentBar,diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 9ac19352c6..30e837334d 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -116,7 +116,7 @@ grep -i "what you want to do" client/src/lib/README.md| Module | Purpose ||---|---|-| `audioContext.js` | `getAudioContext()` — the ONE app-wide lazy Web Audio `AudioContext` singleton every playback feature shares (`songPlayback`, `scorePlayback`, `metronome`, `midiPlayback`). Browsers cap live contexts and one context = one sample clock, so simultaneous features stay aligned. Constructor resolved lazily (`window` → `globalThis`) so node-env test runs import cleanly; tests inject a fake via `vi.stubGlobal('AudioContext', …)` before first call. |+| `audioContext.js` | `getAudioContext()` + `getNoiseBuffer(c)` (the app-wide 1s white-noise buffer every noise voice loops over — chiptune drums, the drum kit's snare/hats/cymbals; don't grow a third copy) — the ONE app-wide lazy Web Audio `AudioContext` singleton every playback feature shares (`songPlayback`, `scorePlayback`, `metronome`, `midiPlayback`). Browsers cap live contexts and one context = one sample clock, so simultaneous features stay aligned. Constructor resolved lazily (`window` → `globalThis`) so node-env test runs import cleanly; tests inject a fake via `vi.stubGlobal('AudioContext', …)` before first call. || `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. || `chordShapes.js` | Chord-name → per-instrument voicing derivation for the SongBook viewer's instrument-view toggle (#2656). `getChordVoicing(name, instrument)` → guitar `{ frets: [6 × (-1/0/n)], baseFret, bass }`, ukulele (4-string GCEA, exact lowest-position search), or piano `{ notes: ['A','C','E'], bass }` with letter-accurate degree spelling (the 3rd of E is G#, never Ab); guitar shapes come from a curated first-position table + movable E-/A-form barre templates offset by `baseFret` (aug/dim7 exploit shape symmetry). Slash chords voice the base chord and carry `bass` separately. `parseChordName(name)`, `splitJoinedChords('Am-Am7')`, `toVoicingInstrument(songInstrument)`, `VOICING_INSTRUMENTS`. Reuses `tabNotation.js`'s `CHORD_TOKEN_RE`/`NOTE_TO_PC`/`spellPitchClass` (exported from there for this module) instead of duplicating the tables. Unknown/unparseable chords → null, never throws. || `canvasRoll.js` | Shared canvas helpers for the two piano-roll renderers (`<PianoRoll>` falling-note + `<MidiPianoRoll>` DAW-style, #2477). `layerColor(index)` — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; `roundRect(ctx, x, y, w, h, r)` — rounded-rect path with `ctx.roundRect` feature-detect and arcTo fallback; `rollPalette()` — resolves the theme-following `{ bg, accent, accentRgb }` from `--port-accent` via `getComputedStyle` (canvas can't read CSS vars); `ROLL_BG` — the shared near-black bg literal. Pure canvas math/palette, no React. |@@ -126,8 +126,9 @@ grep -i "what you want to do" client/src/lib/README.md| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). || `editorialChecks.js` | Pure helpers for the Editorial Checks page (`/pipeline/editorial-checks`, #1285): `groupChecksByScope(checks)` buckets catalog rows into ordered Noun/Scene/Issue/Series sections; `groupFindingsByCheck(comments, rowsById)` groups check-sourced review comments per check with open/total + severity counts; `openFindingsTotal(groups)` sums open findings; `findingManuscriptLink(seriesId, comment)` builds the `?comment=` deep-link into the manuscript editor; the triage filter/sort helpers (#1600) `deriveFindingFacets(groups)` (enumerate present severities/statuses/scopes/checks/issues), `applyFindingsView(groups, filters, sort)` (filter + recount + sort findings and groups), `normalizeFindingSort`, `findingIssueKey`, and the `FINDING_SORT_OPTIONS` table; the per-check maturity/quality helpers (#1629) `checkDismissalRate(group)` and `checkMaturity(group)` (→ `{ findings, dismissalRate, falsePositiveRate, level }`, `level` ∈ new/unproven/noisy/reliable) plus the `CHECK_MATURITY_MIN_SAMPLE`/`CHECK_NOISY_DISMISSAL_RATE` thresholds; plus `scopeLabel` and the `CHECK_SCOPE_ORDER`/`CHECK_SCOPE_LABELS` tables. No React/window — the page and its tests share them. || `editorialHealth.js` | Pure presentation helpers for the editorial health panel (`/pipeline/editorial-checks`, #1316): `scoreBand(score)` bands a 0–100 health score into a label + Tailwind tone; `deltaDisplay(delta)` formats the revision-to-revision score change (arrow + tone); `sparklineGeometry(points, box)` projects the trend's score points into SVG polyline coords; `orderedCategories(openByCategory)` sorts the per-category open-finding breakdown; `orderedChecks(openByCheck, labelFor)` sorts the per-check breakdown resolving each id to its catalog label (#1597); `checkCountSeries(points, checkId)` extracts one check's count series across the trend points; `countSparklineGeometry(values, box)` projects a non-negative count series into SVG polyline coords normalized to its own max (per-check finding-count sparkline); `diffCountMaps(current, previous)` lists the buckets whose open-finding count changed between two snapshots (#1630); `snapshotDiff(point, previous)` builds a trend snapshot's drill-down (its own breakdown + per-severity/category/check diff vs the prior revision, null-aware for pre-#1597 per-check telemetry, #1630); plus the `SEVERITY_ORDER`/`SEVERITY_LABELS` and `READINESS_GATE_LABELS`/`READINESS_GATE_ORDER` tables. No React/window — the panel and its tests share them. |+| `drumKits.js` | The three selectable synth kits for the SongBook drum play-along — `DRUM_KIT_LIST` (the one ordered source of truth, first entry = default; the picker renders it directly) plus the derived `DRUM_KITS` / `DRUM_KIT_IDS` / `DEFAULT_DRUM_KIT` (`909` punchy, `808` deep-sub, `acoustic`), `resolveDrumKit(id)` (unknown/stale id → the default, never silence), `kitVoiceLayers(kit, sound)` (unmapped piece → the snare, never silence) and the kit-independent `CLICK_VOICE`. Pure DATA: each voice is a list of LAYERS — `tone` (`wave, from, to, pitchDecay, drive`), `noise` (`filter`), or `metal` (N square `partials` summed into one filter+envelope) — that `drumPlayback.js` realizes in Web Audio. Three properties carry the kit's punch and are easy to undo by accident: `pitchDecay` is INDEPENDENT of the amplitude `decay` (a membrane snaps to its fundamental in ~30–60ms then holds while the tail runs on — coupling the two is what made the original kick sound weak), `drive` tanh-saturates a layer so a sub-50 Hz kick generates the harmonics a phone/laptop speaker can actually reproduce, and a `metal` layer's high-pass cutoffs are far LOWER (and gains far higher) than the noise voices beside them because a square's harmonics fall off 6 dB/octave — see the calibration warning in the file before "harmonizing" those numbers. || `drumNotation.js` | Parser for the PortOS drum-kit notation (#3115) — a dependency-free GRID DSL (`HH: x x x x`) for the SongBook `drum` content format, drawn by `<DrumSheetView>` (hand-rolled SVG, no engraving lib). `parseDrumChart(text)` → `{ time, tempo, subdivision, stepsPerBar, bars:[{index,label,repeat,repeatPass,rows:[{piece,cells}]}], pieces, errors }` — `key: value` headers (`time`/`tempo`/`subdivision`/`kit` row-order override), blank-line-separated bar blocks with a `# label x2` repeat suffix expanded into real bars, nine kit pieces (`CR RD HH T1 T2 S FT K HF`, long aliases accepted), six cell glyphs (`-` rest, `x` normal, `X` accent, `o` open, `g` ghost, `f` flam) with spacing optional. Forgiving: short rows pad with rests, over-long rows truncate, unknown pieces/cells collect into `errors` — never throws. Plus `KIT_PIECES` (label / GM `midi` / synth `sound` / `glyph`), `kitPiece(id)`, `CELL_GLYPHS` (per-glyph velocity + flags), `isDrumNotation(text)` (import-page format sniff, runs BEFORE `tabNotation.detectFormat`), `drumChartHasMusic(text)` and its already-parsed twin `chartHasMusic(chart)`. Also the plain-language explainers the sheet's tap-a-note readout and Legend panel read — `describeDrumCell(pieceId, cell)` → `{ pieceLabel, char, articulation, detail, technique, velocityPercent, rest }` (piece-aware: `o` is "Open" on a hi-hat/cymbal but a normal hit on a drum; a null/unknown cell describes as a rest, an unknown piece returns null), `describeDrumPosition(bar, step, subdivision)` → `bar 6, count “2 e”` (count-along syllables, exact `+n/N` fallback for an unconventional subdivision), `drumGlyphLegend(pieceIds)` (all six cell characters, with the `o` row resolved for the pieces a chart uses — a fixed row would tell a crash-only chart to work the hi-hat pedal; a mixed kit gets every applicable reading) and each `KIT_PIECES` row's `technique` (how that piece is struck). Only the hi-hat voice sustains an `o` in playback, so the `open` wording follows the piece's `sound`, not its glyph shape. NOT the lead-sheet parser (`scoreNotation.js`). |-| `drumPlayback.js` | Synthesized drum-kit play-along for the SongBook `drum` format (#3115) — the third consumer of `lookaheadTransport.js` alongside `scorePlayback`/`midiPlayback`. `buildDrumSchedule(chart, { bpm, loop, countInBars })` is the PURE chart→`[{ bar, step, piece, sound, velocity, startSec, durSec, countIn }]` mapping (one notated beat = `60/bpm`, one grid step = beat/`subdivision`; per-glyph velocity; a looped bar range is sliced and rebased while keeping the CHART's bar numbers for the playhead) — unit-tested with no Web Audio; `resolveLoopRange(barCount, loop)` clamps/normalizes a 1-based inclusive bar range; the count-in is scheduled as real `countIn: true` events on the same clock so there is no second timer. `createDrumPlayer(chart, { bpm, countInBars, loopBars, clickEnabled, onStep, onEnded })` sounds it on the shared `AudioContext` from a SYNTHESIZED kit (no shipped samples — bandpassed noise burst for snare/hats/cymbals, pitch-dropping sine for kick/toms, open-hat tail, flam grace note) with an optional layered metronome click, loops the range scheduler-exactly (count-in only on the first pass), and reports `onStep({ bar, step, countIn })` for the `<DrumSheetView>` playhead. Pure (no React) — `SongBookViewer` owns the transport UI. |+| `drumPlayback.js` | Synthesized drum-kit play-along for the SongBook `drum` format (#3115) — the third consumer of `lookaheadTransport.js` alongside `scorePlayback`/`midiPlayback`. `buildDrumSchedule(chart, { bpm, loop, countInBars })` is the PURE chart→`[{ bar, step, piece, sound, velocity, startSec, durSec, countIn }]` mapping (one notated beat = `60/bpm`, one grid step = beat/`subdivision`; per-glyph velocity; a looped bar range is sliced and rebased while keeping the CHART's bar numbers for the playhead) — unit-tested with no Web Audio; `resolveLoopRange(barCount, loop)` clamps/normalizes a 1-based inclusive bar range; the count-in is scheduled as real `countIn: true` events on the same clock so there is no second timer. `createDrumPlayer(chart, { bpm, countInBars, loopBars, clickEnabled, kit, onStep, onEnded })` sounds it on the shared `AudioContext` from a SYNTHESIZED kit (no shipped samples — recipes in `drumKits.js`, realized here as per-layer oscillator/noise + optional tanh drive + optional filter into a soft-clipped master bus; open-hat tail, flam grace note) with an optional layered metronome click, loops the range scheduler-exactly (count-in only on the first pass), and reports `onStep({ bar, step, countIn })` for the `<DrumSheetView>` playhead. `setKit(id)` applies LIVE (it touches no timing, unlike `setBpm`/`setLoop`/`setCountIn`, which only rebuild while idle). Pure (no React) — `SongBookViewer` owns the transport UI. || `lookaheadTransport.js` | Shared lookahead-transport state machine for the synth players (#2493) — `createLookaheadTransport({ getTotalSec, scheduleWindow, prepare?, seekCursors?, onStop?, onEnded?, onTeardown? })` owns the Web Audio clock + live-node lifecycle (playing / interval / startTime / offsetSec / nodes / playToken, the suspended-context resume with the teardown-race guard, `track()` node pruning, and the play / pause / stop / seek / position transitions); each player supplies only the scheduling + notify callbacks and stays a thin scheduler over it, so a fix to the token-guard race or teardown lands in one place. Also the single source of the `SYNTH_TIMING` lookahead constants (`LEAD`/`LOOKAHEAD_MS`/`SCHEDULE_AHEAD`) `scorePlayback`/`midiPlayback` share. No React, no score/MIDI concepts — imports only the shared `AudioContext`. || `lossSparkline.js` | `lossSparklineGeometry(series, box)` — projects an unbounded training-loss series (`{step,loss}[]`) into SVG polyline coords, normalized to its own min/max (unlike `editorialHealth.sparklineGeometry`'s fixed 0–100 axis). Returns `{ points, coords, last, min, max }`. Drives the Render Queue's training-row loss curve (#1408). No React. || `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. |diff --git a/client/src/lib/audioContext.js b/client/src/lib/audioContext.jsindex b155c1fd22..f0032c0632 100644--- a/client/src/lib/audioContext.js+++ b/client/src/lib/audioContext.js@@ -29,3 +29,21 @@ export function getAudioContext() {}return sharedCtx;}++// One second of white noise, shared by every synth that needs a noise source+// (chiptune drums, the drum-kit snare/hats/cymbals). It lives beside the shared+// context for the same reason the context does: each copy is a megabyte of+// Float32 that every noise voice can read from instead of re-generating.+// Re-generated only if the sample rate changes — which for the shared context+// means never, but a per-mount context (MorseTrainer) may differ.+let noiseBuffer = null;++/** The shared white-noise buffer for `c`. Loop an AudioBufferSourceNode over it. */+export function getNoiseBuffer(c) {+ if (!noiseBuffer || noiseBuffer.sampleRate !== c.sampleRate) {+ noiseBuffer = c.createBuffer(1, c.sampleRate, c.sampleRate);+ const data = noiseBuffer.getChannelData(0);+ for (let i = 0; i < data.length; i += 1) data[i] = Math.random() * 2 - 1;+ }+ return noiseBuffer;+}diff --git a/client/src/lib/chiptunePlayback.js b/client/src/lib/chiptunePlayback.jsindex 3b1f225f65..8da568d8e3 100644--- a/client/src/lib/chiptunePlayback.js+++ b/client/src/lib/chiptunePlayback.js@@ -11,7 +11,7 @@// by re-basing its cursor each time it exhausts the event list, so the loop// boundary is sample-scheduler-exact rather than "restart on a timer".-import { getAudioContext as ctx } from './audioContext.js';+import { getAudioContext as ctx, getNoiseBuffer } from './audioContext.js';import { createLookaheadTransport, SYNTH_TIMING } from './lookaheadTransport.js';import { midiToFreq, makeSafeCall } from './scorePlayback.js';@@ -97,17 +97,8 @@ const pulseWave = (c, duty) => {return c.createPeriodicWave(real, imag, { disableNormalization: false });};-// Shared white-noise buffer (1s, reused by every noise voice via offset 0 —-// the LFSR aesthetic matters less in preview than in the deterministic render).-let noiseBuffer = null;-const getNoiseBuffer = (c) => {- if (!noiseBuffer || noiseBuffer.sampleRate !== c.sampleRate) {- noiseBuffer = c.createBuffer(1, c.sampleRate, c.sampleRate);- const data = noiseBuffer.getChannelData(0);- for (let i = 0; i < data.length; i += 1) data[i] = Math.random() * 2 - 1;- }- return noiseBuffer;-};+// Noise voices read the app-wide buffer from audioContext.js via offset 0 — the+// LFSR aesthetic matters less in preview than in the deterministic render.const NOISE_VOICES = {kick: { decaySec: 0.11 },diff --git a/client/src/lib/drumKits.js b/client/src/lib/drumKits.jsnew file mode 100644index 0000000000..17b8d91d62--- /dev/null+++ b/client/src/lib/drumKits.js@@ -0,0 +1,211 @@+// Synthesized drum-kit voice recipes for the SongBook play-along (#3115).+//+// PortOS ships no drum samples (repo size + sample licensing), so the play-along+// kit is synthesized. The original recipe was a generic "noise burst + sine+// sweep" click-with-groove, and its kick read as weak: the pitch sweep ran across+// the WHOLE 0.22s amplitude decay, so the tone spent most of the note above+// 100 Hz and then vanished before any body developed. Two fixes carry this file:+//+// 1. THE PITCH ENVELOPE IS DECOUPLED FROM THE AMPLITUDE ENVELOPE (`pitchDecay`).+// A drum-machine kick snaps from its attack pitch down to the fundamental in+// ~30–60ms and then HOLDS there while the amplitude decays for half a second+// or more. That separation is what the ear reads as "punch, then weight".+// 2. VOICES ARE SATURATED (`drive`). A 48 Hz sine is nearly inaudible on a phone+// or laptop speaker — there is no driver for it. Running the tone through a+// tanh shaper generates the harmonic series (96/144/192 Hz…) that small+// speakers CAN reproduce, so the ear reconstructs the missing fundamental.+// This is the same trick every drum machine and bass amp uses.+//+// A voice is a list of LAYERS mixed together, each an independent little synth:+//+// { kind: 'tone', wave, from, to?, pitchDecay?, decay, openDecay?, gain,+// drive?, filter? }+// { kind: 'metal', partials, decay, openDecay?, gain, filter }+// { kind: 'noise', filter, decay, openDecay?, gain }+//+// - `from`/`to` are the pitch envelope endpoints; omit `to` for a static pitch.+// - `pitchDecay` is how long the sweep takes — INDEPENDENT of `decay`, and+// required whenever `to` is set (see the note at the top).+// - `openDecay` replaces `decay` for an `o` (open hi-hat) cell.+// - `filter` is `{ type, freq, q }` applied after the source(s).+// - `drive` (>0) is the tanh saturation amount, normalized so the layer keeps its+// peak level and only gains harmonics.+// - a `metal` layer is one voice built from N square oscillators summed into a+// single filter + envelope; `gain` is the level of the WHOLE cluster (the+// realization divides it across the partials), so it is directly comparable to+// a noise layer's `gain`.+//+// `drumPlayback.js` owns the Web Audio realization of these recipes; this module+// is pure data plus the small helpers that build repetitive layer sets, so a kit+// can be auditioned/tweaked without touching the scheduler.++// The 808's hi-hat/cymbal source is a cluster of square oscillators at+// deliberately inharmonic ratios, run through a high-pass — that inharmonicity is+// what makes it read as "metal" rather than "hiss". These are the classic six.+const METAL_PARTIALS = [205.3, 304.4, 369.6, 522.7, 540, 800];++// CALIBRATION WARNING for every `metal` layer below. A square's harmonics fall+// off 6 dB/octave, so almost nothing of a 205 Hz partial survives a hi-hat-height+// high-pass: measured against the 909's noise hat, this cluster at a 7.8 kHz+// cutoff and a noise-hat-like gain came out 19 dB quieter — inaudible under the+// kit. Metal cutoffs are therefore much LOWER, and their gains much HIGHER, than+// the noise voices they sit beside. They are not typos and must not be+// "harmonized" with the 909's numbers.+const metal = ({ freq, decay, openDecay, gain, partials = METAL_PARTIALS }) => ({+ kind: 'metal', partials, filter: { type: 'highpass', freq, q: 0.7 }, decay, openDecay, gain,+});++// A membrane (kick/tom) is a pitch-dropping sine; the arguments are the knobs+// that actually differ between one and the next.+const membrane = ({ from, to, pitchDecay, decay, gain, drive = 0 }) => ({+ kind: 'tone', wave: 'sine', from, to, pitchDecay, decay, gain, drive,+});++// The beater/stick transient that sits on top of a membrane hit — a very short+// high-passed noise tick. This is most of what makes a kick audible on a laptop+// speaker before the body arrives.+const transient = ({ freq, decay, gain }) => ({+ kind: 'noise', filter: { type: 'highpass', freq, q: 0.4 }, decay, gain,+});++/**+ * TR-909 — the punchy one, and the default.+ *+ * Chosen as the default because it is the most legible kit to practise against:+ * a short attack-forward kick, a bright snare crack, and tight hats all stay+ * distinct at speed, where the 808's long tails smear together under 16ths.+ */+const KIT_909 = {+ id: '909',+ label: 'TR-909',+ description: 'Punchy attack-forward kick, bright snare crack, tight hats.',+ voices: {+ kick: [+ membrane({ from: 200, to: 48, pitchDecay: 0.03, decay: 0.42, gain: 1.55, drive: 7 }),+ transient({ freq: 1800, decay: 0.014, gain: 0.5 }),+ ],+ snare: [+ { kind: 'noise', filter: { type: 'highpass', freq: 1400, q: 0.7 }, decay: 0.17, gain: 0.85 },+ { kind: 'tone', wave: 'triangle', from: 330, to: 300, pitchDecay: 0.05, decay: 0.085, gain: 0.4 },+ { kind: 'tone', wave: 'triangle', from: 185, to: 172, pitchDecay: 0.06, decay: 0.11, gain: 0.5, drive: 2.5 },+ ],+ tom1: [membrane({ from: 380, to: 165, pitchDecay: 0.07, decay: 0.38, gain: 0.95, drive: 3 })],+ tom2: [membrane({ from: 285, to: 122, pitchDecay: 0.08, decay: 0.45, gain: 0.95, drive: 3 })],+ floor: [membrane({ from: 195, to: 76, pitchDecay: 0.1, decay: 0.6, gain: 1, drive: 4 })],+ hihat: [+ { kind: 'noise', filter: { type: 'highpass', freq: 8200, q: 0.8 }, decay: 0.045, openDecay: 0.32, gain: 0.5 },+ ],+ hihatFoot: [+ { kind: 'noise', filter: { type: 'highpass', freq: 6500, q: 0.8 }, decay: 0.03, gain: 0.34 },+ ],+ ride: [+ { kind: 'noise', filter: { type: 'bandpass', freq: 5600, q: 0.7 }, decay: 0.8, gain: 0.34 },+ // The bell "ping" on top of the wash — same square-harmonic rolloff caveat+ // as `metal`, hence the low cutoff for so modest a gain.+ { kind: 'tone', wave: 'square', from: 1180, filter: { type: 'highpass', freq: 2500, q: 0.7 }, decay: 0.5, gain: 0.2 },+ ],+ crash: [+ { kind: 'noise', filter: { type: 'highpass', freq: 3200, q: 0.4 }, decay: 1.3, gain: 0.5 },+ ],+ },+};++/**+ * TR-808 — the deep one. Long sub-heavy kick, thin snare, metallic square-cluster+ * hats. Sounds enormous on headphones and at slow practice tempos; the kick tail+ * deliberately outruns a 16th at speed, which is the point of the machine.+ */+const KIT_808 = {+ id: '808',+ label: 'TR-808',+ description: 'Deep sub kick with a long tail, thin snare, metallic hats.',+ voices: {+ kick: [+ membrane({ from: 110, to: 45, pitchDecay: 0.055, decay: 0.9, gain: 1.7, drive: 4 }),+ transient({ freq: 1200, decay: 0.01, gain: 0.28 }),+ ],+ snare: [+ { kind: 'noise', filter: { type: 'bandpass', freq: 1750, q: 0.5 }, decay: 0.12, gain: 0.72 },+ { kind: 'tone', wave: 'triangle', from: 330, to: 315, pitchDecay: 0.04, decay: 0.075, gain: 0.34 },+ { kind: 'tone', wave: 'triangle', from: 178, to: 168, pitchDecay: 0.05, decay: 0.1, gain: 0.44 },+ ],+ tom1: [membrane({ from: 340, to: 150, pitchDecay: 0.09, decay: 0.55, gain: 0.9, drive: 2 })],+ tom2: [membrane({ from: 250, to: 110, pitchDecay: 0.1, decay: 0.65, gain: 0.9, drive: 2 })],+ floor: [membrane({ from: 165, to: 66, pitchDecay: 0.12, decay: 0.85, gain: 0.95, drive: 3 })],+ hihat: [metal({ freq: 4200, decay: 0.04, openDecay: 0.42, gain: 2.4 })],+ hihatFoot: [metal({ freq: 3800, decay: 0.028, gain: 1.7 })],+ ride: [+ metal({ freq: 3200, decay: 0.7, gain: 1.3 }),+ { kind: 'noise', filter: { type: 'bandpass', freq: 5200, q: 0.9 }, decay: 0.7, gain: 0.16 },+ ],+ crash: [+ metal({ freq: 2400, decay: 1.2, gain: 1.3 }),+ { kind: 'noise', filter: { type: 'highpass', freq: 3000, q: 0.4 }, decay: 1.4, gain: 0.34 },+ ],+ },+};++/**+ * Acoustic — the closest of the three to a real kit, for charts that read as+ * band parts rather than machine patterns. Same envelope discipline as the+ * others (this is NOT the old weak recipe), just tuned rounder and less driven.+ */+const KIT_ACOUSTIC = {+ id: 'acoustic',+ label: 'Acoustic',+ description: 'Rounder, less saturated — a studio kit rather than a machine.',+ voices: {+ kick: [+ membrane({ from: 165, to: 52, pitchDecay: 0.045, decay: 0.4, gain: 1.35, drive: 3 }),+ transient({ freq: 2400, decay: 0.02, gain: 0.4 }),+ ],+ snare: [+ { kind: 'noise', filter: { type: 'highpass', freq: 1100, q: 0.6 }, decay: 0.2, gain: 0.8 },+ { kind: 'tone', wave: 'triangle', from: 340, to: 300, pitchDecay: 0.05, decay: 0.1, gain: 0.3 },+ { kind: 'tone', wave: 'sine', from: 200, to: 178, pitchDecay: 0.06, decay: 0.13, gain: 0.42 },+ ],+ tom1: [membrane({ from: 300, to: 160, pitchDecay: 0.09, decay: 0.42, gain: 0.9 })],+ tom2: [membrane({ from: 235, to: 120, pitchDecay: 0.1, decay: 0.5, gain: 0.9 })],+ floor: [membrane({ from: 160, to: 82, pitchDecay: 0.12, decay: 0.68, gain: 0.95, drive: 2 })],+ hihat: [+ { kind: 'noise', filter: { type: 'highpass', freq: 7200, q: 0.9 }, decay: 0.05, openDecay: 0.3, gain: 0.46 },+ ],+ hihatFoot: [+ { kind: 'noise', filter: { type: 'highpass', freq: 5800, q: 0.9 }, decay: 0.035, gain: 0.32 },+ ],+ ride: [+ { kind: 'noise', filter: { type: 'bandpass', freq: 6000, q: 0.8 }, decay: 0.75, gain: 0.32 },+ ],+ crash: [+ { kind: 'noise', filter: { type: 'highpass', freq: 2800, q: 0.4 }, decay: 1.4, gain: 0.46 },+ ],+ },+};++// One ordered source of truth — the picker renders this order, and the FIRST kit+// is the default. Everything else below is derived, so adding a kit is one edit.+export const DRUM_KIT_LIST = [KIT_909, KIT_808, KIT_ACOUSTIC];+export const DRUM_KITS = Object.fromEntries(DRUM_KIT_LIST.map((kit) => [kit.id, kit]));+export const DRUM_KIT_IDS = DRUM_KIT_LIST.map((kit) => kit.id);+export const DEFAULT_DRUM_KIT = DRUM_KIT_LIST[0].id;++/**+ * A kit id → its recipe, falling back to the default. An unknown id (a stale+ * localStorage value from a kit that has since been renamed) must degrade to a+ * kit that sounds, never to silence.+ */+export const resolveDrumKit = (id) => DRUM_KITS[id] || DRUM_KITS[DEFAULT_DRUM_KIT];++/**+ * The layer list for one kit piece — `sound` is the `KIT_PIECES` synth name+ * (`kick`, `snare`, `hihat`, …). Falls back to the kit's snare so an unmapped+ * piece is still audible at the right time rather than dropping out.+ */+export const kitVoiceLayers = (kit, sound) => kit?.voices?.[sound] || kit?.voices?.snare || [];++// The metronome click is NOT part of the kit: it's a reference pulse layered over+// whatever kit is selected, so it must stay identical (and cut through) across+// all three. A short, bright, barely-moving blip.+export const CLICK_VOICE = [+ { kind: 'tone', wave: 'square', from: 1600, to: 1560, pitchDecay: 0.02, decay: 0.045, gain: 0.6 },+];diff --git a/client/src/lib/drumKits.test.js b/client/src/lib/drumKits.test.jsnew file mode 100644index 0000000000..b6f4dd16f8--- /dev/null+++ b/client/src/lib/drumKits.test.js@@ -0,0 +1,121 @@+import { describe, it, expect } from 'vitest';+import { KIT_PIECES } from './drumNotation.js';+import {+ CLICK_VOICE,+ DEFAULT_DRUM_KIT,+ DRUM_KITS,+ DRUM_KIT_IDS,+ DRUM_KIT_LIST,+ kitVoiceLayers,+ resolveDrumKit,+} from './drumKits.js';++// The kits are pure data with no runtime validation — a typo'd envelope number+// or a piece a kit forgot to voice would only show up as a drum that plays+// silence (or a click) somewhere in a chart. These are PROPERTY tests over every+// kit × every layer rather than a spot-check of one recipe, so a fourth kit or a+// tenth kit piece is covered the moment it's added.++const ALL_LAYERS = Object.values(DRUM_KITS).flatMap((kit) => Object+ .entries(kit.voices)+ .flatMap(([sound, layers]) => layers.map((layer, i) => ({ kit: kit.id, sound, i, layer }))));++describe('drumKits', () => {+ it('derives every lookup from the one ordered kit list', () => {+ expect(DRUM_KIT_LIST.length).toBeGreaterThan(1);+ expect(DRUM_KIT_IDS).toEqual(DRUM_KIT_LIST.map((k) => k.id));+ expect(DEFAULT_DRUM_KIT).toBe(DRUM_KIT_LIST[0].id);+ for (const id of DRUM_KIT_IDS) expect(DRUM_KITS[id]?.id).toBe(id);+ // The picker renders label + tooltip straight off the list.+ expect(DRUM_KIT_LIST.every((k) => k.label && k.description)).toBe(true);+ });++ it('voices every kit piece the notation can name, in every kit', () => {+ // A missing voice would fall back to the snare — the hit lands at the right+ // time but on the wrong drum, which reads as a chart bug, not a kit gap.+ const sounds = [...new Set(KIT_PIECES.map((p) => p.sound))];+ for (const id of DRUM_KIT_IDS) {+ for (const sound of sounds) {+ expect(DRUM_KITS[id].voices[sound]?.length, `${id}/${sound}`).toBeGreaterThan(0);+ }+ }+ });++ it('gives every layer a sounding envelope', () => {+ for (const { kit, sound, i, layer } of ALL_LAYERS) {+ const where = `${kit}/${sound}[${i}]`;+ expect(['tone', 'noise', 'metal'], where).toContain(layer.kind);+ if (layer.kind === 'metal') {+ expect(layer.partials.length, where).toBeGreaterThan(1);+ expect(layer.partials.every((hz) => hz > 0), where).toBe(true);+ expect(layer.filter, where).toBeTruthy();+ }+ expect(layer.decay, where).toBeGreaterThan(0);+ expect(layer.gain, where).toBeGreaterThan(0);+ // Web Audio's exponential ramps cannot touch zero, so no envelope endpoint+ // or filter frequency may be 0 — that throws at schedule time.+ if (layer.filter) expect(layer.filter.freq, where).toBeGreaterThan(0);+ if (layer.openDecay != null) expect(layer.openDecay, where).toBeGreaterThan(layer.decay);+ }+ });++ it('sweeps every pitched layer downward, and faster than its amplitude tail', () => {+ // The punch rule from the module header: a membrane snaps to its fundamental+ // and HOLDS while the amplitude decays. A layer whose pitchDecay equals its+ // amp decay is the weak-kick recipe this replaced.+ for (const { kit, sound, i, layer } of ALL_LAYERS) {+ if (layer.kind !== 'tone' || !(layer.to > 0)) continue;+ const where = `${kit}/${sound}[${i}]`;+ expect(layer.from, where).toBeGreaterThan(layer.to);+ expect(layer.pitchDecay, where).toBeGreaterThan(0);+ expect(layer.pitchDecay, where).toBeLessThan(layer.decay);+ }+ });++ it('drives the kick of every kit so it reads on a small speaker', () => {+ for (const id of DRUM_KIT_IDS) {+ const kick = DRUM_KITS[id].voices.kick;+ const body = kick.find((l) => l.kind === 'tone');+ expect(body?.drive, id).toBeGreaterThan(0);+ // Deep enough to be a kick, and its tail long enough to have weight — the+ // original 0.22s sweep-the-whole-decay recipe had neither.+ expect(body.to, id).toBeLessThan(60);+ expect(body.decay, id).toBeGreaterThan(0.35);+ }+ });++ it('keeps every high-passed square layer within reach of its own harmonics', () => {+ // A square's harmonic amplitudes fall off as 1/h, so a high-pass far above+ // the fundamental leaves almost nothing: the 808's metal hat first landed at+ // a 7.8 kHz cutoff over a 205 Hz partial (a ratio of 38) and measured 19 dB+ // below the 909's noise hat — audibly missing. 25 is comfortably past every+ // calibrated value here and comfortably short of that bug.+ for (const { kit, sound, i, layer } of ALL_LAYERS) {+ if (layer.filter?.type !== 'highpass') continue;+ const squares = layer.kind === 'metal' ? layer.partials+ : (layer.wave === 'square' ? [layer.from] : []);+ for (const hz of squares) {+ expect(layer.filter.freq / hz, `${kit}/${sound}[${i}] @${hz}Hz`).toBeLessThan(25);+ }+ }+ });++ it('resolveDrumKit falls back to the default for a missing or unknown id', () => {+ expect(resolveDrumKit(DEFAULT_DRUM_KIT).id).toBe(DEFAULT_DRUM_KIT);+ expect(resolveDrumKit('808').id).toBe('808');+ expect(resolveDrumKit(undefined).id).toBe(DEFAULT_DRUM_KIT);+ expect(resolveDrumKit('a-kit-that-was-renamed').id).toBe(DEFAULT_DRUM_KIT);+ });++ it('kitVoiceLayers falls back to the snare rather than to silence', () => {+ const kit = resolveDrumKit('909');+ expect(kitVoiceLayers(kit, 'kick')).toBe(kit.voices.kick);+ expect(kitVoiceLayers(kit, 'tambourine')).toBe(kit.voices.snare);+ expect(kitVoiceLayers(null, 'kick')).toEqual([]);+ });++ it('keeps the metronome click out of the kits so it sounds the same in all three', () => {+ expect(CLICK_VOICE.length).toBeGreaterThan(0);+ for (const id of DRUM_KIT_IDS) expect(DRUM_KITS[id].voices.click).toBeUndefined();+ });+});diff --git a/client/src/lib/drumPlayback.js b/client/src/lib/drumPlayback.jsindex 3c2acd658b..4fe54e9399 100644--- a/client/src/lib/drumPlayback.js+++ b/client/src/lib/drumPlayback.js@@ -5,19 +5,20 @@// the clock, node lifecycle and teardown semantics are all the shared ones, so// this module only owns the schedule math and the kit voices.//-// The kit is SYNTHESIZED — noise burst + bandpass for snare/hats/cymbals, a-// pitch-dropping sine for kick/toms. No sampled kit ships with PortOS (repo size-// + sample licensing), and the synth reads well enough as a practice click-with--// groove, which is what the play-along is for.+// The kit is SYNTHESIZED — no sampled kit ships with PortOS (repo size + sample+// licensing). The voice recipes live in `drumKits.js` (TR-909 / TR-808 /+// Acoustic, selectable); this module owns the schedule math and the Web Audio+// realization of whichever kit is selected.//// `buildDrumSchedule` is PURE (no Web Audio) so the timing math — bpm, time// signature, subdivision, count-in, loop expansion, per-glyph velocity — is// unit-testable in a node env, mirroring `buildSchedule` in scorePlayback.js.-import { getAudioContext as ctx } from './audioContext.js';+import { getAudioContext as ctx, getNoiseBuffer } from './audioContext.js';import { createLookaheadTransport, SYNTH_TIMING } from './lookaheadTransport.js';import { makeSafeCall } from './scorePlayback.js';import { kitPiece, DEFAULT_DRUM_TEMPO } from './drumNotation.js';+import { CLICK_VOICE, kitVoiceLayers, resolveDrumKit } from './drumKits.js';const { SCHEDULE_AHEAD } = SYNTH_TIMING;const safeCall = makeSafeCall('drum playback');@@ -188,91 +189,158 @@ export const resolvePlayhead = (schedule, posSec) => {// --- Kit voices --------------------------------------------------------------const VOICE_PEAK = 0.5; // per-hit gain ceiling before the per-cell velocity scale--// Shared white-noise buffer (1s, re-generated only if the sample rate changes) —-// same idiom as chiptunePlayback.js's noise voice.-let noiseBuffer = null;-const getNoiseBuffer = (c) => {- if (!noiseBuffer || noiseBuffer.sampleRate !== c.sampleRate) {- noiseBuffer = c.createBuffer(1, c.sampleRate, c.sampleRate);- const data = noiseBuffer.getChannelData(0);- for (let i = 0; i < data.length; i += 1) data[i] = Math.random() * 2 - 1;- }- return noiseBuffer;-};--// One voice recipe per kit sound. `tone` sounds a pitch-dropping sine (membranes);-// `noise` sounds a bandpassed noise burst (metal + snare wires). `decay` is the-// exponential tail in seconds; `open` extends it for an open hi-hat.-const VOICES = {- kick: { type: 'tone', from: 150, to: 45, decay: 0.22, gain: 1 },- tom1: { type: 'tone', from: 260, to: 150, decay: 0.24, gain: 0.85 },- tom2: { type: 'tone', from: 200, to: 115, decay: 0.28, gain: 0.85 },- floor: { type: 'tone', from: 140, to: 80, decay: 0.34, gain: 0.85 },- // A snare is a membrane plus wires: a short tone under a wide noise burst.- snare: { type: 'noise', freq: 1900, q: 0.7, decay: 0.16, gain: 0.9, body: { from: 210, to: 170, decay: 0.09, gain: 0.5 } },- hihat: { type: 'noise', freq: 8500, q: 1.6, decay: 0.045, openDecay: 0.28, gain: 0.5 },- hihatFoot: { type: 'noise', freq: 7000, q: 1.4, decay: 0.035, gain: 0.35 },- ride: { type: 'noise', freq: 6200, q: 0.9, decay: 0.5, gain: 0.4 },- crash: { type: 'noise', freq: 4200, q: 0.4, decay: 1.1, gain: 0.5 },- // Metronome click layered over the kit (and the count-in voice) — a short- // pitched blip, brighter on the accent, so it cuts through the noise voices.- click: { type: 'tone', from: 1600, to: 1550, decay: 0.05, gain: 0.7 },+// The RECIPES live in drumKits.js (three selectable kits); this section is the+// Web Audio realization of them — one node graph per layer, plus the master bus.++const VOICE_PEAK = 0.42; // per-layer gain ceiling before the per-cell velocity scale+// Headroom into the master soft-clipper: a busy bar stacks a kick, a snare, a hat+// and a click at once, so the sum is deliberately kept under unity and the+// clipper only rounds the peaks that still get through.+const MASTER_GAIN = 0.9;++const CURVE_SAMPLES = 1024;+const buildCurve = (shape) => Float32Array.from(+ { length: CURVE_SAMPLES },+ (_, i) => shape((i * 2) / (CURVE_SAMPLES - 1) - 1),+);++// MASTER soft-clipper: plain tanh, so it is unity-gain for quiet material and+// only rounds off the peaks when several loud voices land on the same downbeat.+// Cheaper and steadier than a compressor for a fixed-level drum bus. NOT the+// same curve as a drive of 1 — this one is deliberately un-normalized, and+// normalizing it would push ~2.4 dB of makeup gain into the clipper.+const CLIP_CURVE = buildCurve(Math.tanh);++// Per-LAYER saturation curve, cached per drive amount (a handful of compiled-in+// values). Normalized so the layer keeps its PEAK level and only gains harmonics+// — that harmonic series is what makes a sub-50Hz kick audible on a phone or+// laptop speaker, which has no driver for the fundamental at all (see the+// drumKits.js header).+const driveCurves = new Map();+const driveCurve = (amount) => {+ const cached = driveCurves.get(amount);+ if (cached) return cached;+ const norm = Math.tanh(amount);+ const curve = buildCurve((x) => Math.tanh(amount * x) / norm);+ driveCurves.set(amount, curve);+ return curve;};// Flam grace-note lead: the ghost hit lands this far BEFORE the main hit.const FLAM_LEAD_SEC = 0.032;+// Envelope attack. An instant jump to full scale pops on some speakers, so every+// voice ramps in over this — short enough to stay percussive.+const ATTACK_SEC = 0.0015;+// Pitch-envelope fallback for a recipe that sets `to` without a `pitchDecay`.+// Deliberately NOT the amplitude decay: coupling the two is the weak-kick recipe+// this engine replaced, and a fourth kit must not be able to resurrect it by+// omitting a field.+const PITCH_SNAP_SEC = 0.04;-// Schedule one voice node pair; returns { osc, gain } for the transport's-// teardown tracking (an AudioBufferSourceNode satisfies the same-// start/stop/onended surface an OscillatorNode does).-const scheduleVoice = (c, voice, startAt, destination, { velocity, open }) => {+/**+ * Schedule ONE layer of a voice (see the layer shape in drumKits.js); returns an+ * array of `{ osc, gain }` for the transport's teardown tracking — one per+ * source, so a `metal` cluster's partials are each stoppable (an+ * AudioBufferSourceNode satisfies the same start/stop/onended surface an+ * OscillatorNode does).+ *+ * The pitch envelope runs on `pitchDecay`, NOT on the amplitude `decay` — a+ * drum-machine membrane snaps down to its fundamental in tens of milliseconds+ * and then holds there while the amplitude tail runs on for half a second. The+ * two being the same number is exactly what made the old kick sound weak.+ */+const scheduleLayer = (c, layer, startAt, destination, { velocity, open }) => {const gain = c.createGain();- const peak = Math.max(0.0002, VOICE_PEAK * (voice.gain ?? 1) * velocity);- const decay = open && voice.openDecay ? voice.openDecay : voice.decay;- let osc;-- if (voice.type === 'noise') {- osc = c.createBufferSource();- osc.buffer = getNoiseBuffer(c);- osc.loop = true;+ const decay = Math.max(0.005, (open && layer.openDecay) || layer.decay || 0.1);+ const stopAt = startAt + ATTACK_SEC + decay + 0.02;++ // Build the source(s). A `metal` layer is N square oscillators summed into the+ // ONE filter/envelope below — a biquad is linear, so filtering the sum is+ // identical to summing filtered partials, at a third of the nodes per hit.+ const partials = layer.kind === 'metal' ? layer.partials : [null];+ const sources = partials.map((hz) => {+ if (layer.kind === 'noise') {+ const src = c.createBufferSource();+ src.buffer = getNoiseBuffer(c);+ src.loop = true;+ return src;+ }+ const osc = c.createOscillator();+ osc.type = layer.kind === 'metal' ? 'square' : (layer.wave || 'sine');+ osc.frequency.setValueAtTime(hz ?? layer.from, startAt);+ if (layer.kind !== 'metal' && layer.to > 0 && layer.to !== layer.from) {+ osc.frequency.exponentialRampToValueAtTime(+ layer.to,+ startAt + Math.max(0.004, layer.pitchDecay ?? PITCH_SNAP_SEC),+ );+ }+ return osc;+ });++ // source(s) → [drive] → [filter] → gain → bus. The shaper sits BEFORE the gain+ // so the timbre is the same at every velocity (a drive that only bit on accents+ // would make the kit change character as you play softer).+ let head = null; // the node the sources feed; null until one is created+ let tail = null; // the last node before the gain+ const append = (node) => {+ if (!head) head = node;+ else tail.connect(node);+ tail = node;+ };+ if (layer.drive > 0) {+ const shaper = c.createWaveShaper();+ shaper.curve = driveCurve(layer.drive);+ shaper.oversample = '2x';+ append(shaper);+ }+ if (layer.filter) {const filter = c.createBiquadFilter();- filter.type = 'bandpass';- filter.frequency.setValueAtTime(voice.freq, startAt);- filter.Q.value = voice.q;- osc.connect(filter).connect(gain);- } else {- osc = c.createOscillator();- osc.type = 'sine';- osc.frequency.setValueAtTime(voice.from, startAt);- osc.frequency.exponentialRampToValueAtTime(voice.to, startAt + decay);- osc.connect(gain);+ filter.type = layer.filter.type;+ filter.frequency.setValueAtTime(layer.filter.freq, startAt);+ filter.Q.value = layer.filter.q ?? 1;+ append(filter);}-- // Percussive envelope: instant attack, exponential decay to silence.- gain.gain.setValueAtTime(peak, startAt);- gain.gain.exponentialRampToValueAtTime(0.0001, startAt + decay);+ if (tail) tail.connect(gain);+ for (const src of sources) src.connect(head || gain);gain.connect(destination);- osc.start(startAt);- osc.stop(startAt + decay + 0.02);- return { osc, gain };++ // Percussive envelope: a sub-millisecond attack ramp into an exponential decay+ // to silence. A cluster's `gain` is the level of the WHOLE voice, so it splits+ // across the partials — that keeps a six-oscillator hat comparable to a+ // one-source noise hat instead of six times louder.+ const peak = Math.max(0.0002, (VOICE_PEAK * (layer.gain ?? 1) * velocity) / sources.length);+ gain.gain.setValueAtTime(0.0001, startAt);+ gain.gain.exponentialRampToValueAtTime(peak, startAt + ATTACK_SEC);+ gain.gain.exponentialRampToValueAtTime(0.0001, stopAt - 0.02);++ // One transport entry PER source, all sharing the single gain node: teardown+ // only ever touches `entry.osc`, and a cluster whose partials weren't each+ // tracked would keep ringing after stop() (up to 1.2s for the 808 crash).+ return sources.map((src) => {+ src.start(startAt);+ src.stop(stopAt);+ return { osc: src, gain };+ });};-// Sound one chart event — the main hit, plus a snare-body tone and/or a flam-// grace note when the voice/glyph calls for them. Every created node pair goes-// through `track` so the transport tears all of them down on stop.-const soundEvent = (c, ev, at, destination, track) => {- const voice = VOICES[ev.sound] || VOICES.snare;+// Sound every layer of a voice at one time, scaled by a velocity multiplier.+const soundLayers = (c, layers, at, destination, track, { velocity, open }) => {+ for (const layer of layers) {+ for (const entry of scheduleLayer(c, layer, at, destination, { velocity, open })) track(entry);+ }+};++// Sound one chart event — the hit, plus a flam grace note when the glyph calls+// for one. Every created node pair goes through `track` so the transport tears+// all of them down on stop.+const soundEvent = (c, kit, ev, at, destination, track) => {+ const layers = kitVoiceLayers(kit, ev.sound);if (ev.flam) {- track(scheduleVoice(c, voice, Math.max(at - FLAM_LEAD_SEC, 0), destination, {+ soundLayers(c, layers, Math.max(at - FLAM_LEAD_SEC, 0), destination, track, {velocity: ev.velocity * 0.45, open: ev.open,- }));- }- track(scheduleVoice(c, voice, at, destination, { velocity: ev.velocity, open: ev.open }));- if (voice.body) {- track(scheduleVoice(c, voice.body, at, destination, { velocity: ev.velocity, open: false }));+ });}+ soundLayers(c, layers, at, destination, track, { velocity: ev.velocity, open: ev.open });};// --- Player -----------------------------------------------------------------@@ -288,11 +356,13 @@ const soundEvent = (c, ev, at, destination, track) => {* bar range; when set, playback repeats that range until stopped.* @param {boolean} [options.clickEnabled] — layer a metronome click on every* notated beat, on the same clock as the kit.+ * @param {string} [options.kit] — kit id from `drumKits.js` (`909` / `808` /+ * `acoustic`); an unknown id falls back to the default rather than to silence.* @param {({bar:number|null, step:number|null, countIn:boolean})=>void} [options.onStep]* — the now-sounding grid position (null when playback ends/stops), for the* sheet playhead.* @param {()=>void} [options.onEnded] — fired once when a non-looping chart ends.- * @returns {{ play, pause, stop, isPlaying, setBpm, setLoop, setClick, schedule }}+ * @returns {{ play, pause, stop, isPlaying, setBpm, setLoop, setClick, setKit, schedule }}*/export const createDrumPlayer = (chart, options = {}) => {const { onStep, onEnded } = options;@@ -300,10 +370,14 @@ export const createDrumPlayer = (chart, options = {}) => {let loopBars = options.loopBars || null;let clickEnabled = !!options.clickEnabled;let countInBars = options.countInBars || 0;+ // The kit only affects which voices SOUND, never the schedule — so unlike the+ // timing settings it can change mid-play (the next scheduled hit picks it up).+ let kit = resolveDrumKit(options.kit);const build = () => buildDrumSchedule(chart, { bpm, loop: loopBars, countInBars });let schedule = build();let master = null;+ let masterOut = null;// Click track for the CURRENT schedule: one marker per notated beat of the// music (the count-in carries its own clicks as real events). Derived rather@@ -391,7 +465,7 @@ export const createDrumPlayer = (chart, options = {}) => {if (at >= horizon) break;hitCursor.idx += 1;if (at < now - 0.05) continue; // already past (first tick after a stall)- soundEvent(c, ev, Math.max(at, now), master, track);+ soundEvent(c, kit, ev, Math.max(at, now), master, track);}// The click layer walks its own list on the same pass geometry. Its pass ≥ 1@@ -408,9 +482,9 @@ export const createDrumPlayer = (chart, options = {}) => {if (at >= horizon) break;clickCursor.idx += 1;if (at < now - 0.05) continue;- track(scheduleVoice(c, VOICES.click, Math.max(at, now), master, {+ soundLayers(c, CLICK_VOICE, Math.max(at, now), master, track, {velocity: click.accent ? 1 : 0.55, open: false,- }));+ });}}@@ -457,9 +531,15 @@ export const createDrumPlayer = (chart, options = {}) => {clicks = clickTimes();resetCursor();const c = ctx();+ // Drum bus: every voice sums here, then through a soft-clipper so a+ // downbeat stacking kick + crash + click rounds off instead of clipping.master = c.createGain();- master.gain.value = 1;- master.connect(c.destination);+ master.gain.value = MASTER_GAIN;+ masterOut = c.createWaveShaper();+ masterOut.curve = CLIP_CURVE;+ masterOut.oversample = '2x';+ master.connect(masterOut);+ masterOut.connect(c.destination);return true;},seekCursors: (offsetSec) => {@@ -478,12 +558,14 @@ export const createDrumPlayer = (chart, options = {}) => {onStop: () => { notify(null); },onEnded: () => { safeCall(onEnded); },onTeardown: () => {- if (master) {- // Outside the request lifecycle — a disconnect on an already-torn-down- // node must not throw into the transport's teardown path.- try { master.disconnect(); } catch { /* already gone */ }- master = null;+ // Outside the request lifecycle — a disconnect on an already-torn-down+ // node must not throw into the transport's teardown path.+ for (const node of [master, masterOut]) {+ if (!node) continue;+ try { node.disconnect(); } catch { /* already gone */ }}+ master = null;+ masterOut = null;},});@@ -517,6 +599,10 @@ export const createDrumPlayer = (chart, options = {}) => {rebuildIfIdle();},setClick: (enabled) => { clickEnabled = !!enabled; },+ // Kit changes touch no timing, so — like the click toggle — they apply live:+ // whatever is already in the lookahead window finishes on the old kit and+ // everything scheduled after this lands on the new one.+ setKit: (id) => { kit = resolveDrumKit(id); },schedule: () => schedule,};};diff --git a/client/src/lib/drumPlayer.test.js b/client/src/lib/drumPlayer.test.jsindex d2793a61df..e9263d5f55 100644--- a/client/src/lib/drumPlayer.test.js+++ b/client/src/lib/drumPlayer.test.js@@ -53,27 +53,118 @@ describe('createDrumPlayer', () => {expect(player.isPlaying()).toBe(false);});- it('uses bandpassed noise for cymbals/snare and a pitched sweep for the kick', async () => {+ it('uses filtered noise for the hat and a pitched sweep for the kick', async () => {const player = createDrumPlayer(parseDrumChart('tempo: 240\nsubdivision: 1\n\nHH: x---\nK: -o--'), {});await player.play();drive(2);- // The hat is a filtered noise burst; the kick is a sine sweep (no filter).- expect(audio.filters.length).toBe(1);- expect(audio.filters[0].type).toBe('bandpass');+ // The hat is a filtered noise burst; the kick's body is a pitched oscillator.expect(audio.oscillators.some((o) => o.noise)).toBe(true);- expect(audio.oscillators.some((o) => !o.noise)).toBe(true);+ expect(audio.filters.length).toBeGreaterThan(0);+ const swept = audio.oscillators.filter((o) => !o.noise && o.frequency.values.length > 1);+ expect(swept.length).toBeGreaterThan(0);+ // Every sweep DROPS in pitch — a membrane falling to its fundamental.+ expect(swept.every((o) => o.frequency.values[1] < o.frequency.values[0])).toBe(true);+ });++ it('drops the kick pitch far faster than its amplitude decays', async () => {+ // The punch fix: the pitch envelope and the amplitude envelope are separate.+ // A kick whose sweep runs the full length of its tail is the weak-sounding+ // recipe this replaced, so the two are pinned apart here rather than left to+ // whichever numbers a kit happens to carry.+ const player = createDrumPlayer(parseDrumChart('tempo: 240\nsubdivision: 1\n\nK: o---'), {});+ await player.play();+ drive(0.2);+ const body = audio.oscillators.find((o) => !o.noise && o.frequency.values.length > 1);+ expect(body).toBeDefined();+ // stop() is scheduled at attack + decay + 0.02 — a proxy for the amp tail.+ const ampTail = body.stopped - body.started;+ expect(ampTail).toBeGreaterThan(0.3);+ // …and the sweep lands in the first tenth of it (~30–60ms in every kit).+ expect(body.frequency.values[1]).toBeLessThan(body.frequency.values[0] / 2);+ player.stop();+ });++ it('routes the kick body through a drive shaper, and the bus through a clipper', async () => {+ // A sub-50Hz sine is inaudible on a phone speaker; the drive shaper supplies+ // the harmonics that make it read. Both shapers are load-bearing for the+ // "the kick sounds weak" fix, so both are pinned — structurally, off the+ // fake's recorded connections rather than off node creation order.+ const player = createDrumPlayer(parseDrumChart('tempo: 240\nsubdivision: 1\n\nK: o---'), {});+ await player.play();+ drive(0.2);+ const body = audio.oscillators.find((o) => !o.noise && o.frequency.values.length > 1);+ expect(audio.shapers).toContain(body.connections[0]);+ // The master gain feeds a shaper, which feeds the destination.+ const busShaper = audio.shapers.find((s) => s.connections.some((t) => t?.id === 'destination'));+ expect(busShaper).toBeDefined();+ expect(audio.gains.some((g) => g.connections.includes(busShaper))).toBe(true);+ // Every curve is a real saturation curve: bounded to ±1 and monotonic.+ for (const shaper of audio.shapers) {+ expect(shaper.curve.length).toBeGreaterThan(0);+ expect(Math.max(...shaper.curve)).toBeLessThanOrEqual(1);+ expect(Math.min(...shaper.curve)).toBeGreaterThanOrEqual(-1);+ expect(shaper.curve.every((v, i, a) => i === 0 || v >= a[i - 1])).toBe(true);+ }+ player.stop();});it('scales voice gain by the glyph velocity (accent louder than ghost)', async () => {const player = createDrumPlayer(parseDrumChart('tempo: 240\nsubdivision: 1\n\nHH: X-g-'), {});await player.play();drive(2);- const peaks = audio.gains.map((g) => Math.max(...g.gain.values, 0));- // [master, accent, ghost] in creation order — the accent must be louder.- expect(peaks[1]).toBeGreaterThan(peaks[2]);+ // Creation order is [master, ...accent layers, ...ghost layers] — a voice can+ // be several layers (the 808 hat is a six-oscillator cluster), so compare the+ // two halves rather than two fixed indices.+ const peaks = audio.gains.slice(1).map((g) => Math.max(...g.gain.values, 0));+ const half = peaks.length / 2;+ expect(Number.isInteger(half)).toBe(true);+ expect(Math.max(...peaks.slice(0, half))).toBeGreaterThan(Math.max(...peaks.slice(half)));player.stop();});+ it('setKit swaps the voices live, without stopping playback', async () => {+ const player = createDrumPlayer(parseDrumChart('tempo: 120\nsubdivision: 1\n\nHH: xxxx'), {});+ await player.play();+ drive(0.5);+ // The default 909 hat is one noise burst.+ expect(audio.oscillators.every((o) => o.noise)).toBe(true);+ player.setKit('808');+ drive(1);+ // The 808's is a square cluster — so the swap shows up as pitched sources+ // appearing mid-run, and playback never stopped to do it.+ expect(audio.oscillators.some((o) => !o.noise)).toBe(true);+ expect(player.isPlaying()).toBe(true);+ player.stop();+ });++ it('shares one filter and envelope across a square cluster', async () => {+ // The 808 hat is six oscillators; they must sum into ONE filter + gain (a+ // biquad is linear, so per-partial filters would be six times the nodes for+ // an identical signal) while each partial stays individually stoppable.+ const player = createDrumPlayer(parseDrumChart('tempo: 240\nsubdivision: 1\n\nHH: x---'), {+ kit: '808',+ });+ await player.play();+ drive(0.2);+ expect(audio.oscillators.length).toBeGreaterThan(1);+ expect(audio.filters).toHaveLength(1);+ expect(audio.gains).toHaveLength(2); // the master bus + one voice envelope+ for (const osc of audio.oscillators) expect(osc.connections).toEqual([audio.filters[0]]);+ player.stop();+ // Every partial was stopped — one tracked entry per oscillator, so an open+ // hat or a 1.2s crash can't ring on after Stop.+ expect(audio.oscillators.every((o) => o.stopped !== null)).toBe(true);+ });++ it('falls back to the default kit for an unknown id rather than going silent', async () => {+ const player = createDrumPlayer(parseDrumChart('tempo: 240\nsubdivision: 1\n\nK: o---'), {+ kit: 'roland-tr-nope',+ });+ await player.play();+ drive(2);+ expect(audio.oscillators.length).toBeGreaterThan(0);+ });+it('reports the playhead per grid position, once per bar+step', async () => {const steps = [];const player = createDrumPlayer(CHART, { onStep: (info) => steps.push(info) });diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 3ff7a1abe7..e81b26e71e 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -91,6 +91,7 @@ export * from './canvasRoll.js';export * from './chiptunePlayback.js';export * from './chordShapes.js';export * from './colorMatch.js';+export * from './drumKits.js';export * from './drumNotation.js';export * from './drumPlayback.js';export * from './editorialChecks.js';diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex 8c7d959012..d3f7e2b492 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -587,6 +587,8 @@ export default function SongBookViewer() {barCount={drum.barCount}clickEnabled={drum.clickEnabled}onClickToggle={drum.setClickEnabled}+ kitId={drum.kitId}+ onKitChange={drum.setKitId}beatsPerBar={drum.beatsPerBar}pulse={drum.pulse}currentBar={drum.currentBar}diff --git a/client/src/test/fakeAudioContext.js b/client/src/test/fakeAudioContext.jsindex 94b4739008..4f0603ff30 100644--- a/client/src/test/fakeAudioContext.js+++ b/client/src/test/fakeAudioContext.js@@ -26,16 +26,29 @@ export const createFakeAudio = ({ suspended = false } = {}) => {// too (they satisfy the same start/stop/onended surface the transport tracks),// so a caller that only cares "how many voices sounded" reads that one list.filters: [],+ // WaveShaperNodes — per-voice saturation and the master soft-clipper in+ // drumPlayback.js. `curve` is recorded so a test can assert a voice is+ // actually driven (the harmonics that make a sub-bass kick audible).+ shapers: [],reset() {this.now = 0;this.oscillators.length = 0;this.gains.length = 0;this.filters.length = 0;+ this.shapers.length = 0;resolveResume = null;},// Resolve a suspended context's pending resume() so play()'s await continues.flushResume() { const r = resolveResume; resolveResume = null; if (r) r(); },};+ // Every node records what it was connected TO, so a test can assert ROUTING+ // ("the kick's oscillator feeds a drive shaper") rather than inferring it from+ // node creation order. `connect` still returns its target so chains work.+ const connectable = () => ({+ connections: [],+ connect(target) { this.connections.push(target); return target; },+ disconnect() {},+ });const fakeParam = () => {const values = [];return {@@ -55,13 +68,13 @@ export const createFakeAudio = ({ suspended = false } = {}) => {createOscillator() {const osc = {type: '', frequency: fakeParam(), onended: null, started: null, stopped: null,- connect: (t) => t, start(t) { this.started = t; }, stop(t) { this.stopped = t; },+ ...connectable(), start(t) { this.started = t; }, stop(t) { this.stopped = t; },};audio.oscillators.push(osc);return osc;},createGain() {- const gain = { gain: fakeParam(), connect: (t) => t, disconnect() {} };+ const gain = { gain: fakeParam(), ...connectable() };audio.gains.push(gain);return gain;},@@ -74,17 +87,22 @@ export const createFakeAudio = ({ suspended = false } = {}) => {const src = {buffer: null, loop: false, playbackRate: { value: 1 },onended: null, started: null, stopped: null, noise: true,- connect: (t) => t, start(t) { this.started = t; }, stop(t) { this.stopped = t; },+ ...connectable(), start(t) { this.started = t; }, stop(t) { this.stopped = t; },};// Recorded alongside oscillators: the transport tracks both the same way.audio.oscillators.push(src);return src;},createBiquadFilter() {- const filter = { type: '', frequency: fakeParam(), Q: { value: 1 }, connect: (t) => t };+ const filter = { type: '', frequency: fakeParam(), Q: { value: 1 }, ...connectable() };audio.filters.push(filter);return filter;},+ createWaveShaper() {+ const shaper = { curve: null, oversample: 'none', ...connectable() };+ audio.shapers.push(shaper);+ return shaper;+ },sampleRate: 48000,};}