This commit is contained in:
Andras Schmelczer 2026-05-18 08:11:52 +01:00
commit 15e99380b5
84 changed files with 1659 additions and 4726 deletions

View file

@ -57,4 +57,4 @@ jobs:
if: github.event_name == 'push' && github.ref == 'refs/heads/main' if: github.event_name == 'push' && github.ref == 'refs/heads/main'
run: | run: |
apt update && apt install -y rsync apt update && apt install -y rsync
rsync -a --delete dist/ /pages/fleeting-garden rsync -a --delete dist/ /pages/fleeting

45
.gitignore vendored
View file

@ -1,47 +1,2 @@
# Dependency directory
node_modules node_modules
modules/
ts-node--*/
rss.xml
dist dist
playwright-report
test-results
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
*.ssh
*.ppk
v8-compile-cache-0/
Thumbs.db
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
bin
ts-node
# Personal Scripts
*.bat
*.ssh
*.sh
!system.min.js
# Editors
.vscode
.markdownlint.json
# Build Files
temp
*.js
*.map
!webpack.*

2
definitions.d.ts vendored
View file

@ -6,5 +6,3 @@ declare module '*.wgsl?raw' {
interface HTMLCanvasElement { interface HTMLCanvasElement {
getContext(contextId: 'webgpu'): GPUCanvasContext | null; getContext(contextId: 'webgpu'): GPUCanvasContext | null;
} }
declare var webkitOfflineAudioContext: typeof OfflineAudioContext | undefined;

View file

@ -133,3 +133,37 @@ test('shows a clear fallback when WebGPU is unavailable', async ({ page }) => {
await expect(fallback).toContainText('webgpu-unsupported'); await expect(fallback).toContainText('webgpu-unsupported');
expect(browserFailures).toEqual([]); expect(browserFailures).toEqual([]);
}); });
test('keeps audio focus outlines scoped to the active control', async ({ page }) => {
await disableWebGpu(page);
await page.goto('/');
await expect(page.locator('body')).not.toHaveClass(/is-loading/);
const audioControl = page.locator('.audio-control');
const soundButton = page.locator('button.sound');
const volumeSlider = page.locator('.volume-slider');
await soundButton.click();
await expect(audioControl).toHaveCSS('outline-style', 'none');
await expect(soundButton).toHaveCSS('outline-style', 'none');
await page.mouse.click(10, 10);
for (let tabIndex = 0; tabIndex < 12; tabIndex += 1) {
await page.keyboard.press('Tab');
const activeClass = await page.evaluate(() =>
String(document.activeElement?.className ?? '')
);
if (activeClass.includes('sound')) {
break;
}
}
await expect(soundButton).toBeFocused();
await expect(soundButton).toHaveCSS('outline-style', 'solid');
await expect(soundButton).toHaveCSS('outline-offset', '-4px');
await page.keyboard.press('Tab');
await expect(volumeSlider).toBeFocused();
await expect(volumeSlider).toHaveCSS('outline-style', 'solid');
await expect(volumeSlider).toHaveCSS('outline-offset', '-4px');
});

View file

@ -47,11 +47,14 @@
<div class="garden-prompt" aria-live="polite"></div> <div class="garden-prompt" aria-live="polite"></div>
<div class="loading-indicator" role="status"> <div class="loading-indicator" role="status">
<div class="loading-dots" aria-hidden="true"> <div class="splash">
<span class="loading-dot"></span> <h1 class="splash-title">Fleeting Garden</h1>
<span class="loading-dot"></span> <p class="splash-description">
<span class="loading-dot"></span> Draw coloured paths and watch them bloom into a living WebGPU garden.
</p>
<button class="start-button" type="button" disabled>Start</button>
</div> </div>
<div class="loading-bar" hidden>
<div class="loading-status">Starting up&hellip;</div> <div class="loading-status">Starting up&hellip;</div>
<div <div
class="loading-progress" class="loading-progress"
@ -62,6 +65,7 @@
aria-valuenow="0" aria-valuenow="0"
></div> ></div>
</div> </div>
</div>
<section class="errors-container"> <section class="errors-container">
<noscript>JavaScript is required for this website.</noscript> <noscript>JavaScript is required for this website.</noscript>
@ -141,6 +145,7 @@
</label> </label>
</div> </div>
</section> </section>
</div>
<nav class="buttons" aria-label="App controls"> <nav class="buttons" aria-label="App controls">
<button <button
@ -190,7 +195,6 @@
title="Restart simulation" title="Restart simulation"
></button> ></button>
</nav> </nav>
</div>
<button class="next-vibe vibe-button" aria-label="Next vibe" title="Next vibe"> <button class="next-vibe vibe-button" aria-label="Next vibe" title="Next vibe">
&rsaquo; &rsaquo;

33
package-lock.json generated
View file

@ -22,6 +22,7 @@
"@vitejs/plugin-basic-ssl": "^2.3.0", "@vitejs/plugin-basic-ssl": "^2.3.0",
"@webgpu/types": "^0.1.69", "@webgpu/types": "^0.1.69",
"browserslist": "^4.28.2", "browserslist": "^4.28.2",
"browserslist-to-esbuild": "^2.1.1",
"eslint": "^10.3.0", "eslint": "^10.3.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"gl-matrix": "^3.4.4", "gl-matrix": "^3.4.4",
@ -2832,6 +2833,25 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
} }
}, },
"node_modules/browserslist-to-esbuild": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/browserslist-to-esbuild/-/browserslist-to-esbuild-2.1.1.tgz",
"integrity": "sha512-KN+mty6C3e9AN8Z5dI1xeN15ExcRNeISoC3g7V0Kax/MMF9MSoYA2G7lkTTcVUFntiEjkpI0HNgqJC1NjdyNUw==",
"dev": true,
"license": "MIT",
"dependencies": {
"meow": "^13.0.0"
},
"bin": {
"browserslist-to-esbuild": "cli/index.js"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"browserslist": "*"
}
},
"node_modules/cac": { "node_modules/cac": {
"version": "6.7.14", "version": "6.7.14",
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
@ -3954,6 +3974,19 @@
"@jridgewell/sourcemap-codec": "^1.5.5" "@jridgewell/sourcemap-codec": "^1.5.5"
} }
}, },
"node_modules/meow": {
"version": "13.2.0",
"resolved": "https://registry.npmjs.org/meow/-/meow-13.2.0.tgz",
"integrity": "sha512-pxQJQzB6djGPXh08dacEloMFopsOqGVRKFPYvPOt9XDZ1HasbgDZA74CJGreSU4G3Ak7EFJGoiH2auq+yXISgA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/micromatch": { "node_modules/micromatch": {
"version": "4.0.8", "version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",

View file

@ -54,6 +54,7 @@
"@vitejs/plugin-basic-ssl": "^2.3.0", "@vitejs/plugin-basic-ssl": "^2.3.0",
"@webgpu/types": "^0.1.69", "@webgpu/types": "^0.1.69",
"browserslist": "^4.28.2", "browserslist": "^4.28.2",
"browserslist-to-esbuild": "^2.1.1",
"eslint": "^10.3.0", "eslint": "^10.3.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"gl-matrix": "^3.4.4", "gl-matrix": "^3.4.4",

View file

@ -52,6 +52,10 @@ export const trackVibeChange = ({
}); });
}; };
export const trackStart = () => {
track('Start');
};
export const trackExport = ({ vibeId }: { vibeId: VibeId }) => { export const trackExport = ({ vibeId }: { vibeId: VibeId }) => {
track('Export', { track('Export', {
props: { props: {

View file

@ -8,201 +8,6 @@ export interface GardenAudioChord {
quality: GardenAudioChordQuality; quality: GardenAudioChordQuality;
} }
interface GardenAudioStyleVoice {
scaleDegreeOffset: number;
velocityMultiplier: number;
panOffset: number;
}
export interface GardenAudioRegister {
midiMin: number;
midiMax: number;
preferredMidi: number;
pan: number;
}
export interface GardenAudioStylePool extends GardenAudioRegister {
scaleDegrees: Array<number>;
}
interface GardenAudioGenerativePianoConfig {
stylePools: [GardenAudioStylePool, GardenAudioStylePool, GardenAudioStylePool];
padRegisters: [GardenAudioRegister, GardenAudioRegister, GardenAudioRegister];
chordVoicings: {
majorOpen: Array<number>;
minorOpen: Array<number>;
majorClosed: Array<number>;
minorClosed: Array<number>;
};
vibeChangeStinger: {
velocities: [number, number, number];
pans: [number, number, number];
delaySends: [number, number, number];
lowpassExpression: number;
};
highActivityExtra: {
barOffset: number;
expressionMultiplier: number;
};
padChord: {
velocities: [number, number, number];
expressionVelocityWeight: number;
delaySend: number;
lowpassExpressionWeight: number;
};
supportNote: {
velocityBase: number;
velocityExpressionWeight: number;
durationBaseSeconds: number;
durationExpressionSeconds: number;
delaySendBase: number;
delaySendExpressionWeight: number;
lowpassExpressionWeight: number;
expressionThreshold: number;
offsetsByStyle: [Array<number>, Array<number>, Array<number>];
};
textureNote: {
velocityBase: number;
velocityExpressionWeight: number;
durationBaseSeconds: number;
durationExpressionSeconds: number;
delaySendBase: number;
delaySendExpressionWeight: number;
idleExpressionThreshold: number;
mediumExpressionThreshold: number;
intenseSpacing: number;
idlePhase: number;
};
gestureAccent: {
rotationStrengthMultiplier: number;
quantizeStepLookahead: number;
velocityBase: number;
velocityStrengthWeight: number;
durationBaseSeconds: number;
durationStrengthSeconds: number;
delaySend: number;
};
touchNote: {
registerBiasManiaAmount: number;
velocityBase: number;
velocityStrengthWeight: number;
durationBaseSeconds: number;
durationStrengthSeconds: number;
delaySend: number;
lowpassBaseExpression: number;
lowpassStrengthWeight: number;
};
brushPhrase: {
initialMotifOffset: number;
energyDecaySeconds: number;
maniaDecaySeconds: number;
fadeMinimumLifetimeSeconds: number;
layerIntensityBase: number;
layerIntensityManiaWeight: number;
frameActivityWeight: number;
frameManiaWeight: number;
};
brushStream: {
inferredManiaThreshold: number;
inferredManiaRange: number;
registerManiaShift: number;
chordToneEverySteps: number;
durationBaseSeconds: number;
durationIntensitySeconds: number;
durationManiaSeconds: number;
durationMinSeconds: number;
durationMaxSeconds: number;
delaySendBase: number;
delaySendIntensityWeight: number;
delaySendManiaWeight: number;
delaySendMin: number;
delaySendMax: number;
velocityBase: number;
velocityIntensityWeight: number;
lowpassBaseExpression: number;
lowpassIntensityWeight: number;
lowpassManiaWeight: number;
manicThreshold: number;
intenseThreshold: number;
activeThreshold: number;
};
brushStreamEcho: {
maniaThreshold: number;
stepModulo: number;
stepRemainder: number;
intensityThreshold: number;
octaveSemitones: number;
maxMidi: number;
velocityBase: number;
velocityIntensityWeight: number;
durationMinSeconds: number;
durationScale: number;
panScale: number;
delaySendMin: number;
delaySendScale: number;
lowpassBaseExpression: number;
lowpassManiaWeight: number;
};
brushMotif: {
highThreshold: number;
mediumThreshold: number;
highOffset: number;
mediumOffset: number;
lowOffset: number;
minOffset: number;
maxOffset: number;
};
registerBias: {
maniaShiftSemitones: number;
midiMin: number;
midiMaxForMin: number;
minimumSpan: number;
midiMax: number;
};
candidateOctaveSearch: {
min: number;
max: number;
};
stylePanOffsetScale: number;
lowpass: {
midiBase: number;
midiRange: number;
midiLiftHz: number;
expressionBase: number;
expressionWeight: number;
};
styleRotationBars: number;
chordBars: number;
supportBarSpacing: number;
supportBarOffset: number;
idleTextureBarSpacing: number;
mediumTextureBarSpacing: number;
textureBeat: number;
highActivityExtraBeat: number;
highActivityExtraThreshold: number;
noteScorePreferenceWeight: number;
noteScoreRegisterWeight: number;
noteScoreChordToneWeight: number;
noteScoreRepeatPenalty: number;
gestureAccentMinIntervalSeconds: number;
strokeAccentMinSteps: number;
strokeAccentThreshold: number;
stingerDurationSeconds: number;
stingerSpacingSeconds: number;
maxBrushPhraseLayers: number;
maxBrushStreamNotesPerBar: number;
brushLayerBaseSeconds: number;
brushLayerEnergySeconds: number;
brushLayerMinIntensity: number;
brushStreamIdleIntervalBeats: number;
brushStreamActiveIntervalBeats: number;
brushStreamIntenseIntervalBeats: number;
brushStreamManicIntervalBeats: number;
brushMotifMaxSteps: number;
brushMotifCanonDelaySeconds: number;
padDurationBarScale: number;
}
export interface GardenAudioVibeProfile { export interface GardenAudioVibeProfile {
rootMidi: number; rootMidi: number;
scale: Array<number>; scale: Array<number>;
@ -215,7 +20,6 @@ export interface GardenAudioConfig {
masterVolume: number; masterVolume: number;
fadeInSeconds: number; fadeInSeconds: number;
updateRampSeconds: number; updateRampSeconds: number;
highPassFrequencyHz: number;
delay: { delay: {
timeSeconds: number; timeSeconds: number;
feedback: number; feedback: number;
@ -228,44 +32,24 @@ export interface GardenAudioConfig {
outputBase: number; outputBase: number;
outputActivityDuck: number; outputActivityDuck: number;
timeRampSeconds: number; timeRampSeconds: number;
feedbackHighPassHz: number;
feedbackLowPassHz: number;
returnLowPassHz: number;
}; };
piano: { piano: {
maxVoices: number; maxVoices: number;
filterType: BiquadFilterType;
gain: number; gain: number;
sustainSeconds: number; sustainSeconds: number;
sustainLevel: number; sustainLevel: number;
releaseSeconds: number; releaseSeconds: number;
lowpassHz: number; lowpassHz: number;
filterQ: number;
gainAttackSeconds: number; gainAttackSeconds: number;
lowpassMaxHz: number; lowpassMaxHz: number;
lowpassMinHz: number; lowpassMinHz: number;
minDurationSeconds: number;
minFadeSeconds: number;
minGain: number;
pitchSemitonesPerOctave: number;
scheduleAheadSeconds: number;
sustainBase: number; sustainBase: number;
sustainVelocityRange: number; sustainVelocityRange: number;
tailStopExtraSeconds: number;
voiceStealFadeSeconds: number;
voiceStealStopSeconds: number;
sampleBaseUrl: string;
preloadDecode: {
channels: number;
frames: number;
sampleRateHz: number;
};
}; };
rhythm: { rhythm: {
bpm: number; bpm: number;
stepsPerBeat: number; stepsPerBeat: number;
stepsPerBar: number; stepsPerBar: number;
lookaheadSeconds: number;
sparseActivity: number; sparseActivity: number;
}; };
eraser: { eraser: {
@ -285,32 +69,11 @@ export interface GardenAudioConfig {
strokeDecaySeconds: number; strokeDecaySeconds: number;
}; };
graph: { graph: {
closeGain: number;
closeRampSeconds: number;
delayMaxSeconds: number;
eventBusGain: number;
noiseMax: number;
noiseMin: number;
unlockTickFrequencyHz: number;
unlockTickSeconds: number;
unlockTickType: OscillatorType;
latencyHint: AudioContextLatencyCategory;
outputFilterType: BiquadFilterType;
noiseBufferChannels: number;
noiseBufferDurationSeconds: number;
pianoBusGains: Record<PianoNoteRole, number>; pianoBusGains: Record<PianoNoteRole, number>;
pianoBusActivityDucking: Record<PianoNoteRole, number>; pianoBusActivityDucking: Record<PianoNoteRole, number>;
noiseBusGain: number; noiseBusGain: number;
compressor: {
thresholdDb: number;
kneeDb: number;
ratio: number;
attackSeconds: number;
releaseSeconds: number;
};
}; };
input: { input: {
fallbackFrameSeconds: number;
fullActivitySpeed: number; fullActivitySpeed: number;
activityNoiseFloorSpeed: number; activityNoiseFloorSpeed: number;
activityCurve: number; activityCurve: number;
@ -321,22 +84,7 @@ export interface GardenAudioConfig {
manicActivityThreshold: number; manicActivityThreshold: number;
manicReleaseThreshold: number; manicReleaseThreshold: number;
maniaSmoothingSeconds: number; maniaSmoothingSeconds: number;
minElapsedSeconds: number;
}; };
muteGain: number;
muteRampSeconds: number;
noiseBurst: {
attackSeconds: number;
filterQ: number;
offsetRandomSeconds: number;
scheduleAheadSeconds: number;
silentGain: number;
filterType: BiquadFilterType;
};
startDelaySeconds: number;
vibeChangeStingerMinIntervalSeconds: number;
generativePiano: GardenAudioGenerativePianoConfig;
styleVoices: [GardenAudioStyleVoice, GardenAudioStyleVoice, GardenAudioStyleVoice];
} }
export const gardenAudioConfig: GardenAudioConfig = appConfig.audio; export const gardenAudioConfig: GardenAudioConfig = appConfig.audio;

View file

@ -1,49 +0,0 @@
import { describe, expect, it } from 'vitest';
import { gardenAudioConfig } from './garden-audio-config';
import { GardenAudioEnergy } from './garden-audio-energy';
describe('GardenAudioEnergy', () => {
it('suspends activity but keeps a fading level when the gesture ends', () => {
const energy = new GardenAudioEnergy(gardenAudioConfig);
energy.beginGesture(0);
energy.recordStroke(0.8, 0.1);
energy.update(0.1);
energy.update(0.2);
const levelBeforeLift = energy.getLevel();
expect(energy.getActivity()).toBeGreaterThan(0);
energy.endGesture();
expect(energy.getActivity()).toBe(0);
expect(energy.getLevel()).toBe(levelBeforeLift);
energy.update(0.3);
expect(energy.getLevel()).toBeLessThan(levelBeforeLift);
expect(energy.getLevel()).toBeGreaterThan(0);
});
it('uses recent stroke intensity rather than gesture duration alone', () => {
const energy = new GardenAudioEnergy(gardenAudioConfig);
energy.beginGesture(0);
energy.recordStroke(1, 0.1);
energy.update(0.1);
energy.update(0.2);
const activeLevel = energy.getActivity();
energy.update(1.2);
expect(energy.getActivity()).toBeLessThan(activeLevel);
});
it('raises activity immediately when a stroke is recorded', () => {
const energy = new GardenAudioEnergy(gardenAudioConfig);
energy.beginGesture(0);
energy.recordStroke(0.12, 0.05);
expect(energy.getActivity()).toBeGreaterThan(0.09);
});
});

View file

@ -1,4 +1,4 @@
import { clamp01 } from '../utils/clamp'; import { approach, clamp01 } from '../utils/math';
import type { GardenAudioConfig } from './garden-audio-config'; import type { GardenAudioConfig } from './garden-audio-config';
export class GardenAudioEnergy { export class GardenAudioEnergy {
@ -59,8 +59,7 @@ export class GardenAudioEnergy {
} else if (target > this.energy) { } else if (target > this.energy) {
timeConstant = this.config.energy.attackSeconds; timeConstant = this.config.energy.attackSeconds;
} }
const amount = 1 - Math.exp(-elapsedSeconds / timeConstant); this.energy = approach(this.energy, target, elapsedSeconds, timeConstant);
this.energy += (target - this.energy) * amount;
} }
public getActivity(): number { public getActivity(): number {

View file

@ -1,95 +0,0 @@
import { describe, expect, it } from 'vitest';
import { gardenAudioConfig } from './garden-audio-config';
import { GardenAudioGestureState } from './garden-audio-gesture-state';
import type { GardenAudioStrokeMetrics } from './garden-audio-input';
const makeMetrics = ({
elapsedSeconds,
normalizedDistance,
}: {
elapsedSeconds: number;
normalizedDistance: number;
}): GardenAudioStrokeMetrics => ({
distancePixels: normalizedDistance * 1000,
elapsedSeconds,
normalizedDistance,
normalizedSpeed: normalizedDistance / elapsedSeconds,
});
describe('GardenAudioGestureState', () => {
it('ignores tiny jitter below the activity speed floor', () => {
const state = new GardenAudioGestureState(gardenAudioConfig.input);
state.beginGesture();
expect(
state.recordStroke({
metrics: makeMetrics({
elapsedSeconds: 0.1,
normalizedDistance: 0.001,
}),
}).activity
).toBe(0);
});
it('normalizes equal drawing speeds across pointer sample rates', () => {
const lowRate = new GardenAudioGestureState(gardenAudioConfig.input);
const highRate = new GardenAudioGestureState(gardenAudioConfig.input);
lowRate.beginGesture();
highRate.beginGesture();
const lowRateFrame = lowRate.recordStroke({
metrics: makeMetrics({
elapsedSeconds: 0.1,
normalizedDistance: 0.07,
}),
});
let highRateFrame = { activity: 0, maniaAmount: 0 };
for (let index = 0; index < 5; index += 1) {
highRateFrame = highRate.recordStroke({
metrics: makeMetrics({
elapsedSeconds: 0.02,
normalizedDistance: 0.014,
}),
});
}
expect(highRateFrame.activity).toBeCloseTo(lowRateFrame.activity, 5);
});
it('holds mania with hysteresis before releasing', () => {
const state = new GardenAudioGestureState(gardenAudioConfig.input);
state.beginGesture();
const manicFrame = state.recordStroke({
metrics: makeMetrics({
elapsedSeconds: 0.25,
normalizedDistance: 0.3,
}),
});
expect(manicFrame.maniaAmount).toBeGreaterThan(0);
const heldFrame = state.recordStroke({
metrics: makeMetrics({
elapsedSeconds: 0.06,
normalizedDistance: 0.04,
}),
});
expect(heldFrame.maniaAmount).toBeGreaterThan(0);
const releasedFrame = state.recordStroke({
metrics: makeMetrics({
elapsedSeconds: 0.7,
normalizedDistance: 0,
}),
});
expect(releasedFrame.maniaAmount).toBeLessThan(heldFrame.maniaAmount);
});
});

View file

@ -1,4 +1,4 @@
import { clamp, clamp01 } from '../utils/clamp'; import { approach, clamp, clamp01, smoothstep } from '../utils/math';
import type { GardenAudioConfig } from './garden-audio-config'; import type { GardenAudioConfig } from './garden-audio-config';
import type { GardenAudioStrokeMetrics } from './garden-audio-input'; import type { GardenAudioStrokeMetrics } from './garden-audio-input';
@ -92,18 +92,3 @@ export class GardenAudioGestureState {
return clamp(activity * distanceAmount, 0, this.inputConfig.activitySoftCeiling); return clamp(activity * distanceAmount, 0, this.inputConfig.activitySoftCeiling);
} }
} }
const approach = (
current: number,
target: number,
elapsedSeconds: number,
timeConstantSeconds: number
): number => {
const amount = 1 - Math.exp(-elapsedSeconds / Math.max(0.001, timeConstantSeconds));
return current + (target - current) * amount;
};
const smoothstep = (edge0: number, edge1: number, value: number): number => {
const amount = clamp01((value - edge0) / (edge1 - edge0));
return amount * amount * (3 - 2 * amount);
};

View file

@ -1,92 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { VIBE_PRESETS } from '../vibes';
import { gardenAudioConfig } from './garden-audio-config';
import { GardenAudioGraph } from './garden-audio-graph';
class FakeAudioParam {
public value = 0;
public setTargetAtTime = vi.fn();
}
class FakeAudioNode {
public readonly gain = new FakeAudioParam();
public readonly frequency = new FakeAudioParam();
public readonly threshold = new FakeAudioParam();
public readonly knee = new FakeAudioParam();
public readonly ratio = new FakeAudioParam();
public readonly attack = new FakeAudioParam();
public readonly release = new FakeAudioParam();
public readonly delayTime = new FakeAudioParam();
public readonly connections: Array<unknown> = [];
public type = '';
public connect(target: unknown): unknown {
this.connections.push(target);
return target;
}
}
class FakeAudioBuffer {
private readonly data: Float32Array;
public constructor(length: number) {
this.data = new Float32Array(length);
}
public getChannelData(): Float32Array {
return this.data;
}
}
class FakeAudioContext {
public readonly currentTime = 1;
public readonly destination = new FakeAudioNode() as unknown as AudioDestinationNode;
public readonly sampleRate = 16;
public readonly state = 'running';
public readonly compressors: Array<FakeAudioNode> = [];
public createGain(): GainNode {
return new FakeAudioNode() as unknown as GainNode;
}
public createBiquadFilter(): BiquadFilterNode {
return new FakeAudioNode() as unknown as BiquadFilterNode;
}
public createDelay(): DelayNode {
return new FakeAudioNode() as unknown as DelayNode;
}
public createDynamicsCompressor(): DynamicsCompressorNode {
const node = new FakeAudioNode();
this.compressors.push(node);
return node as unknown as DynamicsCompressorNode;
}
public createBuffer(_channels: number, length: number): AudioBuffer {
return new FakeAudioBuffer(length) as unknown as AudioBuffer;
}
}
describe('GardenAudioGraph', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('builds controlled output, role buses, and delay automation', () => {
vi.stubGlobal('AudioContext', FakeAudioContext);
const graph = new GardenAudioGraph(gardenAudioConfig);
const context = graph.ensureContext(true) as unknown as FakeAudioContext;
expect(context.compressors).toHaveLength(1);
expect(graph.getPianoBus('pad')).not.toBeNull();
expect(graph.getPianoBus('pad')).not.toBe(graph.getPianoBus('gesture'));
expect(graph.noiseBus).not.toBeNull();
graph.updateDelay(VIBE_PRESETS[0].audio, 1);
expect(graph.getPianoBus('pad')?.gain.setTargetAtTime).toHaveBeenCalled();
expect(graph.getPianoBus('brush')?.gain.setTargetAtTime).toHaveBeenCalled();
});
});

View file

@ -1,7 +1,38 @@
import { clamp } from '../utils/clamp'; import { clamp } from '../utils/math';
import { GardenAudioConfig, GardenAudioVibeProfile } from './garden-audio-config'; import { isIosLike } from './audio-platform';
import type { GardenAudioConfig, GardenAudioVibeProfile } from './garden-audio-config';
import type { PianoNoteRole } from './garden-audio-types'; import type { PianoNoteRole } from './garden-audio-types';
const outputHighPassFrequencyHz = 45;
const graphTuning = {
closeGain: 0.0001,
closeRampSeconds: 0.015,
delayMaxSeconds: 2,
eventBusGain: 1,
noiseMax: 1,
noiseMin: -1,
latencyHint: 'interactive' as AudioContextLatencyCategory,
outputFilterType: 'highpass' as BiquadFilterType,
noiseBufferChannels: 1,
noiseBufferDurationSeconds: 1,
unlockTickFrequencyHz: 440,
unlockTickGain: 0.0001,
unlockTickSeconds: 0.025,
unlockTickType: 'sine' as OscillatorType,
compressor: {
thresholdDb: -18,
kneeDb: 18,
ratio: 2.1,
attackSeconds: 0.018,
releaseSeconds: 0.18,
},
};
const delayFilterTuning = {
feedbackHighPassHz: 180,
feedbackLowPassHz: 5200,
returnLowPassHz: 6200,
};
export class GardenAudioGraph { export class GardenAudioGraph {
public context: AudioContext | null = null; public context: AudioContext | null = null;
public eventBus: GainNode | null = null; public eventBus: GainNode | null = null;
@ -13,6 +44,8 @@ export class GardenAudioGraph {
private delayNode: DelayNode | null = null; private delayNode: DelayNode | null = null;
private delayFeedback: GainNode | null = null; private delayFeedback: GainNode | null = null;
private delayOutput: GainNode | null = null; private delayOutput: GainNode | null = null;
private mediaStreamDestination: MediaStreamAudioDestinationNode | null = null;
private mediaStreamElement: HTMLAudioElement | null = null;
private readonly pianoBuses = new Map<PianoNoteRole, GainNode>(); private readonly pianoBuses = new Map<PianoNoteRole, GainNode>();
public constructor(private readonly config: GardenAudioConfig) {} public constructor(private readonly config: GardenAudioConfig) {}
@ -34,7 +67,7 @@ export class GardenAudioGraph {
let context: AudioContext; let context: AudioContext;
try { try {
context = new AudioContextConstructor({ context = new AudioContextConstructor({
latencyHint: this.config.graph.latencyHint, latencyHint: graphTuning.latencyHint,
}); });
} catch { } catch {
context = new AudioContextConstructor(); context = new AudioContextConstructor();
@ -42,22 +75,30 @@ export class GardenAudioGraph {
const masterGain = context.createGain(); const masterGain = context.createGain();
const highPass = context.createBiquadFilter(); const highPass = context.createBiquadFilter();
const compressor = context.createDynamicsCompressor(); const compressor = context.createDynamicsCompressor();
const mediaStreamDestination = isIosLike()
? context.createMediaStreamDestination()
: null;
masterGain.gain.value = 0; masterGain.gain.value = 0;
highPass.type = this.config.graph.outputFilterType; highPass.type = graphTuning.outputFilterType;
highPass.frequency.value = this.config.highPassFrequencyHz; highPass.frequency.value = outputHighPassFrequencyHz;
compressor.threshold.value = this.config.graph.compressor.thresholdDb; compressor.threshold.value = graphTuning.compressor.thresholdDb;
compressor.knee.value = this.config.graph.compressor.kneeDb; compressor.knee.value = graphTuning.compressor.kneeDb;
compressor.ratio.value = this.config.graph.compressor.ratio; compressor.ratio.value = graphTuning.compressor.ratio;
compressor.attack.value = this.config.graph.compressor.attackSeconds; compressor.attack.value = graphTuning.compressor.attackSeconds;
compressor.release.value = this.config.graph.compressor.releaseSeconds; compressor.release.value = graphTuning.compressor.releaseSeconds;
masterGain.connect(highPass); masterGain.connect(highPass);
highPass.connect(compressor); highPass.connect(compressor);
if (mediaStreamDestination) {
compressor.connect(mediaStreamDestination);
} else {
compressor.connect(context.destination); compressor.connect(context.destination);
}
this.context = context; this.context = context;
this.masterGain = masterGain; this.masterGain = masterGain;
this.mediaStreamDestination = mediaStreamDestination;
this.noiseBuffer = this.createNoiseBuffer(context); this.noiseBuffer = this.createNoiseBuffer(context);
this.createDelay(context, masterGain); this.createDelay(context, masterGain);
this.createBuses(context, masterGain); this.createBuses(context, masterGain);
@ -77,17 +118,13 @@ export class GardenAudioGraph {
const source = this.context.createOscillator(); const source = this.context.createOscillator();
const gain = this.context.createGain(); const gain = this.context.createGain();
source.type = this.config.graph.unlockTickType; source.type = graphTuning.unlockTickType;
source.frequency.setValueAtTime(this.config.graph.unlockTickFrequencyHz, now); source.frequency.setValueAtTime(graphTuning.unlockTickFrequencyHz, now);
gain.gain.setValueAtTime(this.config.piano.minGain, now); gain.gain.setValueAtTime(graphTuning.unlockTickGain, now);
gain.gain.exponentialRampToValueAtTime(
this.config.piano.minGain,
now + this.config.graph.unlockTickSeconds
);
source.connect(gain); source.connect(gain);
gain.connect(this.context.destination); gain.connect(this.context.destination);
source.start(now); source.start(now);
source.stop(now + this.config.graph.unlockTickSeconds); source.stop(now + graphTuning.unlockTickSeconds);
source.addEventListener( source.addEventListener(
'ended', 'ended',
() => { () => {
@ -110,6 +147,38 @@ export class GardenAudioGraph {
); );
} }
public startMediaElementOutput(): void {
if (!this.mediaStreamDestination) {
return;
}
const mediaElement = this.ensureMediaStreamElement();
const playPromise = mediaElement.play();
void playPromise?.catch(() => undefined);
}
private ensureMediaStreamElement(): HTMLAudioElement {
if (this.mediaStreamElement) {
return this.mediaStreamElement;
}
const mediaElement = document.createElement('audio');
mediaElement.autoplay = true;
mediaElement.volume = 1;
mediaElement.setAttribute('playsinline', '');
mediaElement.setAttribute('aria-hidden', 'true');
mediaElement.style.position = 'fixed';
mediaElement.style.width = '1px';
mediaElement.style.height = '1px';
mediaElement.style.opacity = '0';
mediaElement.style.pointerEvents = 'none';
mediaElement.style.left = '-9999px';
mediaElement.srcObject = this.mediaStreamDestination?.stream ?? null;
document.body.append(mediaElement);
this.mediaStreamElement = mediaElement;
return mediaElement;
}
public applyDelayProfile(profile: GardenAudioVibeProfile): void { public applyDelayProfile(profile: GardenAudioVibeProfile): void {
if (!this.context || !this.delayNode) { if (!this.context || !this.delayNode) {
return; return;
@ -167,9 +236,9 @@ export class GardenAudioGraph {
if (this.masterGain && context.state !== 'closed') { if (this.masterGain && context.state !== 'closed') {
this.masterGain.gain.setTargetAtTime( this.masterGain.gain.setTargetAtTime(
this.config.graph.closeGain, graphTuning.closeGain,
context.currentTime, context.currentTime,
this.config.graph.closeRampSeconds graphTuning.closeRampSeconds
); );
} }
@ -182,7 +251,7 @@ export class GardenAudioGraph {
private createDelay(context: AudioContext, masterGain: GainNode): void { private createDelay(context: AudioContext, masterGain: GainNode): void {
const delayInput = context.createGain(); const delayInput = context.createGain();
const delayNode = context.createDelay(this.config.graph.delayMaxSeconds); const delayNode = context.createDelay(graphTuning.delayMaxSeconds);
const delayFeedback = context.createGain(); const delayFeedback = context.createGain();
const delayOutput = context.createGain(); const delayOutput = context.createGain();
const feedbackHighPass = context.createBiquadFilter(); const feedbackHighPass = context.createBiquadFilter();
@ -193,11 +262,11 @@ export class GardenAudioGraph {
delayFeedback.gain.value = this.config.delay.feedback; delayFeedback.gain.value = this.config.delay.feedback;
delayOutput.gain.value = this.config.delay.wetGain; delayOutput.gain.value = this.config.delay.wetGain;
feedbackHighPass.type = 'highpass'; feedbackHighPass.type = 'highpass';
feedbackHighPass.frequency.value = this.config.delay.feedbackHighPassHz; feedbackHighPass.frequency.value = delayFilterTuning.feedbackHighPassHz;
feedbackLowPass.type = 'lowpass'; feedbackLowPass.type = 'lowpass';
feedbackLowPass.frequency.value = this.config.delay.feedbackLowPassHz; feedbackLowPass.frequency.value = delayFilterTuning.feedbackLowPassHz;
returnLowPass.type = 'lowpass'; returnLowPass.type = 'lowpass';
returnLowPass.frequency.value = this.config.delay.returnLowPassHz; returnLowPass.frequency.value = delayFilterTuning.returnLowPassHz;
delayInput.connect(delayNode); delayInput.connect(delayNode);
delayNode.connect(feedbackHighPass); delayNode.connect(feedbackHighPass);
@ -216,7 +285,7 @@ export class GardenAudioGraph {
private createBuses(context: AudioContext, masterGain: GainNode): void { private createBuses(context: AudioContext, masterGain: GainNode): void {
const eventBus = context.createGain(); const eventBus = context.createGain();
eventBus.gain.value = this.config.graph.eventBusGain; eventBus.gain.value = graphTuning.eventBusGain;
eventBus.connect(masterGain); eventBus.connect(masterGain);
this.eventBus = eventBus; this.eventBus = eventBus;
this.pianoBuses.clear(); this.pianoBuses.clear();
@ -249,12 +318,11 @@ export class GardenAudioGraph {
private createNoiseBuffer(context: AudioContext): AudioBuffer { private createNoiseBuffer(context: AudioContext): AudioBuffer {
const buffer = context.createBuffer( const buffer = context.createBuffer(
appPositiveInteger(this.config.graph.noiseBufferChannels), appPositiveInteger(graphTuning.noiseBufferChannels),
Math.max( Math.max(
1, 1,
Math.floor( Math.floor(
context.sampleRate * context.sampleRate * Math.max(0.001, graphTuning.noiseBufferDurationSeconds)
Math.max(0.001, this.config.graph.noiseBufferDurationSeconds)
) )
), ),
context.sampleRate context.sampleRate
@ -263,8 +331,8 @@ export class GardenAudioGraph {
for (let index = 0; index < data.length; index++) { for (let index = 0; index < data.length; index++) {
data[index] = data[index] =
this.config.graph.noiseMin + graphTuning.noiseMin +
Math.random() * (this.config.graph.noiseMax - this.config.graph.noiseMin); Math.random() * (graphTuning.noiseMax - graphTuning.noiseMin);
} }
return buffer; return buffer;
@ -280,6 +348,13 @@ export class GardenAudioGraph {
this.delayNode = null; this.delayNode = null;
this.delayFeedback = null; this.delayFeedback = null;
this.delayOutput = null; this.delayOutput = null;
this.mediaStreamDestination = null;
if (this.mediaStreamElement) {
this.mediaStreamElement.pause();
this.mediaStreamElement.srcObject = null;
this.mediaStreamElement.remove();
this.mediaStreamElement = null;
}
this.pianoBuses.clear(); this.pianoBuses.clear();
} }
} }

View file

@ -1,52 +0,0 @@
import { describe, expect, it } from 'vitest';
import { gardenAudioConfig } from './garden-audio-config';
import { getStrokeMetrics } from './garden-audio-input';
describe('getStrokeMetrics', () => {
it('normalizes stroke distance against canvas size', () => {
const standardDensity = getStrokeMetrics(
{
vibe: {} as never,
from: [0, 0],
to: [100, 0],
canvasSize: [1000, 500],
elapsedSeconds: 0.1,
isErasing: false,
},
gardenAudioConfig.input
);
const highDensity = getStrokeMetrics(
{
vibe: {} as never,
from: [0, 0],
to: [200, 0],
canvasSize: [2000, 1000],
elapsedSeconds: 0.1,
isErasing: false,
},
gardenAudioConfig.input
);
expect(highDensity.normalizedDistance).toBeCloseTo(
standardDensity.normalizedDistance
);
expect(highDensity.normalizedSpeed).toBeCloseTo(standardDensity.normalizedSpeed);
});
it('uses configured elapsed-time floors for missing or invalid samples', () => {
const metrics = getStrokeMetrics(
{
vibe: {} as never,
from: [0, 0],
to: [10, 0],
elapsedSeconds: 0,
isErasing: false,
},
gardenAudioConfig.input
);
expect(metrics.elapsedSeconds).toBe(gardenAudioConfig.input.fallbackFrameSeconds);
expect(Number.isFinite(metrics.normalizedSpeed)).toBe(true);
});
});

View file

@ -1,7 +1,8 @@
import type { GardenAudioConfig } from './garden-audio-config';
import type { GardenAudioStroke } from './garden-audio-types'; import type { GardenAudioStroke } from './garden-audio-types';
const fallbackNormalizationPixels = 1000; const fallbackNormalizationPixels = 1000;
const fallbackFrameSeconds = 1 / 60;
const minElapsedSeconds = 0.001;
export interface GardenAudioStrokeMetrics { export interface GardenAudioStrokeMetrics {
distancePixels: number; distancePixels: number;
@ -10,14 +11,11 @@ export interface GardenAudioStrokeMetrics {
normalizedSpeed: number; normalizedSpeed: number;
} }
export const getStrokeMetrics = ( export const getStrokeMetrics = (stroke: GardenAudioStroke): GardenAudioStrokeMetrics => {
stroke: GardenAudioStroke,
inputConfig: GardenAudioConfig['input']
): GardenAudioStrokeMetrics => {
const dx = stroke.to[0] - stroke.from[0]; const dx = stroke.to[0] - stroke.from[0];
const dy = stroke.to[1] - stroke.from[1]; const dy = stroke.to[1] - stroke.from[1];
const distancePixels = Math.hypot(dx, dy); const distancePixels = Math.hypot(dx, dy);
const elapsedSeconds = getElapsedSeconds(stroke, inputConfig); const elapsedSeconds = getElapsedSeconds(stroke);
const normalizedDistance = distancePixels / getStrokeNormalizationPixels(stroke); const normalizedDistance = distancePixels / getStrokeNormalizationPixels(stroke);
return { return {
@ -28,19 +26,16 @@ export const getStrokeMetrics = (
}; };
}; };
const getElapsedSeconds = ( const getElapsedSeconds = (stroke: GardenAudioStroke): number => {
stroke: GardenAudioStroke,
inputConfig: GardenAudioConfig['input']
): number => {
if ( if (
stroke.elapsedSeconds !== undefined && stroke.elapsedSeconds !== undefined &&
Number.isFinite(stroke.elapsedSeconds) && Number.isFinite(stroke.elapsedSeconds) &&
stroke.elapsedSeconds > 0 stroke.elapsedSeconds > 0
) { ) {
return Math.max(inputConfig.minElapsedSeconds, stroke.elapsedSeconds); return Math.max(minElapsedSeconds, stroke.elapsedSeconds);
} }
return inputConfig.fallbackFrameSeconds; return fallbackFrameSeconds;
}; };
const getStrokeNormalizationPixels = (stroke: GardenAudioStroke): number => { const getStrokeNormalizationPixels = (stroke: GardenAudioStroke): number => {

View file

@ -1,9 +1,14 @@
import { VibePreset } from '../vibes'; import type { VibePreset } from '../vibes';
import { import type { GardenAudioChord, GardenAudioVibeProfile } from './garden-audio-config';
GardenAudioChord,
gardenAudioConfig, export const PITCH_SEMITONES_PER_OCTAVE = 12;
GardenAudioVibeProfile,
} from './garden-audio-config'; const chordVoicings = {
majorOpen: [0, 7, 12, 16],
minorOpen: [0, 7, 12, 15],
majorClosed: [0, 4, 7, 12, 16],
minorClosed: [0, 3, 7, 12, 15],
};
export const getVibeProfile = (vibe: VibePreset): GardenAudioVibeProfile => vibe.audio; export const getVibeProfile = (vibe: VibePreset): GardenAudioVibeProfile => vibe.audio;
@ -12,14 +17,12 @@ export const getChordIntervals = (
openVoicing: boolean openVoicing: boolean
): Array<number> => { ): Array<number> => {
if (openVoicing) { if (openVoicing) {
return chord.quality === 'major' return chord.quality === 'major' ? chordVoicings.majorOpen : chordVoicings.minorOpen;
? gardenAudioConfig.generativePiano.chordVoicings.majorOpen
: gardenAudioConfig.generativePiano.chordVoicings.minorOpen;
} }
return chord.quality === 'major' return chord.quality === 'major'
? gardenAudioConfig.generativePiano.chordVoicings.majorClosed ? chordVoicings.majorClosed
: gardenAudioConfig.generativePiano.chordVoicings.minorClosed; : chordVoicings.minorClosed;
}; };
export const degreeToSemitone = ( export const degreeToSemitone = (
@ -29,7 +32,5 @@ export const degreeToSemitone = (
const scaleIndex = const scaleIndex =
((degree % profile.scale.length) + profile.scale.length) % profile.scale.length; ((degree % profile.scale.length) + profile.scale.length) % profile.scale.length;
const octave = Math.floor(degree / profile.scale.length); const octave = Math.floor(degree / profile.scale.length);
return ( return profile.scale[scaleIndex] + octave * PITCH_SEMITONES_PER_OCTAVE;
profile.scale[scaleIndex] + octave * gardenAudioConfig.piano.pitchSemitonesPerOctave
);
}; };

View file

@ -1,326 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { appConfig } from '../config';
import { VIBE_PRESETS } from '../vibes';
import { gardenAudioConfig, GardenAudioConfig } from './garden-audio-config';
type FakeScheduledSourceNode = {
start: ReturnType<typeof vi.fn>;
stop: ReturnType<typeof vi.fn>;
};
const calls = {
constructed: 0,
resumed: 0,
sourcesStarted: 0,
sources: [] as Array<FakeScheduledSourceNode>,
gains: [] as Array<FakeAudioNode>,
};
let contextState: AudioContextState = 'suspended';
let resumeError: Error | null = null;
let ErrorHandler: typeof import('../utils/error-handler').ErrorHandler;
let GardenAudio: typeof import('./garden-audio').GardenAudio;
let loadPianoSamples: typeof import('./piano-samples').loadPianoSamples;
let Severity: typeof import('../utils/error-handler').Severity;
class FakeAudioParam {
public value = 0;
public setTargetAtTime = vi.fn();
public setValueAtTime = vi.fn();
public exponentialRampToValueAtTime = vi.fn();
public cancelScheduledValues = vi.fn();
}
class FakeAudioNode {
public readonly gain = new FakeAudioParam();
public readonly frequency = new FakeAudioParam();
public readonly playbackRate = new FakeAudioParam();
public readonly Q = new FakeAudioParam();
public readonly threshold = new FakeAudioParam();
public readonly knee = new FakeAudioParam();
public readonly ratio = new FakeAudioParam();
public readonly attack = new FakeAudioParam();
public readonly release = new FakeAudioParam();
public readonly delayTime = new FakeAudioParam();
public readonly pan = new FakeAudioParam();
public type = '';
public addEventListener = vi.fn();
public connect = vi.fn();
public disconnect = vi.fn();
}
class FakeAudioBuffer {
private readonly data: Float32Array;
public constructor(length: number) {
this.data = new Float32Array(length);
}
public getChannelData(): Float32Array {
return this.data;
}
}
class FakeAudioContext {
public readonly currentTime = 1;
public readonly sampleRate = 16;
public readonly destination = new FakeAudioNode() as unknown as AudioDestinationNode;
public readonly decodeAudioData = vi.fn(async () => ({}) as AudioBuffer);
public constructor() {
calls.constructed += 1;
}
public get state(): AudioContextState {
return contextState;
}
public set state(state: AudioContextState) {
contextState = state;
}
public createGain(): GainNode {
const node = new FakeAudioNode();
calls.gains.push(node);
return node as unknown as GainNode;
}
public createBiquadFilter(): BiquadFilterNode {
return new FakeAudioNode() as unknown as BiquadFilterNode;
}
public createDelay(): DelayNode {
return new FakeAudioNode() as unknown as DelayNode;
}
public createDynamicsCompressor(): DynamicsCompressorNode {
return new FakeAudioNode() as unknown as DynamicsCompressorNode;
}
public createStereoPanner(): StereoPannerNode {
return new FakeAudioNode() as unknown as StereoPannerNode;
}
public createBuffer(_channels: number, length: number): AudioBuffer {
return new FakeAudioBuffer(length) as unknown as AudioBuffer;
}
public createBufferSource(): AudioBufferSourceNode {
const node = new FakeAudioNode() as unknown as AudioBufferSourceNode & {
buffer: AudioBuffer | null;
start: () => void;
stop: () => void;
};
node.buffer = null;
node.start = vi.fn(() => {
calls.sourcesStarted += 1;
}) as unknown as typeof node.start;
node.stop = vi.fn() as unknown as typeof node.stop;
calls.sources.push(node as unknown as FakeScheduledSourceNode);
return node;
}
public createOscillator(): OscillatorNode {
const node = new FakeAudioNode() as unknown as OscillatorNode & {
start: () => void;
stop: () => void;
};
node.start = vi.fn(() => {
calls.sourcesStarted += 1;
}) as unknown as typeof node.start;
node.stop = vi.fn() as unknown as typeof node.stop;
calls.sources.push(node as unknown as FakeScheduledSourceNode);
return node;
}
public async resume(): Promise<void> {
calls.resumed += 1;
if (resumeError) {
throw resumeError;
}
contextState = 'running';
}
}
const makeConfig = (): GardenAudioConfig => ({
...gardenAudioConfig,
});
describe('GardenAudio startup policy', () => {
beforeEach(async () => {
vi.resetModules();
({ ErrorHandler, Severity } = await import('../utils/error-handler'));
({ GardenAudio } = await import('./garden-audio'));
({ loadPianoSamples } = await import('./piano-samples'));
calls.constructed = 0;
calls.resumed = 0;
calls.sourcesStarted = 0;
calls.sources = [];
calls.gains = [];
contextState = 'suspended';
resumeError = null;
vi.stubGlobal('AudioContext', FakeAudioContext);
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('not loaded in tests')));
});
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it('does not create an AudioContext from passive audio paths', () => {
const audio = new GardenAudio(makeConfig());
const vibe = VIBE_PRESETS[0];
audio.start(vibe);
audio.stroke({
vibe,
from: [0, 0],
to: [12, 0],
isErasing: false,
});
expect(calls.constructed).toBe(0);
});
it('only resumes a suspended context from a user gesture start', () => {
const audio = new GardenAudio(makeConfig());
const vibe = VIBE_PRESETS[0];
audio.start(vibe, { userGesture: true });
expect(calls.constructed).toBe(1);
expect(calls.resumed).toBe(1);
expect(contextState).toBe('running');
contextState = 'suspended';
audio.start(vibe);
audio.setMuted(false);
expect(calls.resumed).toBe(1);
});
it('reports AudioContext resume failures as warnings', async () => {
const audio = new GardenAudio(makeConfig());
const vibe = VIBE_PRESETS[0];
resumeError = new Error('resume rejected');
const addException = vi.spyOn(ErrorHandler, 'addException');
audio.start(vibe, { userGesture: true });
await Promise.resolve();
await Promise.resolve();
expect(addException).toHaveBeenCalledWith(resumeError, {
fallbackMessage: 'Could not resume audio playback.',
severity: Severity.WARNING,
});
});
it('updates live master gain from adjustable volume', () => {
const config = makeConfig();
const audio = new GardenAudio(config);
const vibe = VIBE_PRESETS[0];
audio.start(vibe, { userGesture: true });
const masterGain = calls.gains[0]?.gain;
if (!masterGain) {
throw new Error('Missing fake master gain');
}
audio.setMasterVolume(0.2);
expect(masterGain.setTargetAtTime).toHaveBeenLastCalledWith(
0.2,
1,
config.updateRampSeconds
);
audio.setMuted(true);
const mutedCallCount = masterGain.setTargetAtTime.mock.calls.length;
audio.setMasterVolume(0.8);
expect(masterGain.setTargetAtTime).toHaveBeenCalledTimes(mutedCallCount);
audio.setMuted(false);
expect(masterGain.setTargetAtTime).toHaveBeenLastCalledWith(
0.8,
1,
config.fadeInSeconds
);
});
it('stays silent without piano samples while preserving eraser noise', () => {
const audio = new GardenAudio(makeConfig());
const vibe = VIBE_PRESETS[0];
audio.start(vibe, { userGesture: true });
expect(calls.sourcesStarted).toBe(1);
audio.beginGesture();
audio.stroke({
vibe,
from: [30, 40],
to: [60, 60],
isErasing: false,
elapsedSeconds: 0.05,
});
expect(calls.sourcesStarted).toBe(1);
audio.stroke({
vibe,
from: [60, 60],
to: [75, 80],
isErasing: true,
elapsedSeconds: 0.05,
});
expect(calls.sourcesStarted).toBe(2);
});
it('quickly stops active piano voices when the vibe changes', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => ({
arrayBuffer: async () => new ArrayBuffer(8),
ok: true,
}))
);
await loadPianoSamples(new FakeAudioContext() as unknown as AudioContext);
const audio = new GardenAudio(makeConfig());
const vibe = VIBE_PRESETS[0];
audio.start(vibe, { userGesture: true });
audio.beginGesture();
audio.stroke({
vibe,
from: [30, 40],
to: [90, 40],
elapsedSeconds: 0.05,
isErasing: false,
});
const activePianoSources = calls.sources.filter(
(source) => source.stop.mock.calls.length === 1
);
expect(activePianoSources.length).toBeGreaterThan(0);
const stopCounts = activePianoSources.map((source) => source.stop.mock.calls.length);
audio.changeVibe(VIBE_PRESETS[1], { userGesture: true });
const stoppedVoices = activePianoSources.filter(
(source, index) => source.stop.mock.calls.length === stopCounts[index] + 1
);
expect(stoppedVoices.length).toBeGreaterThan(0);
stoppedVoices.forEach((source) => {
expect(source.stop.mock.calls.at(-1)?.[0]).toBeCloseTo(
1 + appConfig.audio.piano.voiceStealStopSeconds,
3
);
});
});
});

View file

@ -1,7 +1,7 @@
import { clamp01 } from '../utils/clamp';
import { ErrorHandler, Severity } from '../utils/error-handler'; import { ErrorHandler, Severity } from '../utils/error-handler';
import { clamp01 } from '../utils/math';
import type { VibeId, VibePreset } from '../vibes'; import type { VibeId, VibePreset } from '../vibes';
import { GardenAudioConfig } from './garden-audio-config'; import type { GardenAudioConfig } from './garden-audio-config';
import { GardenAudioEnergy } from './garden-audio-energy'; import { GardenAudioEnergy } from './garden-audio-energy';
import { GardenAudioGestureState } from './garden-audio-gesture-state'; import { GardenAudioGestureState } from './garden-audio-gesture-state';
import { GardenAudioGraph } from './garden-audio-graph'; import { GardenAudioGraph } from './garden-audio-graph';
@ -24,6 +24,12 @@ export type {
type AudioLifecycle = 'idle' | 'started' | 'destroyed'; type AudioLifecycle = 'idle' | 'started' | 'destroyed';
const muteGain = 0.0001;
const muteRampSeconds = 0.02;
const brushUpPianoFinishSeconds = 1.2;
const brushUpPianoFadeSeconds = 1.1;
const vibeChangeStingerMinIntervalSeconds = 0.45;
export class GardenAudio { export class GardenAudio {
private readonly graph: GardenAudioGraph; private readonly graph: GardenAudioGraph;
private readonly piano: PianoSampler; private readonly piano: PianoSampler;
@ -36,7 +42,10 @@ export class GardenAudio {
private lifecycle: AudioLifecycle = 'idle'; private lifecycle: AudioLifecycle = 'idle';
private isMuted = false; private isMuted = false;
private isGestureActive = false; private isGestureActive = false;
private isPianoStoppedAfterGesture = false;
private fadePianoAfter: number | null = null;
private masterVolume: number; private masterVolume: number;
private stopPianoAfter: number | null = null;
private lastEraserAt = Number.NEGATIVE_INFINITY; private lastEraserAt = Number.NEGATIVE_INFINITY;
private lastVibeStingerAt = Number.NEGATIVE_INFINITY; private lastVibeStingerAt = Number.NEGATIVE_INFINITY;
@ -44,50 +53,55 @@ export class GardenAudio {
this.masterVolume = clamp01(config.masterVolume); this.masterVolume = clamp01(config.masterVolume);
this.graph = new GardenAudioGraph(config); this.graph = new GardenAudioGraph(config);
this.piano = new PianoSampler(config, this.graph); this.piano = new PianoSampler(config, this.graph);
this.noise = new NoiseBurstPlayer(config, this.graph); this.noise = new NoiseBurstPlayer(this.graph);
this.energy = new GardenAudioEnergy(config); this.energy = new GardenAudioEnergy(config);
this.gestureState = new GardenAudioGestureState(config.input); this.gestureState = new GardenAudioGestureState(config.input);
this.pianoEngine = new GenerativePianoEngine(config, (note) => this.piano.play(note)); this.pianoEngine = new GenerativePianoEngine(config, (note) => this.piano.play(note));
} }
public start(vibe: VibePreset, options: GardenAudioStartOptions = {}): void { public start(vibe: VibePreset, options: GardenAudioStartOptions = {}): void {
if (this.lifecycle === 'destroyed' || this.isMuted) { const isUserGesture = options.userGesture === true;
if (this.lifecycle === 'destroyed') {
return; return;
} }
const context = this.graph.ensureContext(options.userGesture === true); const context = this.graph.ensureContext(isUserGesture);
if (!context) { if (!context) {
return; return;
} }
const startupRampSeconds = const startupRampSeconds = isUserGesture
options.userGesture === true ? muteRampSeconds
? this.config.muteRampSeconds
: this.config.fadeInSeconds; : this.config.fadeInSeconds;
const needsResume = context.state !== 'running' && context.state !== 'closed'; const needsResume = context.state !== 'running' && context.state !== 'closed';
let resumePromise: Promise<void> | null = null; let resumePromise: Promise<void> | null = null;
if (isUserGesture) {
this.graph.startMediaElementOutput();
this.graph.unlock();
}
if (needsResume) { if (needsResume) {
if (options.userGesture !== true) { if (!isUserGesture) {
return; return;
} }
resumePromise = context.resume(); resumePromise = context.resume();
} }
if (options.userGesture === true) { if (isUserGesture) {
this.graph.unlock(); this.graph.unlock();
} }
if (resumePromise) { if (resumePromise) {
void resumePromise void resumePromise
.then(() => { .then(() => {
if ( if (this.graph.context === context && this.lifecycle !== 'destroyed') {
this.graph.context === context &&
this.lifecycle !== 'destroyed' &&
!this.isMuted
) {
this.graph.unlock(); this.graph.unlock();
this.graph.setMasterGain(this.masterVolume, startupRampSeconds); this.completeStart(vibe, {
context,
startupRampSeconds,
});
} }
}) })
.catch((error) => { .catch((error) => {
@ -96,6 +110,32 @@ export class GardenAudio {
severity: Severity.WARNING, severity: Severity.WARNING,
}); });
}); });
return;
}
this.completeStart(vibe, {
context,
startupRampSeconds,
});
}
private completeStart(
vibe: VibePreset,
{
context,
startupRampSeconds,
}: {
context: AudioContext;
startupRampSeconds: number;
}
): void {
if (this.graph.context !== context || this.lifecycle === 'destroyed') {
return;
}
if (this.isMuted) {
this.graph.setMasterGain(muteGain, muteRampSeconds);
return;
} }
this.lifecycle = 'started'; this.lifecycle = 'started';
@ -111,7 +151,12 @@ export class GardenAudio {
this.pianoEngine.cue(context.currentTime); this.pianoEngine.cue(context.currentTime);
} }
}) })
.catch(() => undefined); .catch((error) => {
ErrorHandler.addException(error, {
fallbackMessage: 'Could not load piano samples. Using synthesized audio.',
severity: Severity.WARNING,
});
});
} }
} }
@ -143,8 +188,8 @@ export class GardenAudio {
this.isMuted = isMuted; this.isMuted = isMuted;
this.graph.setMasterGain( this.graph.setMasterGain(
isMuted ? this.config.muteGain : this.masterVolume, isMuted ? muteGain : this.masterVolume,
isMuted ? this.config.muteRampSeconds : this.config.fadeInSeconds isMuted ? muteRampSeconds : this.config.fadeInSeconds
); );
} }
@ -162,6 +207,9 @@ export class GardenAudio {
} }
this.isGestureActive = true; this.isGestureActive = true;
this.isPianoStoppedAfterGesture = false;
this.fadePianoAfter = null;
this.stopPianoAfter = null;
this.gestureState.beginGesture(); this.gestureState.beginGesture();
this.energy.beginGesture(context.currentTime); this.energy.beginGesture(context.currentTime);
this.pianoEngine.beginGesture(); this.pianoEngine.beginGesture();
@ -170,6 +218,12 @@ export class GardenAudio {
public endGesture(): void { public endGesture(): void {
this.gestureState.endGesture(); this.gestureState.endGesture();
this.isGestureActive = false; this.isGestureActive = false;
const context = this.graph.context;
this.isPianoStoppedAfterGesture = true;
this.fadePianoAfter = context
? context.currentTime + brushUpPianoFinishSeconds
: null;
this.stopPianoAfter = null;
this.energy.endGesture(); this.energy.endGesture();
this.pianoEngine.endGesture(); this.pianoEngine.endGesture();
} }
@ -187,6 +241,21 @@ export class GardenAudio {
this.energy.silence(); this.energy.silence();
} }
if (!this.isGestureActive && this.isPianoStoppedAfterGesture) {
if (this.fadePianoAfter !== null && context.currentTime >= this.fadePianoAfter) {
this.piano.fadeAll(brushUpPianoFadeSeconds);
this.fadePianoAfter = null;
this.stopPianoAfter = context.currentTime + brushUpPianoFadeSeconds;
}
if (this.stopPianoAfter !== null && context.currentTime >= this.stopPianoAfter) {
this.piano.stopAll();
this.pianoEngine.reset();
this.stopPianoAfter = null;
}
this.updateDelay(snapshot);
return;
}
this.pianoEngine.renderLookahead({ this.pianoEngine.renderLookahead({
vibe: snapshot.vibe, vibe: snapshot.vibe,
now: context.currentTime, now: context.currentTime,
@ -211,7 +280,7 @@ export class GardenAudio {
return; return;
} }
const metrics = getStrokeMetrics(stroke, this.config.input); const metrics = getStrokeMetrics(stroke);
const now = context.currentTime; const now = context.currentTime;
const frame = this.gestureState.recordStroke({ metrics }); const frame = this.gestureState.recordStroke({ metrics });
@ -242,6 +311,9 @@ export class GardenAudio {
this.pianoEngine.reset(); this.pianoEngine.reset();
this.currentVibeId = null; this.currentVibeId = null;
this.isGestureActive = false; this.isGestureActive = false;
this.isPianoStoppedAfterGesture = false;
this.fadePianoAfter = null;
this.stopPianoAfter = null;
this.lastEraserAt = Number.NEGATIVE_INFINITY; this.lastEraserAt = Number.NEGATIVE_INFINITY;
this.lastVibeStingerAt = Number.NEGATIVE_INFINITY; this.lastVibeStingerAt = Number.NEGATIVE_INFINITY;
} }
@ -253,7 +325,7 @@ export class GardenAudio {
} }
const now = context.currentTime; const now = context.currentTime;
if (now - this.lastVibeStingerAt < this.config.vibeChangeStingerMinIntervalSeconds) { if (now - this.lastVibeStingerAt < vibeChangeStingerMinIntervalSeconds) {
return; return;
} }

Some files were not shown because too many files have changed in this diff Show more