,
This commit is contained in:
parent
70423851ba
commit
1fe5015056
55 changed files with 2036 additions and 685 deletions
2
definitions.d.ts
vendored
2
definitions.d.ts
vendored
|
|
@ -6,3 +6,5 @@ declare module '*.wgsl?raw' {
|
||||||
interface HTMLCanvasElement {
|
interface HTMLCanvasElement {
|
||||||
getContext(contextId: 'webgpu'): GPUCanvasContext | null;
|
getContext(contextId: 'webgpu'): GPUCanvasContext | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
declare var webkitOfflineAudioContext: typeof OfflineAudioContext | undefined;
|
||||||
|
|
|
||||||
7
package-lock.json
generated
7
package-lock.json
generated
|
|
@ -9,6 +9,7 @@
|
||||||
"version": "0.2.0",
|
"version": "0.2.0",
|
||||||
"license": "Unlicense",
|
"license": "Unlicense",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@plausible-analytics/tracker": "^0.4.5",
|
||||||
"tweakpane": "^4.0.5"
|
"tweakpane": "^4.0.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|
@ -1936,6 +1937,12 @@
|
||||||
"url": "https://opencollective.com/pkgr"
|
"url": "https://opencollective.com/pkgr"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@plausible-analytics/tracker": {
|
||||||
|
"version": "0.4.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@plausible-analytics/tracker/-/tracker-0.4.5.tgz",
|
||||||
|
"integrity": "sha512-6BfAGejXY+YA3Cw6LYT2Zpn4hTxDtPQAawFsYUsQCOg78wIS5C4deAGXTfJffa5VleMWITv5lpJ/EYuQBl1tPA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@playwright/test": {
|
"node_modules/@playwright/test": {
|
||||||
"version": "1.60.0",
|
"version": "1.60.0",
|
||||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz",
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz",
|
||||||
|
|
|
||||||
|
|
@ -68,6 +68,7 @@
|
||||||
"vitest": "^4.1.5"
|
"vitest": "^4.1.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@plausible-analytics/tracker": "^0.4.5",
|
||||||
"tweakpane": "^4.0.5"
|
"tweakpane": "^4.0.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ export default defineConfig({
|
||||||
webServer: {
|
webServer: {
|
||||||
command: `npm run preview -- --host 127.0.0.1 --port ${port}`,
|
command: `npm run preview -- --host 127.0.0.1 --port ${port}`,
|
||||||
ignoreHTTPSErrors: true,
|
ignoreHTTPSErrors: true,
|
||||||
reuseExistingServer: !isCi,
|
reuseExistingServer: false,
|
||||||
timeout: 120_000,
|
timeout: 120_000,
|
||||||
url: baseURL,
|
url: baseURL,
|
||||||
},
|
},
|
||||||
|
|
|
||||||
69
src/analytics.ts
Normal file
69
src/analytics.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
import {
|
||||||
|
init as plausibleInit,
|
||||||
|
track as plausibleTrack,
|
||||||
|
type PlausibleEventOptions,
|
||||||
|
} from '@plausible-analytics/tracker';
|
||||||
|
|
||||||
|
let isInitialized = false;
|
||||||
|
|
||||||
|
const track = (eventName: string, options: PlausibleEventOptions = {}) => {
|
||||||
|
try {
|
||||||
|
plausibleTrack(eventName, options);
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`Could not track analytics event "${eventName}".`, error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const initAnalytics = () => {
|
||||||
|
if (isInitialized) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
plausibleInit({
|
||||||
|
domain: 'schmelczer.dev/floating',
|
||||||
|
endpoint: 'https://stats.schmelczer.dev/status',
|
||||||
|
autoCapturePageviews: true,
|
||||||
|
captureOnLocalhost: true,
|
||||||
|
logging: true,
|
||||||
|
fileDownloads: true,
|
||||||
|
outboundLinks: true,
|
||||||
|
hashBasedRouting: true,
|
||||||
|
});
|
||||||
|
isInitialized = true;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Could not initialize analytics.', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const trackVibeChange = ({
|
||||||
|
vibeId,
|
||||||
|
vibeName,
|
||||||
|
source,
|
||||||
|
}: {
|
||||||
|
vibeId: string;
|
||||||
|
vibeName: string;
|
||||||
|
source: string;
|
||||||
|
}) => {
|
||||||
|
track('Vibe Change', {
|
||||||
|
props: {
|
||||||
|
vibeId,
|
||||||
|
vibeName,
|
||||||
|
source,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const trackExport = ({ vibeId }: { vibeId: string }) => {
|
||||||
|
track('Export', {
|
||||||
|
props: {
|
||||||
|
format: 'png',
|
||||||
|
resolution: '4k',
|
||||||
|
vibeId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const trackSettingsOpen = () => {
|
||||||
|
track('Settings Open');
|
||||||
|
};
|
||||||
|
|
@ -26,14 +26,6 @@ export interface GardenAudioConfig {
|
||||||
fadeInSeconds: number;
|
fadeInSeconds: number;
|
||||||
updateRampSeconds: number;
|
updateRampSeconds: number;
|
||||||
highPassFrequencyHz: number;
|
highPassFrequencyHz: number;
|
||||||
fallbackVibeId: string;
|
|
||||||
compressor: {
|
|
||||||
thresholdDb: number;
|
|
||||||
kneeDb: number;
|
|
||||||
ratio: number;
|
|
||||||
attackSeconds: number;
|
|
||||||
releaseSeconds: number;
|
|
||||||
};
|
|
||||||
delay: {
|
delay: {
|
||||||
timeSeconds: number;
|
timeSeconds: number;
|
||||||
feedback: number;
|
feedback: number;
|
||||||
|
|
@ -47,9 +39,6 @@ export interface GardenAudioConfig {
|
||||||
releaseSeconds: number;
|
releaseSeconds: number;
|
||||||
lowpassHz: number;
|
lowpassHz: number;
|
||||||
};
|
};
|
||||||
input: {
|
|
||||||
pressureFallback: number;
|
|
||||||
};
|
|
||||||
rhythm: {
|
rhythm: {
|
||||||
bpm: number;
|
bpm: number;
|
||||||
stepsPerBeat: number;
|
stepsPerBeat: number;
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,9 @@ import type { GardenAudioEngineConfig } from '../config';
|
||||||
import { clamp } from '../utils/clamp';
|
import { clamp } from '../utils/clamp';
|
||||||
import { GardenAudioConfig, GardenAudioVibeProfile } from './garden-audio-config';
|
import { GardenAudioConfig, GardenAudioVibeProfile } from './garden-audio-config';
|
||||||
|
|
||||||
|
const UNLOCK_TICK_SECONDS = 0.035;
|
||||||
|
const UNLOCK_TICK_FREQUENCY_HZ = 440;
|
||||||
|
|
||||||
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;
|
||||||
|
|
@ -12,7 +15,6 @@ 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 hasUnlocked = false;
|
|
||||||
|
|
||||||
public constructor(
|
public constructor(
|
||||||
private readonly config: GardenAudioConfig,
|
private readonly config: GardenAudioConfig,
|
||||||
|
|
@ -28,23 +30,26 @@ export class GardenAudioGraph {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const context = new AudioContext({ latencyHint: 'interactive' });
|
const AudioContextConstructor = globalThis.AudioContext;
|
||||||
|
if (!AudioContextConstructor) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
let context: AudioContext;
|
||||||
|
try {
|
||||||
|
context = new AudioContextConstructor({ latencyHint: 'interactive' });
|
||||||
|
} catch {
|
||||||
|
context = new AudioContextConstructor();
|
||||||
|
}
|
||||||
const masterGain = context.createGain();
|
const masterGain = context.createGain();
|
||||||
const highPass = context.createBiquadFilter();
|
const highPass = context.createBiquadFilter();
|
||||||
const compressor = context.createDynamicsCompressor();
|
|
||||||
|
|
||||||
masterGain.gain.value = 0;
|
masterGain.gain.value = 0;
|
||||||
highPass.type = 'highpass';
|
highPass.type = 'highpass';
|
||||||
highPass.frequency.value = this.config.highPassFrequencyHz;
|
highPass.frequency.value = this.config.highPassFrequencyHz;
|
||||||
compressor.threshold.value = this.config.compressor.thresholdDb;
|
|
||||||
compressor.knee.value = this.config.compressor.kneeDb;
|
|
||||||
compressor.ratio.value = this.config.compressor.ratio;
|
|
||||||
compressor.attack.value = this.config.compressor.attackSeconds;
|
|
||||||
compressor.release.value = this.config.compressor.releaseSeconds;
|
|
||||||
|
|
||||||
masterGain.connect(highPass);
|
masterGain.connect(highPass);
|
||||||
highPass.connect(compressor);
|
highPass.connect(context.destination);
|
||||||
compressor.connect(context.destination);
|
|
||||||
|
|
||||||
this.context = context;
|
this.context = context;
|
||||||
this.masterGain = masterGain;
|
this.masterGain = masterGain;
|
||||||
|
|
@ -55,24 +60,37 @@ export class GardenAudioGraph {
|
||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
// iOS WebKit (Safari + Chrome iOS) only fully unlocks audio output once
|
// iOS WebKit can report "running" while the hardware output is still silent.
|
||||||
// a buffer source has been started inside a user-gesture handler. Calling
|
// A very short, nearly inaudible oscillator in the gesture stack is more
|
||||||
// resume() alone leaves the context "running" but silent.
|
// reliable than a fully silent buffer on recent Safari versions.
|
||||||
public unlock(): void {
|
public unlock(): void {
|
||||||
if (!this.context || this.hasUnlocked) {
|
if (!this.context) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const buffer = this.context.createBuffer(
|
const now = this.context.currentTime;
|
||||||
1,
|
const source = this.context.createOscillator();
|
||||||
this.engineConfig.graph.unlockBufferLength,
|
const gain = this.context.createGain();
|
||||||
this.engineConfig.graph.unlockSampleRate
|
|
||||||
|
source.type = 'sine';
|
||||||
|
source.frequency.setValueAtTime(UNLOCK_TICK_FREQUENCY_HZ, now);
|
||||||
|
gain.gain.setValueAtTime(this.engineConfig.piano.minGain, now);
|
||||||
|
gain.gain.exponentialRampToValueAtTime(
|
||||||
|
this.engineConfig.piano.minGain,
|
||||||
|
now + UNLOCK_TICK_SECONDS
|
||||||
|
);
|
||||||
|
source.connect(gain);
|
||||||
|
gain.connect(this.context.destination);
|
||||||
|
source.start(now);
|
||||||
|
source.stop(now + UNLOCK_TICK_SECONDS);
|
||||||
|
source.addEventListener(
|
||||||
|
'ended',
|
||||||
|
() => {
|
||||||
|
source.disconnect();
|
||||||
|
gain.disconnect();
|
||||||
|
},
|
||||||
|
{ once: true }
|
||||||
);
|
);
|
||||||
const source = this.context.createBufferSource();
|
|
||||||
source.buffer = buffer;
|
|
||||||
source.connect(this.context.destination);
|
|
||||||
source.start(0);
|
|
||||||
this.hasUnlocked = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public setMasterGain(targetGain: number, timeConstantSeconds: number): void {
|
public setMasterGain(targetGain: number, timeConstantSeconds: number): void {
|
||||||
|
|
@ -201,6 +219,5 @@ export class GardenAudioGraph {
|
||||||
this.delayNode = null;
|
this.delayNode = null;
|
||||||
this.delayFeedback = null;
|
this.delayFeedback = null;
|
||||||
this.delayOutput = null;
|
this.delayOutput = null;
|
||||||
this.hasUnlocked = false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,14 +13,13 @@ export interface GardenAudioStrokeMetrics {
|
||||||
export const getStrokeMetrics = (
|
export const getStrokeMetrics = (
|
||||||
stroke: GardenAudioStroke,
|
stroke: GardenAudioStroke,
|
||||||
speedForFullEnergyPixelsPerSecond: number,
|
speedForFullEnergyPixelsPerSecond: number,
|
||||||
fallbackPressure: number,
|
|
||||||
inputConfig: GardenAudioEngineConfig['input']
|
inputConfig: GardenAudioEngineConfig['input']
|
||||||
): GardenAudioStrokeMetrics => {
|
): 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 speedPixelsPerSecond = getStrokeVelocity(stroke, distancePixels, inputConfig);
|
const speedPixelsPerSecond = getStrokeVelocity(stroke, distancePixels, inputConfig);
|
||||||
const pressure = getPressureAmount(stroke, fallbackPressure, inputConfig);
|
const pressure = getPressureAmount(stroke);
|
||||||
const speedAmount = clamp01(speedPixelsPerSecond / speedForFullEnergyPixelsPerSecond);
|
const speedAmount = clamp01(speedPixelsPerSecond / speedForFullEnergyPixelsPerSecond);
|
||||||
const strokeEnergy = clamp01(
|
const strokeEnergy = clamp01(
|
||||||
inputConfig.strokeEnergyBase +
|
inputConfig.strokeEnergyBase +
|
||||||
|
|
@ -58,11 +57,7 @@ const getStrokeVelocity = (
|
||||||
return distancePixels / inputConfig.fallbackFrameSeconds;
|
return distancePixels / inputConfig.fallbackFrameSeconds;
|
||||||
};
|
};
|
||||||
|
|
||||||
const getPressureAmount = (
|
const getPressureAmount = (stroke: GardenAudioStroke): number => {
|
||||||
stroke: GardenAudioStroke,
|
|
||||||
fallbackPressure: number,
|
|
||||||
inputConfig: GardenAudioEngineConfig['input']
|
|
||||||
): number => {
|
|
||||||
if (
|
if (
|
||||||
stroke.pressure !== undefined &&
|
stroke.pressure !== undefined &&
|
||||||
Number.isFinite(stroke.pressure) &&
|
Number.isFinite(stroke.pressure) &&
|
||||||
|
|
@ -71,7 +66,5 @@ const getPressureAmount = (
|
||||||
return clamp01(stroke.pressure);
|
return clamp01(stroke.pressure);
|
||||||
}
|
}
|
||||||
|
|
||||||
return stroke.pointerType === 'pen'
|
return 0;
|
||||||
? Math.max(inputConfig.penMinPressure, clamp01(fallbackPressure))
|
|
||||||
: clamp01(fallbackPressure);
|
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -12,10 +12,14 @@ export const normalizeColorIndex = (index: number): GardenAudioColorIndex =>
|
||||||
export const getVibeProfile = (
|
export const getVibeProfile = (
|
||||||
config: GardenAudioConfig,
|
config: GardenAudioConfig,
|
||||||
vibe: VibePreset
|
vibe: VibePreset
|
||||||
): GardenAudioVibeProfile =>
|
): GardenAudioVibeProfile => {
|
||||||
config.vibes[vibe.id] ??
|
const profile = config.vibes[vibe.id];
|
||||||
config.vibes[config.fallbackVibeId] ??
|
if (!profile) {
|
||||||
Object.values(config.vibes)[0];
|
throw new Error(`Missing audio profile for vibe "${vibe.id}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return profile;
|
||||||
|
};
|
||||||
|
|
||||||
export const getChordIntervals = (
|
export const getChordIntervals = (
|
||||||
chord: GardenAudioChord,
|
chord: GardenAudioChord,
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,6 @@ export interface GardenAudioStroke {
|
||||||
elapsedSeconds?: number;
|
elapsedSeconds?: number;
|
||||||
eraserSizePixels?: number;
|
eraserSizePixels?: number;
|
||||||
mirrorSegmentCount?: number;
|
mirrorSegmentCount?: number;
|
||||||
pointerType?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GardenAudioTouchDown {
|
export interface GardenAudioTouchDown {
|
||||||
|
|
@ -31,7 +30,6 @@ export interface GardenAudioTouchDown {
|
||||||
canvasSize?: ArrayLike<number>;
|
canvasSize?: ArrayLike<number>;
|
||||||
mirrorSegmentCount?: number;
|
mirrorSegmentCount?: number;
|
||||||
pressure?: number;
|
pressure?: number;
|
||||||
pointerType?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GardenAudioStartOptions {
|
export interface GardenAudioStartOptions {
|
||||||
|
|
@ -45,7 +43,7 @@ export interface LoadedPianoSample {
|
||||||
|
|
||||||
export interface ActivePianoVoice {
|
export interface ActivePianoVoice {
|
||||||
gain: GainNode;
|
gain: GainNode;
|
||||||
source: AudioBufferSourceNode;
|
source: AudioScheduledSourceNode;
|
||||||
startAt: number;
|
startAt: number;
|
||||||
stopAt: number;
|
stopAt: number;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,26 @@
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import { appConfig } from '../config';
|
import { appConfig } from '../config';
|
||||||
|
import { ErrorHandler, Severity } from '../utils/error-handler';
|
||||||
import { VIBE_PRESETS } from '../vibes';
|
import { VIBE_PRESETS } from '../vibes';
|
||||||
import { GardenAudio } from './garden-audio';
|
import { GardenAudio } from './garden-audio';
|
||||||
import { gardenAudioConfig, GardenAudioConfig } from './garden-audio-config';
|
import { gardenAudioConfig, GardenAudioConfig } from './garden-audio-config';
|
||||||
|
import { loadPianoSamples, resetPianoSampleCacheForTest } from './piano-samples';
|
||||||
|
|
||||||
|
type FakeScheduledSourceNode = {
|
||||||
|
start: ReturnType<typeof vi.fn>;
|
||||||
|
stop: ReturnType<typeof vi.fn>;
|
||||||
|
};
|
||||||
|
|
||||||
const calls = {
|
const calls = {
|
||||||
constructed: 0,
|
constructed: 0,
|
||||||
resumed: 0,
|
resumed: 0,
|
||||||
sourcesStarted: 0,
|
sourcesStarted: 0,
|
||||||
|
sources: [] as Array<FakeScheduledSourceNode>,
|
||||||
};
|
};
|
||||||
|
|
||||||
let contextState: AudioContextState = 'suspended';
|
let contextState: AudioContextState = 'suspended';
|
||||||
|
let resumeError: Error | null = null;
|
||||||
|
|
||||||
class FakeAudioParam {
|
class FakeAudioParam {
|
||||||
public value = 0;
|
public value = 0;
|
||||||
|
|
@ -24,6 +33,7 @@ class FakeAudioParam {
|
||||||
class FakeAudioNode {
|
class FakeAudioNode {
|
||||||
public readonly gain = new FakeAudioParam();
|
public readonly gain = new FakeAudioParam();
|
||||||
public readonly frequency = new FakeAudioParam();
|
public readonly frequency = new FakeAudioParam();
|
||||||
|
public readonly playbackRate = new FakeAudioParam();
|
||||||
public readonly Q = new FakeAudioParam();
|
public readonly Q = new FakeAudioParam();
|
||||||
public readonly threshold = new FakeAudioParam();
|
public readonly threshold = new FakeAudioParam();
|
||||||
public readonly knee = new FakeAudioParam();
|
public readonly knee = new FakeAudioParam();
|
||||||
|
|
@ -54,6 +64,7 @@ class FakeAudioContext {
|
||||||
public readonly currentTime = 1;
|
public readonly currentTime = 1;
|
||||||
public readonly sampleRate = 16;
|
public readonly sampleRate = 16;
|
||||||
public readonly destination = new FakeAudioNode() as unknown as AudioDestinationNode;
|
public readonly destination = new FakeAudioNode() as unknown as AudioDestinationNode;
|
||||||
|
public readonly decodeAudioData = vi.fn(async () => ({}) as AudioBuffer);
|
||||||
|
|
||||||
public constructor() {
|
public constructor() {
|
||||||
calls.constructed += 1;
|
calls.constructed += 1;
|
||||||
|
|
@ -75,10 +86,6 @@ class FakeAudioContext {
|
||||||
return new FakeAudioNode() as unknown as BiquadFilterNode;
|
return new FakeAudioNode() as unknown as BiquadFilterNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
public createDynamicsCompressor(): DynamicsCompressorNode {
|
|
||||||
return new FakeAudioNode() as unknown as DynamicsCompressorNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public createDelay(): DelayNode {
|
public createDelay(): DelayNode {
|
||||||
return new FakeAudioNode() as unknown as DelayNode;
|
return new FakeAudioNode() as unknown as DelayNode;
|
||||||
}
|
}
|
||||||
|
|
@ -100,13 +107,30 @@ class FakeAudioContext {
|
||||||
node.buffer = null;
|
node.buffer = null;
|
||||||
node.start = vi.fn(() => {
|
node.start = vi.fn(() => {
|
||||||
calls.sourcesStarted += 1;
|
calls.sourcesStarted += 1;
|
||||||
});
|
}) as unknown as typeof node.start;
|
||||||
node.stop = vi.fn();
|
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;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async resume(): Promise<void> {
|
public async resume(): Promise<void> {
|
||||||
calls.resumed += 1;
|
calls.resumed += 1;
|
||||||
|
if (resumeError) {
|
||||||
|
throw resumeError;
|
||||||
|
}
|
||||||
contextState = 'running';
|
contextState = 'running';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -120,13 +144,18 @@ describe('GardenAudio startup policy', () => {
|
||||||
calls.constructed = 0;
|
calls.constructed = 0;
|
||||||
calls.resumed = 0;
|
calls.resumed = 0;
|
||||||
calls.sourcesStarted = 0;
|
calls.sourcesStarted = 0;
|
||||||
|
calls.sources = [];
|
||||||
contextState = 'suspended';
|
contextState = 'suspended';
|
||||||
|
resumeError = null;
|
||||||
|
resetPianoSampleCacheForTest();
|
||||||
vi.stubGlobal('AudioContext', FakeAudioContext);
|
vi.stubGlobal('AudioContext', FakeAudioContext);
|
||||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('not loaded in tests')));
|
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('not loaded in tests')));
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
vi.unstubAllGlobals();
|
vi.unstubAllGlobals();
|
||||||
|
resetPianoSampleCacheForTest();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('does not create an AudioContext from passive audio paths', () => {
|
it('does not create an AudioContext from passive audio paths', () => {
|
||||||
|
|
@ -171,7 +200,27 @@ describe('GardenAudio startup policy', () => {
|
||||||
expect(calls.resumed).toBe(1);
|
expect(calls.resumed).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('skips cold piano fallback while preserving eraser noise', () => {
|
it('reports AudioContext resume failures as warnings', async () => {
|
||||||
|
const audio = new GardenAudio(
|
||||||
|
makeConfig(),
|
||||||
|
appConfig.audioEngine,
|
||||||
|
appConfig.simulation.maxMirrorSegmentCount
|
||||||
|
);
|
||||||
|
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('stays silent without piano samples while preserving eraser noise', () => {
|
||||||
const audio = new GardenAudio(
|
const audio = new GardenAudio(
|
||||||
makeConfig(),
|
makeConfig(),
|
||||||
appConfig.audioEngine,
|
appConfig.audioEngine,
|
||||||
|
|
@ -217,4 +266,51 @@ describe('GardenAudio startup policy', () => {
|
||||||
|
|
||||||
expect(calls.sourcesStarted).toBe(2);
|
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(),
|
||||||
|
appConfig.audioEngine,
|
||||||
|
appConfig.simulation.maxMirrorSegmentCount
|
||||||
|
);
|
||||||
|
const vibe = VIBE_PRESETS[0];
|
||||||
|
|
||||||
|
audio.start(vibe, { userGesture: true });
|
||||||
|
audio.beginGesture();
|
||||||
|
audio.touchDown({
|
||||||
|
vibe,
|
||||||
|
colorIndex: 1,
|
||||||
|
position: [30, 40],
|
||||||
|
canvasSize: [100, 100],
|
||||||
|
pressure: 0.7,
|
||||||
|
});
|
||||||
|
|
||||||
|
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.audioEngine.piano.voiceStealStopSeconds,
|
||||||
|
3
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import type { GardenAudioEngineConfig } from '../config';
|
import type { GardenAudioEngineConfig } from '../config';
|
||||||
import { clamp, clamp01 } from '../utils/clamp';
|
import { clamp, clamp01 } from '../utils/clamp';
|
||||||
|
import { ErrorHandler, Severity } from '../utils/error-handler';
|
||||||
import { VibePreset } from '../vibes';
|
import { VibePreset } from '../vibes';
|
||||||
import { GardenAudioConfig } from './garden-audio-config';
|
import { GardenAudioConfig } from './garden-audio-config';
|
||||||
import { GardenAudioEnergy } from './garden-audio-energy';
|
import { GardenAudioEnergy } from './garden-audio-energy';
|
||||||
|
|
@ -71,40 +72,66 @@ export class GardenAudio {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const startupRampSeconds =
|
||||||
|
options.userGesture === true
|
||||||
|
? this.engineConfig.muteRampSeconds
|
||||||
|
: this.config.fadeInSeconds;
|
||||||
|
const needsResume = context.state !== 'running' && context.state !== 'closed';
|
||||||
|
let resumePromise: Promise<void> | null = null;
|
||||||
|
|
||||||
|
if (needsResume) {
|
||||||
|
if (options.userGesture !== true) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
resumePromise = context.resume();
|
||||||
|
}
|
||||||
|
|
||||||
if (options.userGesture === true) {
|
if (options.userGesture === true) {
|
||||||
this.graph.unlock();
|
this.graph.unlock();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (context.state === 'suspended') {
|
if (resumePromise) {
|
||||||
if (options.userGesture !== true) {
|
void resumePromise
|
||||||
return;
|
.then(() => {
|
||||||
}
|
if (this.graph.context === context && !this.isDestroyed && !this.isMuted) {
|
||||||
void context.resume().catch(() => undefined);
|
this.graph.unlock();
|
||||||
|
this.graph.setMasterGain(this.config.masterVolume, startupRampSeconds);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
ErrorHandler.addException(error, {
|
||||||
|
fallbackMessage: 'Could not resume audio playback.',
|
||||||
|
severity: Severity.WARNING,
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
this.hasStarted = true;
|
this.hasStarted = true;
|
||||||
this.applyVibe(vibe);
|
this.applyVibe(vibe);
|
||||||
this.pianoEngine.prime(context.currentTime);
|
this.pianoEngine.prime(context.currentTime);
|
||||||
this.graph.setMasterGain(
|
this.graph.setMasterGain(this.config.masterVolume, startupRampSeconds);
|
||||||
this.config.masterVolume,
|
|
||||||
options.userGesture === true
|
|
||||||
? this.engineConfig.muteRampSeconds
|
|
||||||
: this.config.fadeInSeconds
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!this.hasQueuedPianoLoad) {
|
if (!this.hasQueuedPianoLoad) {
|
||||||
this.hasQueuedPianoLoad = true;
|
this.hasQueuedPianoLoad = true;
|
||||||
void this.piano.load(context).then(() => {
|
void this.piano
|
||||||
if (this.graph.context === context && !this.isDestroyed) {
|
.load(context)
|
||||||
this.pianoEngine.cue(context.currentTime);
|
.then(() => {
|
||||||
}
|
if (this.graph.context === context && !this.isDestroyed) {
|
||||||
});
|
this.pianoEngine.cue(context.currentTime);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public changeVibe(vibe: VibePreset, options: GardenAudioStartOptions = {}): void {
|
public changeVibe(vibe: VibePreset, options: GardenAudioStartOptions = {}): void {
|
||||||
const previousVibeId = this.currentVibeId;
|
const previousVibeId = this.currentVibeId;
|
||||||
this.start(vibe, options);
|
this.start(vibe, options);
|
||||||
|
const didChangeVibe = previousVibeId !== null && previousVibeId !== vibe.id;
|
||||||
|
|
||||||
|
if (didChangeVibe) {
|
||||||
|
this.piano.stopAll();
|
||||||
|
}
|
||||||
|
|
||||||
const context = this.graph.context;
|
const context = this.graph.context;
|
||||||
if (
|
if (
|
||||||
|
|
@ -112,8 +139,7 @@ export class GardenAudio {
|
||||||
(context.state === 'running' || options.userGesture === true) &&
|
(context.state === 'running' || options.userGesture === true) &&
|
||||||
!this.isMuted &&
|
!this.isMuted &&
|
||||||
!this.isDestroyed &&
|
!this.isDestroyed &&
|
||||||
previousVibeId !== null &&
|
didChangeVibe
|
||||||
previousVibeId !== vibe.id
|
|
||||||
) {
|
) {
|
||||||
this.playVibeChangeStinger(vibe);
|
this.playVibeChangeStinger(vibe);
|
||||||
}
|
}
|
||||||
|
|
@ -158,7 +184,7 @@ export class GardenAudio {
|
||||||
|
|
||||||
this.selectedColorIndex = normalizeColorIndex(touch.colorIndex);
|
this.selectedColorIndex = normalizeColorIndex(touch.colorIndex);
|
||||||
const mirrorAmount = this.getMirrorAmount(touch.mirrorSegmentCount ?? 1);
|
const mirrorAmount = this.getMirrorAmount(touch.mirrorSegmentCount ?? 1);
|
||||||
const pressure = this.getTouchPressure(touch.pressure, touch.pointerType);
|
const pressure = this.getPressure(touch.pressure);
|
||||||
const strength = clamp01(0.36 + pressure * 0.34 + mirrorAmount * 0.22);
|
const strength = clamp01(0.36 + pressure * 0.34 + mirrorAmount * 0.22);
|
||||||
const frame = this.gestureState.recordTouchDown({
|
const frame = this.gestureState.recordTouchDown({
|
||||||
touch,
|
touch,
|
||||||
|
|
@ -225,7 +251,6 @@ export class GardenAudio {
|
||||||
const metrics = getStrokeMetrics(
|
const metrics = getStrokeMetrics(
|
||||||
stroke,
|
stroke,
|
||||||
this.config.rhythm.speedForFullEnergyPixelsPerSecond,
|
this.config.rhythm.speedForFullEnergyPixelsPerSecond,
|
||||||
this.config.input.pressureFallback,
|
|
||||||
this.engineConfig.input
|
this.engineConfig.input
|
||||||
);
|
);
|
||||||
const now = context.currentTime;
|
const now = context.currentTime;
|
||||||
|
|
@ -375,16 +400,11 @@ export class GardenAudio {
|
||||||
return clamp01((segmentCount - 1) / (maxMirrorSegmentCount - 1));
|
return clamp01((segmentCount - 1) / (maxMirrorSegmentCount - 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
private getTouchPressure(pressure: number | undefined, pointerType?: string): number {
|
private getPressure(pressure: number | undefined): number {
|
||||||
if (pressure !== undefined && Number.isFinite(pressure) && pressure > 0) {
|
if (pressure !== undefined && Number.isFinite(pressure) && pressure > 0) {
|
||||||
return clamp01(pressure);
|
return clamp01(pressure);
|
||||||
}
|
}
|
||||||
|
|
||||||
return pointerType === 'pen'
|
return 0;
|
||||||
? Math.max(
|
|
||||||
this.engineConfig.input.penMinPressure,
|
|
||||||
this.config.input.pressureFallback
|
|
||||||
)
|
|
||||||
: this.config.input.pressureFallback;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
126
src/audio/piano-sampler.test.ts
Normal file
126
src/audio/piano-sampler.test.ts
Normal file
|
|
@ -0,0 +1,126 @@
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { appConfig } from '../config';
|
||||||
|
import { gardenAudioConfig } from './garden-audio-config';
|
||||||
|
import type { GardenAudioGraph } from './garden-audio-graph';
|
||||||
|
import { PianoSampler } from './piano-sampler';
|
||||||
|
import { pianoSampleDefinitions, resetPianoSampleCacheForTest } from './piano-samples';
|
||||||
|
|
||||||
|
const calls = {
|
||||||
|
bufferSourcesStarted: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
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 pan = new FakeAudioParam();
|
||||||
|
public buffer: AudioBuffer | null = null;
|
||||||
|
public type = '';
|
||||||
|
public addEventListener = vi.fn();
|
||||||
|
public connect = vi.fn();
|
||||||
|
public disconnect = vi.fn();
|
||||||
|
public start = vi.fn();
|
||||||
|
public stop = vi.fn();
|
||||||
|
}
|
||||||
|
|
||||||
|
class FakeAudioContext {
|
||||||
|
public readonly currentTime = 1;
|
||||||
|
public readonly decodeAudioData = vi.fn(async () => ({}) as AudioBuffer);
|
||||||
|
|
||||||
|
public createGain(): GainNode {
|
||||||
|
return new FakeAudioNode() as unknown as GainNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public createBiquadFilter(): BiquadFilterNode {
|
||||||
|
return new FakeAudioNode() as unknown as BiquadFilterNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public createStereoPanner(): StereoPannerNode {
|
||||||
|
return new FakeAudioNode() as unknown as StereoPannerNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public createBufferSource(): AudioBufferSourceNode {
|
||||||
|
const node = new FakeAudioNode() as unknown as AudioBufferSourceNode & {
|
||||||
|
start: () => void;
|
||||||
|
stop: () => void;
|
||||||
|
};
|
||||||
|
node.start = vi.fn(() => {
|
||||||
|
calls.bufferSourcesStarted += 1;
|
||||||
|
});
|
||||||
|
node.stop = vi.fn();
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const makeSampler = (context: AudioContext): PianoSampler => {
|
||||||
|
const eventBus = new FakeAudioNode() as unknown as GainNode;
|
||||||
|
const graph = {
|
||||||
|
context,
|
||||||
|
delayInput: null,
|
||||||
|
eventBus,
|
||||||
|
} as unknown as GardenAudioGraph;
|
||||||
|
|
||||||
|
return new PianoSampler(gardenAudioConfig, appConfig.audioEngine, graph);
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('PianoSampler', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
calls.bufferSourcesStarted = 0;
|
||||||
|
resetPianoSampleCacheForTest();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
resetPianoSampleCacheForTest();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('loads every piano sample before playback', async () => {
|
||||||
|
const context = new FakeAudioContext() as unknown as AudioContext;
|
||||||
|
const sampler = makeSampler(context);
|
||||||
|
const fetch = vi.fn(async () => {
|
||||||
|
return {
|
||||||
|
arrayBuffer: async () => new ArrayBuffer(8),
|
||||||
|
ok: true,
|
||||||
|
} as Response;
|
||||||
|
});
|
||||||
|
vi.stubGlobal('fetch', fetch);
|
||||||
|
|
||||||
|
await sampler.load(context);
|
||||||
|
sampler.play({
|
||||||
|
durationSeconds: 0.2,
|
||||||
|
midi: 60,
|
||||||
|
pan: 0,
|
||||||
|
startTime: context.currentTime,
|
||||||
|
velocity: 0.5,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(fetch).toHaveBeenCalledTimes(pianoSampleDefinitions.length);
|
||||||
|
expect(context.decodeAudioData).toHaveBeenCalledTimes(pianoSampleDefinitions.length);
|
||||||
|
expect(calls.bufferSourcesStarted).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stays silent when no decoded sample is available', () => {
|
||||||
|
const context = new FakeAudioContext() as unknown as AudioContext;
|
||||||
|
const sampler = makeSampler(context);
|
||||||
|
|
||||||
|
sampler.play({
|
||||||
|
durationSeconds: 0.2,
|
||||||
|
midi: 60,
|
||||||
|
pan: 0,
|
||||||
|
startTime: context.currentTime,
|
||||||
|
velocity: 0.5,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(calls.bufferSourcesStarted).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -3,7 +3,7 @@ import { clamp, clamp01 } from '../utils/clamp';
|
||||||
import { GardenAudioConfig } from './garden-audio-config';
|
import { GardenAudioConfig } from './garden-audio-config';
|
||||||
import { GardenAudioGraph } from './garden-audio-graph';
|
import { GardenAudioGraph } from './garden-audio-graph';
|
||||||
import { ActivePianoVoice, LoadedPianoSample, PianoNote } from './garden-audio-types';
|
import { ActivePianoVoice, LoadedPianoSample, PianoNote } from './garden-audio-types';
|
||||||
import { pianoSampleDefinitions } from './piano-samples';
|
import { getLoadedPianoSamples, loadPianoSamples } from './piano-samples';
|
||||||
|
|
||||||
export class PianoSampler {
|
export class PianoSampler {
|
||||||
private sampleLoadPromise: Promise<void> | null = null;
|
private sampleLoadPromise: Promise<void> | null = null;
|
||||||
|
|
@ -16,28 +16,20 @@ export class PianoSampler {
|
||||||
private readonly graph: GardenAudioGraph
|
private readonly graph: GardenAudioGraph
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async load(context: AudioContext): Promise<void> {
|
public load(context: BaseAudioContext): Promise<void> {
|
||||||
|
const loadedSamples = getLoadedPianoSamples();
|
||||||
|
if (loadedSamples) {
|
||||||
|
this.setSamples(loadedSamples);
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
if (this.sampleLoadPromise) {
|
if (this.sampleLoadPromise) {
|
||||||
return this.sampleLoadPromise;
|
return this.sampleLoadPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.sampleLoadPromise = Promise.all(
|
this.sampleLoadPromise = loadPianoSamples(context).then((samples) => {
|
||||||
pianoSampleDefinitions.map(async (sample) => {
|
this.setSamples(samples);
|
||||||
const response = await fetch(sample.url);
|
});
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Unable to load piano sample ${sample.url}`);
|
|
||||||
}
|
|
||||||
const audioData = await response.arrayBuffer();
|
|
||||||
const buffer = await context.decodeAudioData(audioData);
|
|
||||||
return { midi: sample.midi, buffer };
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.then((samples) => {
|
|
||||||
this.samples = samples.sort((a, b) => a.midi - b.midi);
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
this.samples = [];
|
|
||||||
});
|
|
||||||
|
|
||||||
return this.sampleLoadPromise;
|
return this.sampleLoadPromise;
|
||||||
}
|
}
|
||||||
|
|
@ -89,13 +81,9 @@ export class PianoSampler {
|
||||||
this.trimActiveVoices(scheduledStart);
|
this.trimActiveVoices(scheduledStart);
|
||||||
while (this.activeVoices.length >= this.config.piano.maxVoices) {
|
while (this.activeVoices.length >= this.config.piano.maxVoices) {
|
||||||
const oldest = this.activeVoices.shift();
|
const oldest = this.activeVoices.shift();
|
||||||
oldest?.gain.gain.cancelScheduledValues(scheduledStart);
|
if (oldest) {
|
||||||
oldest?.gain.gain.setTargetAtTime(
|
this.stopVoice(oldest, scheduledStart);
|
||||||
this.engineConfig.piano.minGain,
|
}
|
||||||
scheduledStart,
|
|
||||||
this.engineConfig.piano.voiceStealFadeSeconds
|
|
||||||
);
|
|
||||||
oldest?.source.stop(scheduledStart + this.engineConfig.piano.voiceStealStopSeconds);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
source.buffer = sample.buffer;
|
source.buffer = sample.buffer;
|
||||||
|
|
@ -162,6 +150,21 @@ export class PianoSampler {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public stopAll(): void {
|
||||||
|
const context = this.graph.context;
|
||||||
|
if (!context) {
|
||||||
|
this.activeVoices = [];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = context.currentTime;
|
||||||
|
|
||||||
|
this.activeVoices.forEach((voice) => {
|
||||||
|
this.stopVoice(voice, now);
|
||||||
|
});
|
||||||
|
this.activeVoices = [];
|
||||||
|
}
|
||||||
|
|
||||||
public reset(): void {
|
public reset(): void {
|
||||||
this.sampleLoadPromise = null;
|
this.sampleLoadPromise = null;
|
||||||
this.samples = [];
|
this.samples = [];
|
||||||
|
|
@ -181,4 +184,25 @@ export class PianoSampler {
|
||||||
private trimActiveVoices(now: number): void {
|
private trimActiveVoices(now: number): void {
|
||||||
this.activeVoices = this.activeVoices.filter((voice) => voice.stopAt > now);
|
this.activeVoices = this.activeVoices.filter((voice) => voice.stopAt > now);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private stopVoice(voice: ActivePianoVoice, now: number): void {
|
||||||
|
const stopAt = now + this.engineConfig.piano.voiceStealStopSeconds;
|
||||||
|
|
||||||
|
voice.gain.gain.cancelScheduledValues(now);
|
||||||
|
voice.gain.gain.setTargetAtTime(
|
||||||
|
this.engineConfig.piano.minGain,
|
||||||
|
now,
|
||||||
|
this.engineConfig.piano.voiceStealFadeSeconds
|
||||||
|
);
|
||||||
|
voice.stopAt = stopAt;
|
||||||
|
try {
|
||||||
|
voice.source.stop(stopAt);
|
||||||
|
} catch {
|
||||||
|
// The voice may already have ended; either way it is no longer part of the mix.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private setSamples(samples: Array<LoadedPianoSample>): void {
|
||||||
|
this.samples = samples.slice().sort((a, b) => a.midi - b.midi);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,16 @@
|
||||||
interface PianoSampleDefinition {
|
import type { LoadedPianoSample } from './garden-audio-types';
|
||||||
|
|
||||||
|
export interface PianoSampleDefinition {
|
||||||
midi: number;
|
midi: number;
|
||||||
url: string;
|
url: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PianoSampleLoadProgress {
|
||||||
|
loadedCount: number;
|
||||||
|
totalCount: number;
|
||||||
|
sample?: PianoSampleDefinition;
|
||||||
|
}
|
||||||
|
|
||||||
const sampleBaseUrl = `${import.meta.env.BASE_URL}audio/piano/`;
|
const sampleBaseUrl = `${import.meta.env.BASE_URL}audio/piano/`;
|
||||||
|
|
||||||
const sampleFiles: Array<[fileName: string, midi: number]> = [
|
const sampleFiles: Array<[fileName: string, midi: number]> = [
|
||||||
|
|
@ -44,3 +52,94 @@ export const pianoSampleDefinitions: Array<PianoSampleDefinition> = sampleFiles
|
||||||
url: `${sampleBaseUrl}${fileName}`,
|
url: `${sampleBaseUrl}${fileName}`,
|
||||||
}))
|
}))
|
||||||
.sort((a, b) => a.midi - b.midi);
|
.sort((a, b) => a.midi - b.midi);
|
||||||
|
|
||||||
|
let loadedPianoSamples: Array<LoadedPianoSample> | null = null;
|
||||||
|
let pianoSampleLoadPromise: Promise<Array<LoadedPianoSample>> | null = null;
|
||||||
|
|
||||||
|
export const preloadPianoSamples = (
|
||||||
|
onProgress?: (progress: PianoSampleLoadProgress) => void
|
||||||
|
): Promise<Array<LoadedPianoSample>> => {
|
||||||
|
const OfflineAudioContextConstructor =
|
||||||
|
globalThis.OfflineAudioContext ?? globalThis.webkitOfflineAudioContext;
|
||||||
|
|
||||||
|
if (!OfflineAudioContextConstructor) {
|
||||||
|
return Promise.reject(
|
||||||
|
new Error('OfflineAudioContext is required to preload piano samples.')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const decodeContext = new OfflineAudioContextConstructor(1, 1, 44_100);
|
||||||
|
return loadPianoSamples(decodeContext, onProgress);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const loadPianoSamples = (
|
||||||
|
decodeContext: BaseAudioContext,
|
||||||
|
onProgress?: (progress: PianoSampleLoadProgress) => void
|
||||||
|
): Promise<Array<LoadedPianoSample>> => {
|
||||||
|
if (loadedPianoSamples) {
|
||||||
|
onProgress?.({
|
||||||
|
loadedCount: loadedPianoSamples.length,
|
||||||
|
totalCount: pianoSampleDefinitions.length,
|
||||||
|
});
|
||||||
|
return Promise.resolve([...loadedPianoSamples]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pianoSampleLoadPromise) {
|
||||||
|
return pianoSampleLoadPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
let loadedCount = 0;
|
||||||
|
const totalCount = pianoSampleDefinitions.length;
|
||||||
|
onProgress?.({ loadedCount, totalCount });
|
||||||
|
|
||||||
|
pianoSampleLoadPromise = Promise.all(
|
||||||
|
pianoSampleDefinitions.map(async (sample) => {
|
||||||
|
const loadedSample = await loadPianoSample(decodeContext, sample);
|
||||||
|
loadedCount += 1;
|
||||||
|
onProgress?.({ loadedCount, totalCount, sample });
|
||||||
|
return loadedSample;
|
||||||
|
})
|
||||||
|
).then(
|
||||||
|
(samples) => {
|
||||||
|
loadedPianoSamples = samples.slice().sort((a, b) => a.midi - b.midi);
|
||||||
|
return [...loadedPianoSamples];
|
||||||
|
},
|
||||||
|
(error: unknown) => {
|
||||||
|
pianoSampleLoadPromise = null;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return pianoSampleLoadPromise;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getLoadedPianoSamples = (): Array<LoadedPianoSample> | null =>
|
||||||
|
loadedPianoSamples ? [...loadedPianoSamples] : null;
|
||||||
|
|
||||||
|
export const resetPianoSampleCacheForTest = (): void => {
|
||||||
|
loadedPianoSamples = null;
|
||||||
|
pianoSampleLoadPromise = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadPianoSample = async (
|
||||||
|
decodeContext: BaseAudioContext,
|
||||||
|
sample: PianoSampleDefinition
|
||||||
|
): Promise<LoadedPianoSample> => {
|
||||||
|
const response = await fetch(sample.url);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Unable to load piano sample ${sample.url}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const audioData = await response.arrayBuffer();
|
||||||
|
const buffer = await decodeAudioData(decodeContext, audioData);
|
||||||
|
return { midi: sample.midi, buffer };
|
||||||
|
};
|
||||||
|
|
||||||
|
const decodeAudioData = (
|
||||||
|
decodeContext: BaseAudioContext,
|
||||||
|
audioData: ArrayBuffer
|
||||||
|
): Promise<AudioBuffer> =>
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
const decodePromise = decodeContext.decodeAudioData(audioData, resolve, reject);
|
||||||
|
decodePromise?.then(resolve, reject);
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -3,15 +3,10 @@ import type { GardenAppConfig } from './config/types';
|
||||||
import { audioVibes, defaultVibeId, vibePresets } from './config/vibe-presets';
|
import { audioVibes, defaultVibeId, vibePresets } from './config/vibe-presets';
|
||||||
|
|
||||||
export type {
|
export type {
|
||||||
AgentColorInteractionSettings,
|
|
||||||
GardenAppConfig,
|
GardenAppConfig,
|
||||||
GardenAudioEngineConfig,
|
GardenAudioEngineConfig,
|
||||||
GardenRuntimeSettings,
|
GardenRuntimeSettings,
|
||||||
GardenSimulationConfig,
|
|
||||||
GardenStorageConfig,
|
|
||||||
GardenVibeSettings,
|
|
||||||
NumberControlConfig,
|
NumberControlConfig,
|
||||||
RuntimeSettingControlConfig,
|
|
||||||
VibePreset,
|
VibePreset,
|
||||||
} from './config/types';
|
} from './config/types';
|
||||||
|
|
||||||
|
|
@ -21,14 +16,6 @@ export const appConfig = {
|
||||||
fadeInSeconds: 0.45,
|
fadeInSeconds: 0.45,
|
||||||
updateRampSeconds: 0.08,
|
updateRampSeconds: 0.08,
|
||||||
highPassFrequencyHz: 45,
|
highPassFrequencyHz: 45,
|
||||||
fallbackVibeId: defaultVibeId,
|
|
||||||
compressor: {
|
|
||||||
thresholdDb: -18,
|
|
||||||
kneeDb: 18,
|
|
||||||
ratio: 2.4,
|
|
||||||
attackSeconds: 0.006,
|
|
||||||
releaseSeconds: 0.18,
|
|
||||||
},
|
|
||||||
delay: {
|
delay: {
|
||||||
timeSeconds: 0.46,
|
timeSeconds: 0.46,
|
||||||
feedback: 0.12,
|
feedback: 0.12,
|
||||||
|
|
@ -42,9 +29,6 @@ export const appConfig = {
|
||||||
releaseSeconds: 0.24,
|
releaseSeconds: 0.24,
|
||||||
lowpassHz: 7600,
|
lowpassHz: 7600,
|
||||||
},
|
},
|
||||||
input: {
|
|
||||||
pressureFallback: 0.48,
|
|
||||||
},
|
|
||||||
rhythm: {
|
rhythm: {
|
||||||
bpm: 74,
|
bpm: 74,
|
||||||
stepsPerBeat: 4,
|
stepsPerBeat: 4,
|
||||||
|
|
@ -120,7 +104,6 @@ export const appConfig = {
|
||||||
distanceEnergyScale: 0.66,
|
distanceEnergyScale: 0.66,
|
||||||
distanceForFullEnergyPixels: 140,
|
distanceForFullEnergyPixels: 140,
|
||||||
fallbackFrameSeconds: 1 / 60,
|
fallbackFrameSeconds: 1 / 60,
|
||||||
penMinPressure: 0.56,
|
|
||||||
strokeEnergyBase: 0.18,
|
strokeEnergyBase: 0.18,
|
||||||
strokeEnergyPressureWeight: 0.22,
|
strokeEnergyPressureWeight: 0.22,
|
||||||
strokeEnergySpeedWeight: 0.62,
|
strokeEnergySpeedWeight: 0.62,
|
||||||
|
|
|
||||||
|
|
@ -18,47 +18,6 @@ export const defaultColorInteractionSettings: AgentColorInteractionSettings = {
|
||||||
color3ToColor3: 1,
|
color3ToColor3: 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
const hashString = (value: string): number => {
|
|
||||||
let hash = 0x811c9dc5;
|
|
||||||
for (let i = 0; i < value.length; i++) {
|
|
||||||
hash ^= value.charCodeAt(i);
|
|
||||||
hash = Math.imul(hash, 0x01000193);
|
|
||||||
}
|
|
||||||
return hash >>> 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
const createSeededRandom = (seed: number): (() => number) => {
|
|
||||||
let state = seed;
|
|
||||||
return () => {
|
|
||||||
let value = (state += 0x6d2b79f5);
|
|
||||||
value = Math.imul(value ^ (value >>> 15), value | 1);
|
|
||||||
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
|
|
||||||
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export const createColorInteractionSettings = (
|
|
||||||
seedSource: string
|
|
||||||
): AgentColorInteractionSettings => {
|
|
||||||
const random = createSeededRandom(hashString(seedSource));
|
|
||||||
const values = Object.values(agentInteractionOptions);
|
|
||||||
const randomInteraction = () =>
|
|
||||||
values[Math.floor(random() * values.length)] ??
|
|
||||||
defaultColorInteractionSettings.color1ToColor2;
|
|
||||||
|
|
||||||
return {
|
|
||||||
color1ToColor1: 1,
|
|
||||||
color1ToColor2: randomInteraction(),
|
|
||||||
color1ToColor3: randomInteraction(),
|
|
||||||
color2ToColor1: randomInteraction(),
|
|
||||||
color2ToColor2: 1,
|
|
||||||
color2ToColor3: randomInteraction(),
|
|
||||||
color3ToColor1: randomInteraction(),
|
|
||||||
color3ToColor2: randomInteraction(),
|
|
||||||
color3ToColor3: 1,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export const colorInteractionControl = (label: string): NumberControlConfig => ({
|
export const colorInteractionControl = (label: string): NumberControlConfig => ({
|
||||||
folder: 'Color Reactions',
|
folder: 'Color Reactions',
|
||||||
label,
|
label,
|
||||||
|
|
|
||||||
|
|
@ -36,7 +36,6 @@ export const runtimeSettings: GardenAppConfig['runtimeSettings'] = {
|
||||||
|
|
||||||
startColorHue: 200,
|
startColorHue: 200,
|
||||||
|
|
||||||
renderSpeed: 1,
|
|
||||||
simulatedDelayMs: 0,
|
simulatedDelayMs: 0,
|
||||||
},
|
},
|
||||||
controls: {
|
controls: {
|
||||||
|
|
@ -145,13 +144,6 @@ export const runtimeSettings: GardenAppConfig['runtimeSettings'] = {
|
||||||
max: 500,
|
max: 500,
|
||||||
step: 1,
|
step: 1,
|
||||||
},
|
},
|
||||||
renderSpeed: {
|
|
||||||
folder: 'Runtime',
|
|
||||||
integer: true,
|
|
||||||
min: 1,
|
|
||||||
max: 10,
|
|
||||||
step: 1,
|
|
||||||
},
|
|
||||||
selectedColorIndex: {
|
selectedColorIndex: {
|
||||||
folder: 'Brush',
|
folder: 'Brush',
|
||||||
integer: true,
|
integer: true,
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@ export type AgentColorInteractionSettings = Pick<
|
||||||
| 'color3ToColor3'
|
| 'color3ToColor3'
|
||||||
>;
|
>;
|
||||||
|
|
||||||
export type GardenVibeSettings = Partial<
|
type GardenVibeSettings = Partial<
|
||||||
Pick<
|
Pick<
|
||||||
GardenRuntimeSettings,
|
GardenRuntimeSettings,
|
||||||
| 'agentBudgetMax'
|
| 'agentBudgetMax'
|
||||||
|
|
@ -72,7 +72,7 @@ export interface NumberControlConfig {
|
||||||
step?: number;
|
step?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type RuntimeSettingControlConfig = {
|
type RuntimeSettingControlConfig = {
|
||||||
[Key in keyof GardenRuntimeSettings]: NumberControlConfig;
|
[Key in keyof GardenRuntimeSettings]: NumberControlConfig;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -120,7 +120,6 @@ export interface GardenAppConfig {
|
||||||
distanceEnergyScale: number;
|
distanceEnergyScale: number;
|
||||||
distanceForFullEnergyPixels: number;
|
distanceForFullEnergyPixels: number;
|
||||||
fallbackFrameSeconds: number;
|
fallbackFrameSeconds: number;
|
||||||
penMinPressure: number;
|
|
||||||
strokeEnergyBase: number;
|
strokeEnergyBase: number;
|
||||||
strokeEnergyPressureWeight: number;
|
strokeEnergyPressureWeight: number;
|
||||||
strokeEnergySpeedWeight: number;
|
strokeEnergySpeedWeight: number;
|
||||||
|
|
@ -280,5 +279,3 @@ export interface GardenAppConfig {
|
||||||
}
|
}
|
||||||
|
|
||||||
export type GardenAudioEngineConfig = GardenAppConfig['audioEngine'];
|
export type GardenAudioEngineConfig = GardenAppConfig['audioEngine'];
|
||||||
export type GardenSimulationConfig = GardenAppConfig['simulation'];
|
|
||||||
export type GardenStorageConfig = GardenAppConfig['storage'];
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import type {
|
||||||
GardenAudioChord,
|
GardenAudioChord,
|
||||||
GardenAudioVibeProfile,
|
GardenAudioVibeProfile,
|
||||||
} from '../audio/garden-audio-config';
|
} from '../audio/garden-audio-config';
|
||||||
import { createColorInteractionSettings } from './color-interactions';
|
import { defaultColorInteractionSettings } from './color-interactions';
|
||||||
import type { VibePreset } from './types';
|
import type { VibePreset } from './types';
|
||||||
|
|
||||||
const majorProgression: Array<GardenAudioChord> = [
|
const majorProgression: Array<GardenAudioChord> = [
|
||||||
|
|
@ -42,7 +42,7 @@ export const vibePresets: Array<VibePreset> = [
|
||||||
sensorOffsetDistance: 38,
|
sensorOffsetDistance: 38,
|
||||||
spawnPerPixel: 0.22,
|
spawnPerPixel: 0.22,
|
||||||
turnSpeed: 58,
|
turnSpeed: 58,
|
||||||
...createColorInteractionSettings('candy-rain'),
|
...defaultColorInteractionSettings,
|
||||||
},
|
},
|
||||||
audio: {
|
audio: {
|
||||||
rootMidi: 57,
|
rootMidi: 57,
|
||||||
|
|
@ -69,7 +69,7 @@ export const vibePresets: Array<VibePreset> = [
|
||||||
sensorOffsetDistance: 46,
|
sensorOffsetDistance: 46,
|
||||||
spawnPerPixel: 0.18,
|
spawnPerPixel: 0.18,
|
||||||
turnSpeed: 44,
|
turnSpeed: 44,
|
||||||
...createColorInteractionSettings('sunlit-moss'),
|
...defaultColorInteractionSettings,
|
||||||
},
|
},
|
||||||
audio: {
|
audio: {
|
||||||
rootMidi: 53,
|
rootMidi: 53,
|
||||||
|
|
@ -101,7 +101,7 @@ export const vibePresets: Array<VibePreset> = [
|
||||||
sensorOffsetDistance: 35,
|
sensorOffsetDistance: 35,
|
||||||
spawnPerPixel: 0.25,
|
spawnPerPixel: 0.25,
|
||||||
turnSpeed: 62,
|
turnSpeed: 62,
|
||||||
...createColorInteractionSettings('coral-tide'),
|
...defaultColorInteractionSettings,
|
||||||
},
|
},
|
||||||
audio: {
|
audio: {
|
||||||
rootMidi: 50,
|
rootMidi: 50,
|
||||||
|
|
@ -128,7 +128,7 @@ export const vibePresets: Array<VibePreset> = [
|
||||||
sensorOffsetDistance: 42,
|
sensorOffsetDistance: 42,
|
||||||
spawnPerPixel: 0.2,
|
spawnPerPixel: 0.2,
|
||||||
turnSpeed: 52,
|
turnSpeed: 52,
|
||||||
...createColorInteractionSettings('moon-orchid'),
|
...defaultColorInteractionSettings,
|
||||||
},
|
},
|
||||||
audio: {
|
audio: {
|
||||||
rootMidi: 49,
|
rootMidi: 49,
|
||||||
|
|
@ -155,7 +155,7 @@ export const vibePresets: Array<VibePreset> = [
|
||||||
sensorOffsetDistance: 32,
|
sensorOffsetDistance: 32,
|
||||||
spawnPerPixel: 0.24,
|
spawnPerPixel: 0.24,
|
||||||
turnSpeed: 70,
|
turnSpeed: 70,
|
||||||
...createColorInteractionSettings('peach-neon'),
|
...defaultColorInteractionSettings,
|
||||||
},
|
},
|
||||||
audio: {
|
audio: {
|
||||||
rootMidi: 56,
|
rootMidi: 56,
|
||||||
|
|
@ -182,7 +182,7 @@ export const vibePresets: Array<VibePreset> = [
|
||||||
sensorOffsetDistance: 52,
|
sensorOffsetDistance: 52,
|
||||||
spawnPerPixel: 0.16,
|
spawnPerPixel: 0.16,
|
||||||
turnSpeed: 40,
|
turnSpeed: 40,
|
||||||
...createColorInteractionSettings('frost-bloom'),
|
...defaultColorInteractionSettings,
|
||||||
},
|
},
|
||||||
audio: {
|
audio: {
|
||||||
rootMidi: 62,
|
rootMidi: 62,
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue