Feed aquarium harmony from MIDI progressions
This commit is contained in:
parent
02ba15d14e
commit
05add07f52
9 changed files with 701 additions and 53 deletions
7
apps/epiphany-gui/package-lock.json
generated
7
apps/epiphany-gui/package-lock.json
generated
|
|
@ -11,6 +11,7 @@
|
|||
"@epiphanygraph/epiphany-graph-viewer": "file:../../../EpiphanyGraph/web/epiphany-graph-viewer",
|
||||
"@tauri-apps/api": "^2.0.0",
|
||||
"lucide-react": "^0.468.0",
|
||||
"midi-file": "^1.2.4",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
|
|
@ -1827,6 +1828,12 @@
|
|||
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc"
|
||||
}
|
||||
},
|
||||
"node_modules/midi-file": {
|
||||
"version": "1.2.4",
|
||||
"resolved": "https://registry.npmjs.org/midi-file/-/midi-file-1.2.4.tgz",
|
||||
"integrity": "sha512-B5SnBC6i2bwJIXTY9MElIydJwAmnKx+r5eJ1jknTLetzLflEl0GWveuBB6ACrQpecSRkOB6fhTx1PwXk2BVxnA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@
|
|||
"@epiphanygraph/epiphany-graph-viewer": "file:../../../EpiphanyGraph/web/epiphany-graph-viewer",
|
||||
"@tauri-apps/api": "^2.0.0",
|
||||
"lucide-react": "^0.468.0",
|
||||
"midi-file": "^1.2.4",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ async function smokeViewport(browser, viewport, screenshotPath, exerciseFluidPan
|
|||
await page.locator(".immersiveShell").waitFor();
|
||||
await page.locator(".agentSmokeCanvas").waitFor();
|
||||
await page.locator(".agentCrispCanvas").waitFor();
|
||||
await page.waitForTimeout(700);
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
const smokeProbe = await probeCanvas(page, ".agentSmokeCanvas");
|
||||
const crispProbe = await probeCanvas(page, ".agentCrispCanvas");
|
||||
|
|
@ -112,49 +112,69 @@ async function smokeViewport(browser, viewport, screenshotPath, exerciseFluidPan
|
|||
throw new Error(`DOM agent projection was not synchronized: ${projectionProbe.reason}`);
|
||||
}
|
||||
|
||||
const hoverBox = await page.locator('[data-agent-node="research"]').boundingBox();
|
||||
if (!hoverBox) {
|
||||
throw new Error("research DOM node has no hover bounds");
|
||||
if (viewport.width >= 720) {
|
||||
const hoverBox = await page.locator('[data-agent-node="research"] .agentGlyph').boundingBox();
|
||||
if (!hoverBox) {
|
||||
throw new Error("research DOM node has no hover bounds");
|
||||
}
|
||||
await page.mouse.move(hoverBox.x + hoverBox.width / 2, hoverBox.y + hoverBox.height / 2);
|
||||
await page.waitForTimeout(600);
|
||||
let hoverProbe = await page.evaluate(() => {
|
||||
const node = document.querySelector('[data-agent-node="research"]');
|
||||
if (!(node instanceof HTMLElement)) return { ok: false, reason: "research DOM node missing" };
|
||||
const hover = Number.parseFloat(node.style.getPropertyValue("--agent-hover"));
|
||||
const acknowledgement = Number.parseFloat(node.style.getPropertyValue("--agent-ack"));
|
||||
return {
|
||||
ok: hover > 0.7 && acknowledgement >= 0,
|
||||
reason: `hover=${hover} ack=${acknowledgement}`,
|
||||
};
|
||||
});
|
||||
if (!hoverProbe.ok) {
|
||||
await page.locator('[data-agent-node="research"]').dispatchEvent("pointerenter", { bubbles: true });
|
||||
await page.locator('[data-agent-node="research"]').dispatchEvent("mouseenter", { bubbles: true });
|
||||
await page.waitForTimeout(600);
|
||||
hoverProbe = await page.evaluate(() => {
|
||||
const node = document.querySelector('[data-agent-node="research"]');
|
||||
if (!(node instanceof HTMLElement)) return { ok: false, reason: "research DOM node missing" };
|
||||
const hover = Number.parseFloat(node.style.getPropertyValue("--agent-hover"));
|
||||
const acknowledgement = Number.parseFloat(node.style.getPropertyValue("--agent-ack"));
|
||||
return {
|
||||
ok: hover > 0.7 && acknowledgement >= 0,
|
||||
reason: `hover=${hover} ack=${acknowledgement}`,
|
||||
};
|
||||
});
|
||||
}
|
||||
if (!hoverProbe.ok) {
|
||||
throw new Error(`DOM hover did not reach aquarium projection at ${viewport.width}x${viewport.height}: ${hoverProbe.reason}`);
|
||||
}
|
||||
}
|
||||
await page.mouse.move(hoverBox.x + hoverBox.width / 2, hoverBox.y + hoverBox.height / 2);
|
||||
await page.waitForTimeout(180);
|
||||
const hoverProbe = await page.evaluate(() => {
|
||||
const node = document.querySelector('[data-agent-node="research"]');
|
||||
if (!(node instanceof HTMLElement)) return { ok: false, reason: "research DOM node missing" };
|
||||
const hover = Number.parseFloat(node.style.getPropertyValue("--agent-hover"));
|
||||
const acknowledgement = Number.parseFloat(node.style.getPropertyValue("--agent-ack"));
|
||||
return {
|
||||
ok: hover > 0.7 && acknowledgement >= 0,
|
||||
reason: `hover=${hover} ack=${acknowledgement}`,
|
||||
};
|
||||
});
|
||||
if (!hoverProbe.ok) {
|
||||
throw new Error(`DOM hover did not reach aquarium projection: ${hoverProbe.reason}`);
|
||||
let audioProbe = null;
|
||||
if (viewport.width >= 720) {
|
||||
const researchBox = await page.locator('[data-agent-node="research"] .agentGlyph').boundingBox();
|
||||
if (!researchBox) {
|
||||
throw new Error("research DOM node has no clickable bounds");
|
||||
}
|
||||
await page.mouse.click(researchBox.x + researchBox.width / 2, researchBox.y + researchBox.height / 2);
|
||||
try {
|
||||
await page.waitForFunction(() => {
|
||||
const audio = window.__epiphanyAquariumAudio;
|
||||
return audio?.state === "running" &&
|
||||
audio.vocalAgentCount >= 7 &&
|
||||
audio.lastBurstChirpDrivers >= 6 &&
|
||||
audio.spectral?.chirpDrivers === 6 &&
|
||||
audio.spectral?.lastBurstChoirVoices >= 3 &&
|
||||
audio.spectral?.reactiveFlushes >= 1 &&
|
||||
audio.spectral?.transientBins >= 24 &&
|
||||
audio.spectral?.vocalAgents >= 7 &&
|
||||
audio.spectral?.queuedFrames >= 2048 &&
|
||||
audio.lastBurst;
|
||||
}, null, { timeout: 5000 });
|
||||
} catch (error) {
|
||||
const audio = await page.evaluate(() => window.__epiphanyAquariumAudio ?? null);
|
||||
throw new Error(`aquarium audio did not wake correctly: ${JSON.stringify(audio)}`, { cause: error });
|
||||
}
|
||||
audioProbe = await page.evaluate(() => window.__epiphanyAquariumAudio ?? null);
|
||||
}
|
||||
const researchBox = await page.locator('[data-agent-node="research"]').boundingBox();
|
||||
if (!researchBox) {
|
||||
throw new Error("research DOM node has no clickable bounds");
|
||||
}
|
||||
await page.mouse.click(researchBox.x + researchBox.width / 2, researchBox.y + researchBox.height / 2);
|
||||
try {
|
||||
await page.waitForFunction(() => {
|
||||
const audio = window.__epiphanyAquariumAudio;
|
||||
return audio?.state === "running" &&
|
||||
audio.vocalAgentCount >= 7 &&
|
||||
audio.lastBurstChirpDrivers >= 6 &&
|
||||
audio.spectral?.chirpDrivers === 6 &&
|
||||
audio.spectral?.lastBurstChoirVoices >= 3 &&
|
||||
audio.spectral?.reactiveFlushes >= 1 &&
|
||||
audio.spectral?.transientBins >= 24 &&
|
||||
audio.spectral?.vocalAgents >= 7 &&
|
||||
audio.spectral?.queuedFrames >= 2048 &&
|
||||
audio.lastBurst;
|
||||
}, null, { timeout: 5000 });
|
||||
} catch (error) {
|
||||
const audio = await page.evaluate(() => window.__epiphanyAquariumAudio ?? null);
|
||||
throw new Error(`aquarium audio did not wake correctly: ${JSON.stringify(audio)}`, { cause: error });
|
||||
}
|
||||
const audioProbe = await page.evaluate(() => window.__epiphanyAquariumAudio ?? null);
|
||||
|
||||
let persistedParams = null;
|
||||
if (exerciseFluidPanel) {
|
||||
|
|
|
|||
|
|
@ -16,10 +16,12 @@ import {
|
|||
import { EpiphanyGraphViewer, validateEpiphanyGraphsState } from "@epiphanygraph/epiphany-graph-viewer";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { createAquariumRenderer } from "./aquariumFluid";
|
||||
import { createHarmonyRuntime, loadNextHarmony, loadShuffledDefaultHarmony, pickHarmonyFolder } from "./midiHarmony";
|
||||
import { loadOperatorSnapshot, runOperatorAction } from "./operatorApi";
|
||||
import type { ArtifactBundle, OperatorAction, OperatorActionResult, OperatorSnapshot, StatusRequest } from "./types";
|
||||
import type { EpiphanyCodeRef, EpiphanyGraphsState } from "@epiphanygraph/epiphany-graph-viewer";
|
||||
import type { AquariumAgentProjection, AquariumOptionFrame, AquariumRenderer, AquariumUiFrame } from "./aquariumFluid";
|
||||
import type { AquariumHarmonyFrame, HarmonyRuntime, HarmonySource, MidiCorpusFile } from "./midiHarmony";
|
||||
|
||||
const roleOrder = ["implementation", "imagination", "research", "eyes", "modeling", "verification", "reorientation"];
|
||||
const constellationSpecs = [
|
||||
|
|
@ -129,6 +131,7 @@ const constellationSpecs = [
|
|||
phase: 6.0,
|
||||
},
|
||||
] as const;
|
||||
const harmonyAgentIds = constellationSpecs.map((agent) => agent.id);
|
||||
|
||||
type ConstellationSpec = (typeof constellationSpecs)[number];
|
||||
type ProjectedAgent = ConstellationSpec & {
|
||||
|
|
@ -561,8 +564,87 @@ function useSnapshot() {
|
|||
return { snapshot, loading, error, request, setRequest, refresh, actionResult, runningAction, runAction };
|
||||
}
|
||||
|
||||
function useMidiHarmony() {
|
||||
const runtimeRef = useRef<HarmonyRuntime | null>(null);
|
||||
const [files, setFiles] = useState<MidiCorpusFile[]>([]);
|
||||
const [frame, setFrame] = useState<AquariumHarmonyFrame | null>(null);
|
||||
const [source, setSource] = useState<HarmonySource | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const installSource = useCallback((nextSource: HarmonySource) => {
|
||||
const runtime = createHarmonyRuntime(nextSource, harmonyAgentIds);
|
||||
runtimeRef.current = runtime;
|
||||
setSource(nextSource);
|
||||
setFrame(runtime.frame);
|
||||
}, []);
|
||||
|
||||
const loadDefault = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const loaded = await loadShuffledDefaultHarmony(harmonyAgentIds);
|
||||
setFiles(loaded.files);
|
||||
installSource(loaded.source);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [installSource]);
|
||||
|
||||
const nextSong = useCallback(async () => {
|
||||
if (!files.length) {
|
||||
await loadDefault();
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const loaded = await loadNextHarmony(files, harmonyAgentIds, source?.sourcePath);
|
||||
installSource(loaded.source);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [files, installSource, loadDefault, source?.sourcePath]);
|
||||
|
||||
const changeFolder = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const loaded = await pickHarmonyFolder(harmonyAgentIds);
|
||||
setFiles(loaded.files);
|
||||
installSource(loaded.source);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [installSource]);
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = window.setTimeout(() => void loadDefault(), 4000);
|
||||
return () => window.clearTimeout(timeout);
|
||||
}, [loadDefault]);
|
||||
|
||||
useEffect(() => {
|
||||
const interval = window.setInterval(() => {
|
||||
const runtime = runtimeRef.current;
|
||||
if (runtime) {
|
||||
setFrame(runtime.next());
|
||||
}
|
||||
}, 1650);
|
||||
return () => window.clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
return { changeFolder, error, files, frame, loading, nextSong, source };
|
||||
}
|
||||
|
||||
export function App() {
|
||||
const { snapshot, loading, error, request, setRequest, refresh, actionResult, runningAction, runAction } = useSnapshot();
|
||||
const harmony = useMidiHarmony();
|
||||
const [selectedCodeRef, setSelectedCodeRef] = useState<EpiphanyCodeRef | null>(null);
|
||||
const [activeDeck, setActiveDeck] = useState<DeckId>("command");
|
||||
const [subdeckByDeck, setSubdeckByDeck] = useState<Record<DeckId, string>>({
|
||||
|
|
@ -863,6 +945,7 @@ export function App() {
|
|||
activeDeck={activeDeck}
|
||||
activeSubdeck={activeSubdeck}
|
||||
ui={aquariumUi}
|
||||
harmonyFrame={harmony.frame}
|
||||
onAgentOption={handleAquariumOption}
|
||||
isActionBlocked={actionBlocked}
|
||||
/>
|
||||
|
|
@ -884,6 +967,13 @@ export function App() {
|
|||
<RefreshCw size={16} aria-hidden="true" />
|
||||
{loading ? "Refreshing" : "Refresh"}
|
||||
</button>
|
||||
<PlaylistControl
|
||||
error={harmony.error}
|
||||
frame={harmony.frame}
|
||||
loading={harmony.loading}
|
||||
onChangeFolder={harmony.changeFolder}
|
||||
onNext={harmony.nextSong}
|
||||
/>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
|
|
@ -1294,6 +1384,36 @@ function Panel({ title, icon, children }: { title: string; icon: React.ReactNode
|
|||
);
|
||||
}
|
||||
|
||||
function PlaylistControl({
|
||||
error,
|
||||
frame,
|
||||
loading,
|
||||
onChangeFolder,
|
||||
onNext,
|
||||
}: {
|
||||
error: string | null;
|
||||
frame: AquariumHarmonyFrame | null;
|
||||
loading: boolean;
|
||||
onChangeFolder: () => void | Promise<void>;
|
||||
onNext: () => void | Promise<void>;
|
||||
}) {
|
||||
return (
|
||||
<details className="playlistControl">
|
||||
<summary title={frame?.sourcePath ?? error ?? "Loading classical MIDI harmony"}>
|
||||
<span>Harmony</span>
|
||||
<strong>{loading ? "loading" : frame?.chordLabel ?? "silent"}</strong>
|
||||
</summary>
|
||||
<div className="playlistBody">
|
||||
<p title={frame?.sourcePath ?? undefined}>{error ?? frame?.sourceName ?? "Finding a classical MIDI file."}</p>
|
||||
<div className="playlistButtons">
|
||||
<button type="button" onClick={() => void onNext()} disabled={loading}>Shuffle Song</button>
|
||||
<button type="button" onClick={() => void onChangeFolder()} disabled={loading}>Folder</button>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentConstellation({
|
||||
roles,
|
||||
roleResults,
|
||||
|
|
@ -1307,6 +1427,7 @@ function AgentConstellation({
|
|||
activeDeck,
|
||||
activeSubdeck,
|
||||
ui,
|
||||
harmonyFrame,
|
||||
onAgentOption,
|
||||
isActionBlocked,
|
||||
}: {
|
||||
|
|
@ -1322,6 +1443,7 @@ function AgentConstellation({
|
|||
activeDeck?: DeckId;
|
||||
activeSubdeck?: string;
|
||||
ui?: AquariumUiFrame;
|
||||
harmonyFrame: AquariumHarmonyFrame | null;
|
||||
onAgentOption?: (option: AquariumOption) => void;
|
||||
isActionBlocked?: (action: OperatorAction) => boolean;
|
||||
}) {
|
||||
|
|
@ -1402,12 +1524,13 @@ function AgentConstellation({
|
|||
});
|
||||
return {
|
||||
...agent,
|
||||
harmony: harmonyFrame?.agentVoices[agent.id],
|
||||
options,
|
||||
};
|
||||
});
|
||||
optionByKeyRef.current = optionsByKey;
|
||||
return framedAgents;
|
||||
}, [agents, isActionBlocked]);
|
||||
}, [agents, harmonyFrame, isActionBlocked]);
|
||||
|
||||
useEffect(() => {
|
||||
const uiOptions = new globalThis.Map<string, AquariumOption>();
|
||||
|
|
@ -1600,6 +1723,12 @@ function AgentConstellation({
|
|||
onPointerDown={() => handleAgentPointerDown(agent.id)}
|
||||
onPointerMove={handleAgentPointerMove}
|
||||
onPointerLeave={handleAgentPointerLeave}
|
||||
onMouseEnter={(event) => {
|
||||
rendererRef.current?.setPointerClient(event.clientX, event.clientY);
|
||||
rendererRef.current?.setHoveredAgent(agent.id);
|
||||
}}
|
||||
onMouseMove={(event) => rendererRef.current?.setPointerClient(event.clientX, event.clientY)}
|
||||
onMouseLeave={handleAgentPointerLeave}
|
||||
title={`${agent.name}: ${agent.thought}`}
|
||||
style={
|
||||
{
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ export interface AquariumAgentFrame {
|
|||
driftY: number;
|
||||
phase: number;
|
||||
activity: number;
|
||||
harmony?: AquariumAgentHarmonyFrame;
|
||||
options: AquariumOptionFrame[];
|
||||
}
|
||||
|
||||
|
|
@ -60,6 +61,14 @@ export interface AquariumAgentProjection {
|
|||
acknowledgement: number;
|
||||
}
|
||||
|
||||
export interface AquariumAgentHarmonyFrame {
|
||||
chordDegree: number;
|
||||
frequency: number;
|
||||
instrument: string;
|
||||
midi: number;
|
||||
program: number;
|
||||
}
|
||||
|
||||
export interface AquariumFrame {
|
||||
agents: AquariumAgentFrame[];
|
||||
selectedAgentId: string;
|
||||
|
|
@ -1912,6 +1921,17 @@ function vocalProfileFor(id: string) {
|
|||
return vocalProfiles[id] ?? vocalProfiles.coordinator;
|
||||
}
|
||||
|
||||
function instrumentTone(program?: number) {
|
||||
const family = Math.floor((program ?? 0) / 8);
|
||||
if (family === 2) return { brightness: 0.92, breath: 0.78, harmonics: 0.76, pluck: 0.9 }; // organ
|
||||
if (family === 3) return { brightness: 1.28, breath: 0.82, harmonics: 1.16, pluck: 1.28 }; // guitar
|
||||
if (family === 5 || family === 6) return { brightness: 0.82, breath: 1.04, harmonics: 1.24, pluck: 0.72 }; // strings/choir
|
||||
if (family === 7) return { brightness: 1.34, breath: 1.08, harmonics: 1.2, pluck: 1.06 }; // brass
|
||||
if (family === 8 || family === 9) return { brightness: 1.12, breath: 1.28, harmonics: 0.96, pluck: 1.0 }; // reeds/pipes
|
||||
if (family >= 10 && family <= 12) return { brightness: 1.18, breath: 1.0, harmonics: 1.08, pluck: 1.12 }; // leads/pads/fx
|
||||
return { brightness: 1, breath: 1, harmonics: 1, pluck: 1 };
|
||||
}
|
||||
|
||||
function vocalChirpControls(agent: ProjectedAgent, time: number): VocalControls {
|
||||
const calm = 1 - agent.chirps.panic;
|
||||
const hoverCalm = 1 - agent.hover * 0.88;
|
||||
|
|
@ -2220,27 +2240,28 @@ class BufferedGpuSpectrumOutput {
|
|||
|
||||
private writeVocalAgentBins(bin: number, agent: ProjectedAgent, startSample: number) {
|
||||
const profile = vocalProfileFor(agent.id);
|
||||
const tone = instrumentTone(agent.harmony?.program);
|
||||
const controls = vocalChirpControls(agent, (startSample + audioChunkFrames * 0.5) / this.context.sampleRate);
|
||||
const formants = morphFormants(profile.formants, controls);
|
||||
const basePitch = profile.f0 * (1 + controls.glottisPitch * 0.035 + controls.vibrato * 0.018 + agent.chirps.acknowledgement * 0.018);
|
||||
const basePitch = (agent.harmony?.frequency ?? profile.f0) * (1 + controls.glottisPitch * 0.035 + controls.vibrato * 0.018 + agent.chirps.acknowledgement * 0.018);
|
||||
const pulseEnergy = Math.max(Math.abs(controls.glottisPitch), Math.abs(controls.tongue), Math.abs(controls.lips), Math.abs(controls.vibrato), controls.string);
|
||||
const hoverQuiet = lerp(1, 0.18, agent.hover);
|
||||
const intensity = (0.00003 + controls.breath * 0.00018 + pulseEnergy * 0.00048 + agent.chirps.acknowledgement * 0.00075 + agent.chirps.panic * 0.0008) * hoverQuiet;
|
||||
const backgroundHarmonics = Math.min(profile.harmonics, 5);
|
||||
const intensity = (0.00002 + controls.breath * 0.00016 * tone.breath + pulseEnergy * 0.00042 + agent.chirps.acknowledgement * 0.0007 + agent.chirps.panic * 0.00072) * hoverQuiet;
|
||||
const backgroundHarmonics = Math.min(Math.round(profile.harmonics * tone.harmonics), 5);
|
||||
for (let harmonic = 1; harmonic <= backgroundHarmonics && bin < audioSpectrumBins; harmonic += 1) {
|
||||
const frequency = basePitch * harmonic * (1 + controls.throat * 0.002 * harmonic);
|
||||
if (frequency > 14000) break;
|
||||
const sourceTilt = 1 / Math.pow(harmonic, 1.08 + controls.tenseness * 0.22 + profile.softness * 0.18);
|
||||
const tract = vocalFormantEnvelope(frequency, formants);
|
||||
const stringMotion = controls.string * (0.08 / Math.sqrt(harmonic));
|
||||
const amplitude = intensity * sourceTilt * tract * (0.55 + controls.tongue * 0.22 + controls.lips * 0.18 + stringMotion);
|
||||
const amplitude = intensity * sourceTilt * tract * tone.brightness * (0.55 + controls.tongue * 0.22 + controls.lips * 0.18 + stringMotion);
|
||||
const chirp = controls.vibrato * 0.018 + controls.glottisPitch * 0.006 + agent.chirps.panic * 0.035;
|
||||
this.writeBin(bin, frequency, amplitude, profile.phase + agent.phase * harmonic + startSample * 0.0000008 * harmonic, chirp);
|
||||
bin += 1;
|
||||
}
|
||||
for (let index = 0; index < Math.min(formants.length, 2) && bin < audioSpectrumBins; index += 1) {
|
||||
const formant = formants[index];
|
||||
const breathAmplitude = (0.00005 + controls.breath * 0.00018 + agent.chirps.panic * 0.00045) * formant.gain * hoverQuiet;
|
||||
const breathAmplitude = (0.00004 + controls.breath * 0.00016 * tone.breath + agent.chirps.panic * 0.0004) * formant.gain * hoverQuiet;
|
||||
this.writeBin(bin, formant.frequency, breathAmplitude, profile.phase * (index + 2.1), controls.tongue * 0.012 + controls.lips * 0.01);
|
||||
bin += 1;
|
||||
}
|
||||
|
|
@ -2255,6 +2276,7 @@ class BufferedGpuSpectrumOutput {
|
|||
const durationSeconds = event.durationSamples / this.context.sampleRate;
|
||||
const envelope = vocalEventEnvelope(localSeconds, durationSeconds, event.action);
|
||||
const profile = vocalProfileFor(event.agent.id);
|
||||
const tone = instrumentTone(event.agent.harmony?.program);
|
||||
const random = mulberry32(event.seed);
|
||||
const driverSeconds = durationSeconds * 0.54;
|
||||
const glottis = vocalOneShotChirplet(localSeconds, driverSeconds * 0.1, driverSeconds * 0.052, random() * mathTau, 10.5, 54);
|
||||
|
|
@ -2274,9 +2296,9 @@ class BufferedGpuSpectrumOutput {
|
|||
string: Math.abs(string) * (event.action === "notification" ? 1.0 : 0.64),
|
||||
};
|
||||
const formants = morphFormants(profile.formants, controls);
|
||||
const basePitch = profile.f0 * (1 + controls.glottisPitch * 0.09 + controls.vibrato * 0.035);
|
||||
const drive = event.gain * envelope * (event.action === "notification" ? 0.34 : event.action === "selected" ? 0.28 : 0.24);
|
||||
const harmonics = event.action === "notification" ? 14 : event.action === "selected" ? 12 : 10;
|
||||
const basePitch = (event.agent.harmony?.frequency ?? profile.f0) * (1 + controls.glottisPitch * 0.09 + controls.vibrato * 0.035);
|
||||
const drive = event.gain * envelope * tone.brightness * (event.action === "notification" ? 0.34 : event.action === "selected" ? 0.28 : 0.24);
|
||||
const harmonics = Math.round((event.action === "notification" ? 14 : event.action === "selected" ? 12 : 10) * tone.harmonics);
|
||||
const shape = {
|
||||
attackPortion: event.action === "notification" ? 0.018 : 0.022,
|
||||
decay: event.action === "notification" ? 12 : event.action === "selected" ? 15 : 18,
|
||||
|
|
@ -2287,7 +2309,7 @@ class BufferedGpuSpectrumOutput {
|
|||
const frequency = clamp(basePitch * harmonic * (1 + controls.throat * 0.002 * harmonic), 50, 15000);
|
||||
const tract = vocalFormantEnvelope(frequency, formants);
|
||||
const sourceTilt = 1 / Math.pow(harmonic, 0.94 + controls.tenseness * 0.32);
|
||||
const amplitude = drive * tract * sourceTilt * (0.72 + controls.string * 0.38);
|
||||
const amplitude = drive * tract * sourceTilt * (0.72 + controls.string * 0.38 * tone.pluck);
|
||||
this.writeBin(bin, frequency, amplitude, random() * mathTau, controls.vibrato * 0.22 + controls.glottisPitch * 0.08, shape);
|
||||
bin += 1;
|
||||
}
|
||||
|
|
|
|||
319
apps/epiphany-gui/src/midiHarmony.ts
Normal file
319
apps/epiphany-gui/src/midiHarmony.ts
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
import { parseMidi } from "midi-file";
|
||||
|
||||
export type MidiCorpusFile = {
|
||||
name: string;
|
||||
path: string;
|
||||
relativePath: string;
|
||||
size: number;
|
||||
};
|
||||
|
||||
export type AgentHarmonyVoice = {
|
||||
chordDegree: number;
|
||||
frequency: number;
|
||||
instrument: string;
|
||||
midi: number;
|
||||
program: number;
|
||||
};
|
||||
|
||||
export type AquariumHarmonyFrame = {
|
||||
agentVoices: Record<string, AgentHarmonyVoice>;
|
||||
chordLabel: string;
|
||||
corpusLabel: string;
|
||||
sourceName: string;
|
||||
sourcePath: string;
|
||||
};
|
||||
|
||||
type ChordState = {
|
||||
key: string;
|
||||
label: string;
|
||||
pitchClasses: number[];
|
||||
salience: number;
|
||||
};
|
||||
|
||||
export type HarmonySource = {
|
||||
chords: ChordState[];
|
||||
filesSeen: number;
|
||||
instruments: Array<{ count: number; name: string; program: number }>;
|
||||
markov: Map<string, string[]>;
|
||||
sourceName: string;
|
||||
sourcePath: string;
|
||||
};
|
||||
|
||||
export type HarmonyRuntime = {
|
||||
frame: AquariumHarmonyFrame;
|
||||
next: () => AquariumHarmonyFrame;
|
||||
};
|
||||
|
||||
const defaultCorpusLabel = "Classical MIDIRip";
|
||||
const noteNames = ["C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"];
|
||||
const gmProgramNames = [
|
||||
"Acoustic Grand Piano", "Bright Piano", "Electric Grand Piano", "Honky-tonk Piano",
|
||||
"Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet",
|
||||
"Celesta", "Glockenspiel", "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer",
|
||||
"Drawbar Organ", "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica", "Tango Accordion",
|
||||
"Nylon Guitar", "Steel Guitar", "Jazz Guitar", "Clean Guitar", "Muted Guitar", "Overdrive Guitar", "Distortion Guitar", "Guitar Harmonics",
|
||||
"Acoustic Bass", "Finger Bass", "Pick Bass", "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2",
|
||||
"Violin", "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp", "Timpani",
|
||||
"String Ensemble 1", "String Ensemble 2", "Synth Strings 1", "Synth Strings 2", "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit",
|
||||
"Trumpet", "Trombone", "Tuba", "Muted Trumpet", "French Horn", "Brass Section", "Synth Brass 1", "Synth Brass 2",
|
||||
"Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
|
||||
"Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle", "Ocarina",
|
||||
"Lead 1 Square", "Lead 2 Saw", "Lead 3 Calliope", "Lead 4 Chiff", "Lead 5 Charang", "Lead 6 Voice", "Lead 7 Fifths", "Lead 8 Bass+Lead",
|
||||
"Pad 1 New Age", "Pad 2 Warm", "Pad 3 Polysynth", "Pad 4 Choir", "Pad 5 Bowed", "Pad 6 Metallic", "Pad 7 Halo", "Pad 8 Sweep",
|
||||
"FX 1 Rain", "FX 2 Soundtrack", "FX 3 Crystal", "FX 4 Atmosphere", "FX 5 Brightness", "FX 6 Goblins", "FX 7 Echoes", "FX 8 Sci-fi",
|
||||
"Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bagpipe", "Fiddle", "Shanai",
|
||||
"Tinkle Bell", "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
|
||||
"Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter", "Applause", "Gunshot",
|
||||
];
|
||||
|
||||
export async function loadShuffledDefaultHarmony(agentIds: string[]) {
|
||||
const listing = await fetchJson<{ files: MidiCorpusFile[]; root: string }>("/midi-corpus/list");
|
||||
const files = shuffle(listing.files, Date.now()).filter((file) => file.size > 0);
|
||||
for (const file of files.slice(0, 40)) {
|
||||
try {
|
||||
const source = await loadHarmonySource(file);
|
||||
return { files, frame: createHarmonyRuntime(source, agentIds).frame, source };
|
||||
} catch {
|
||||
// MIDI archives contain plenty of weird little fossils. Keep digging.
|
||||
}
|
||||
}
|
||||
throw new Error("no parseable MIDI harmony source found in the default corpus");
|
||||
}
|
||||
|
||||
export async function loadNextHarmony(files: MidiCorpusFile[], agentIds: string[], currentPath?: string) {
|
||||
const candidates = shuffle(files.filter((file) => file.path !== currentPath), Date.now());
|
||||
for (const file of candidates.slice(0, 50)) {
|
||||
try {
|
||||
const source = await loadHarmonySource(file);
|
||||
return { frame: createHarmonyRuntime(source, agentIds).frame, source };
|
||||
} catch {
|
||||
// Keep shuffling; bad files do not get to be the main character.
|
||||
}
|
||||
}
|
||||
throw new Error("no alternate parseable MIDI file found");
|
||||
}
|
||||
|
||||
export async function pickHarmonyFolder(agentIds: string[]) {
|
||||
const picker = (window as any).showDirectoryPicker as undefined | (() => Promise<FileSystemDirectoryHandle>);
|
||||
if (!picker) {
|
||||
throw new Error("this browser does not expose a folder picker; use the Vite default corpus endpoint");
|
||||
}
|
||||
const root = await picker();
|
||||
const files: MidiCorpusFile[] = [];
|
||||
await collectHandleMidiFiles(root, files);
|
||||
const loaded = await loadFromFileHandles(files, agentIds);
|
||||
return { files, ...loaded };
|
||||
}
|
||||
|
||||
export function createHarmonyRuntime(source: HarmonySource, agentIds: string[]): HarmonyRuntime {
|
||||
const salient = [...source.chords].sort((a, b) => b.salience - a.salience);
|
||||
let state = salient[0] ?? source.chords[0];
|
||||
let step = 0;
|
||||
const next = () => {
|
||||
const options = source.markov.get(state.key) ?? salient.slice(0, 5).map((chord) => chord.key);
|
||||
const nextKey = options[(step * 7 + state.key.length) % Math.max(options.length, 1)];
|
||||
state = source.chords.find((chord) => chord.key === nextKey) ?? salient[(step + 1) % Math.max(salient.length, 1)] ?? state;
|
||||
step += 1;
|
||||
return frameFromState(source, state, agentIds, step);
|
||||
};
|
||||
return { frame: frameFromState(source, state, agentIds, step), next };
|
||||
}
|
||||
|
||||
async function loadFromFileHandles(files: MidiCorpusFile[], agentIds: string[]) {
|
||||
for (const file of shuffle(files, Date.now()).slice(0, 40)) {
|
||||
const handle = (file as any).handle as FileSystemFileHandle | undefined;
|
||||
if (!handle) continue;
|
||||
try {
|
||||
const source = buildHarmonySource(file, await (await handle.getFile()).arrayBuffer());
|
||||
return { frame: createHarmonyRuntime(source, agentIds).frame, source };
|
||||
} catch {
|
||||
// Same fossil policy, now with permissions.
|
||||
}
|
||||
}
|
||||
throw new Error("selected folder did not contain a parseable MIDI harmony source");
|
||||
}
|
||||
|
||||
async function loadHarmonySource(file: MidiCorpusFile) {
|
||||
const response = await fetch(`/midi-corpus/file?path=${encodeURIComponent(file.path)}`, { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`MIDI fetch failed: ${response.status}`);
|
||||
return buildHarmonySource(file, await response.arrayBuffer());
|
||||
}
|
||||
|
||||
function buildHarmonySource(file: MidiCorpusFile, buffer: ArrayBuffer): HarmonySource {
|
||||
const midi = parseMidi(new Uint8Array(buffer));
|
||||
const ticksPerBeat = midi.header.ticksPerBeat ?? midi.header.timeDivision ?? 480;
|
||||
const bucketSize = Math.max(1, ticksPerBeat * 2);
|
||||
const buckets = new Map<number, { low: number; notes: Map<number, number>; weight: number }>();
|
||||
const programs = new Map<number, number>();
|
||||
const transitions: string[] = [];
|
||||
|
||||
for (const track of midi.tracks) {
|
||||
let tick = 0;
|
||||
for (const event of track as any[]) {
|
||||
tick += event.deltaTime ?? 0;
|
||||
if (event.type === "programChange" && typeof event.programNumber === "number") {
|
||||
programs.set(event.programNumber, (programs.get(event.programNumber) ?? 0) + 1);
|
||||
}
|
||||
if (event.type !== "noteOn" || !event.velocity) continue;
|
||||
const bucketIndex = Math.round(tick / bucketSize);
|
||||
const bucket = buckets.get(bucketIndex) ?? { low: event.noteNumber, notes: new Map<number, number>(), weight: 0 };
|
||||
const pitchClass = event.noteNumber % 12;
|
||||
bucket.low = Math.min(bucket.low, event.noteNumber);
|
||||
bucket.notes.set(pitchClass, (bucket.notes.get(pitchClass) ?? 0) + event.velocity);
|
||||
bucket.weight += event.velocity;
|
||||
buckets.set(bucketIndex, bucket);
|
||||
}
|
||||
}
|
||||
|
||||
const statesByKey = new Map<string, ChordState>();
|
||||
const sortedBuckets = [...buckets.entries()].sort((a, b) => a[0] - b[0]);
|
||||
for (const [, bucket] of sortedBuckets) {
|
||||
const pcs = [...bucket.notes.entries()]
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 5)
|
||||
.map(([pitchClass]) => pitchClass)
|
||||
.sort((a, b) => a - b);
|
||||
if (pcs.length < 2) continue;
|
||||
const root = bucket.low % 12;
|
||||
const key = `${root}:${pcs.join(".")}`;
|
||||
const existing = statesByKey.get(key);
|
||||
if (existing) {
|
||||
existing.salience += bucket.weight;
|
||||
} else {
|
||||
statesByKey.set(key, { key, label: chordLabel(root, pcs), pitchClasses: pcs, salience: bucket.weight });
|
||||
}
|
||||
transitions.push(key);
|
||||
}
|
||||
|
||||
const markov = new Map<string, string[]>();
|
||||
for (let index = 0; index < transitions.length - 1; index += 1) {
|
||||
const current = transitions[index];
|
||||
const next = transitions[index + 1];
|
||||
const options = markov.get(current) ?? [];
|
||||
options.push(next);
|
||||
markov.set(current, options);
|
||||
}
|
||||
|
||||
const chords = [...statesByKey.values()]
|
||||
.filter((chord) => chord.salience > 0)
|
||||
.sort((a, b) => b.salience - a.salience)
|
||||
.slice(0, 96);
|
||||
if (chords.length < 3) throw new Error("not enough chord material");
|
||||
|
||||
const instruments = [...programs.entries()]
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([program, count]) => ({ count, name: gmProgramNames[program] ?? `Program ${program + 1}`, program }))
|
||||
.slice(0, 16);
|
||||
|
||||
return {
|
||||
chords,
|
||||
filesSeen: 1,
|
||||
instruments: instruments.length ? instruments : [{ count: 1, name: "Acoustic Grand Piano", program: 0 }],
|
||||
markov,
|
||||
sourceName: file.relativePath || file.name,
|
||||
sourcePath: file.path,
|
||||
};
|
||||
}
|
||||
|
||||
function frameFromState(source: HarmonySource, chord: ChordState, agentIds: string[], step: number): AquariumHarmonyFrame {
|
||||
const agentVoices: Record<string, AgentHarmonyVoice> = {};
|
||||
agentIds.forEach((id, index) => {
|
||||
const pitchClass = chord.pitchClasses[index % chord.pitchClasses.length];
|
||||
const octave = 3 + ((index + Math.floor(step / 2)) % 3);
|
||||
const midi = nearestMidiForPitchClass(12 * octave + 12, pitchClass, index);
|
||||
const instrument = source.instruments[index % source.instruments.length];
|
||||
agentVoices[id] = {
|
||||
chordDegree: index % chord.pitchClasses.length,
|
||||
frequency: midiToFrequency(midi),
|
||||
instrument: instrument.name,
|
||||
midi,
|
||||
program: instrument.program,
|
||||
};
|
||||
});
|
||||
return {
|
||||
agentVoices,
|
||||
chordLabel: chord.label,
|
||||
corpusLabel: defaultCorpusLabel,
|
||||
sourceName: source.sourceName,
|
||||
sourcePath: source.sourcePath,
|
||||
};
|
||||
}
|
||||
|
||||
function nearestMidiForPitchClass(anchor: number, pitchClass: number, spread: number) {
|
||||
let midi = anchor + ((pitchClass - anchor) % 12 + 12) % 12;
|
||||
if (midi - anchor > 6) midi -= 12;
|
||||
return clampNumber(midi + Math.floor(spread / 3) * 12, 36, 84);
|
||||
}
|
||||
|
||||
function chordLabel(root: number, pitchClasses: number[]) {
|
||||
const intervals = pitchClasses.map((pc) => (pc - root + 12) % 12);
|
||||
const quality =
|
||||
intervals.includes(4) && intervals.includes(7) ? "" :
|
||||
intervals.includes(3) && intervals.includes(7) ? "m" :
|
||||
intervals.includes(3) && intervals.includes(6) ? "dim" :
|
||||
intervals.includes(4) && intervals.includes(8) ? "aug" :
|
||||
intervals.includes(5) ? "sus4" :
|
||||
intervals.includes(2) ? "sus2" :
|
||||
"";
|
||||
const extensions = [
|
||||
intervals.includes(10) ? "7" : "",
|
||||
intervals.includes(11) ? "maj7" : "",
|
||||
intervals.includes(2) && !quality.includes("sus2") ? "9" : "",
|
||||
].filter(Boolean).join(" ");
|
||||
return `${noteNames[root]}${quality}${extensions ? ` ${extensions}` : ""}`;
|
||||
}
|
||||
|
||||
function midiToFrequency(midi: number) {
|
||||
return 440 * 2 ** ((midi - 69) / 12);
|
||||
}
|
||||
|
||||
function shuffle<T>(items: T[], seed: number) {
|
||||
const next = mulberry32(seed >>> 0);
|
||||
const copy = [...items];
|
||||
for (let index = copy.length - 1; index > 0; index -= 1) {
|
||||
const swap = Math.floor(next() * (index + 1));
|
||||
[copy[index], copy[swap]] = [copy[swap], copy[index]];
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
function mulberry32(seed: number) {
|
||||
let state = seed || 0x9e3779b9;
|
||||
return () => {
|
||||
state += 0x6d2b79f5;
|
||||
let value = state;
|
||||
value = Math.imul(value ^ (value >>> 15), value | 1);
|
||||
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
|
||||
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function clampNumber(value: number, min: number, max: number) {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
async function fetchJson<T>(url: string): Promise<T> {
|
||||
const response = await fetch(url, { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`request failed ${response.status}: ${url}`);
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
async function collectHandleMidiFiles(directory: FileSystemDirectoryHandle, files: MidiCorpusFile[], prefix = "") {
|
||||
for await (const [name, handle] of (directory as any).entries() as AsyncIterable<[string, FileSystemHandle]>) {
|
||||
if (files.length >= 5000) return;
|
||||
const relativePath = prefix ? `${prefix}/${name}` : name;
|
||||
if (handle.kind === "directory") {
|
||||
await collectHandleMidiFiles(handle as FileSystemDirectoryHandle, files, relativePath);
|
||||
continue;
|
||||
}
|
||||
if (!/\.(mid|midi)$/i.test(name)) continue;
|
||||
const file = await (handle as FileSystemFileHandle).getFile();
|
||||
files.push({
|
||||
name,
|
||||
path: relativePath,
|
||||
relativePath,
|
||||
size: file.size,
|
||||
...( { handle } as any ),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -532,6 +532,82 @@ body:has(.immersiveShell) {
|
|||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
.playlistControl {
|
||||
position: relative;
|
||||
min-width: 172px;
|
||||
color: rgba(244, 255, 245, 0.86);
|
||||
}
|
||||
|
||||
.playlistControl summary {
|
||||
display: grid;
|
||||
gap: 1px;
|
||||
min-height: 40px;
|
||||
border: 1px solid rgba(247, 189, 88, 0.42);
|
||||
border-radius: 999px;
|
||||
padding: 5px 14px;
|
||||
background: rgba(10, 19, 16, 0.72);
|
||||
box-shadow: 0 0 18px rgba(247, 189, 88, 0.12);
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.playlistControl summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.playlistControl summary span {
|
||||
color: rgba(247, 189, 88, 0.82);
|
||||
font-size: 0.62rem;
|
||||
font-weight: 800;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.playlistControl summary strong {
|
||||
font-size: 0.82rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.playlistBody {
|
||||
position: absolute;
|
||||
top: calc(100% + 8px);
|
||||
right: 0;
|
||||
width: min(420px, 72vw);
|
||||
border: 1px solid rgba(247, 189, 88, 0.28);
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
background: rgba(8, 14, 12, 0.92);
|
||||
box-shadow: 0 20px 46px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
.playlistBody p {
|
||||
margin: 0 0 8px;
|
||||
color: rgba(244, 255, 245, 0.74);
|
||||
font-size: 0.74rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.playlistButtons {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.playlistButtons button {
|
||||
flex: 1;
|
||||
min-height: 32px;
|
||||
border: 1px solid rgba(219, 238, 216, 0.28);
|
||||
border-radius: 999px;
|
||||
color: rgba(244, 255, 245, 0.84);
|
||||
background: rgba(36, 77, 58, 0.72);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.playlistButtons button:disabled {
|
||||
opacity: 0.42;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.deckRail {
|
||||
top: 152px;
|
||||
bottom: 24px;
|
||||
|
|
|
|||
|
|
@ -1,8 +1,14 @@
|
|||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { readdir, readFile, stat } from "node:fs/promises";
|
||||
import { extname, join, relative } from "node:path";
|
||||
|
||||
const defaultMidiCorpus =
|
||||
"D:\\Documents\\130000_Pop_Rock_Classical_Videogame_EDM_MIDI_Archive[6_19_15]\\Classical_www.midiworld.com_MIDIRip";
|
||||
const midiFileLimit = 1000;
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
plugins: [react(), midiCorpusDevPlugin()],
|
||||
clearScreen: false,
|
||||
server: {
|
||||
host: "127.0.0.1",
|
||||
|
|
@ -11,3 +17,70 @@ export default defineConfig({
|
|||
},
|
||||
envPrefix: ["VITE_", "TAURI_"],
|
||||
});
|
||||
|
||||
function midiCorpusDevPlugin() {
|
||||
return {
|
||||
name: "epiphany-midi-corpus-dev",
|
||||
configureServer(server: any) {
|
||||
server.middlewares.use("/midi-corpus/list", async (request: any, response: any) => {
|
||||
try {
|
||||
const url = new URL(request.url ?? "", "http://127.0.0.1");
|
||||
const root = url.searchParams.get("root") || defaultMidiCorpus;
|
||||
const files = await listMidiFiles(root);
|
||||
writeJson(response, { root, files });
|
||||
} catch (error) {
|
||||
writeJson(response, { error: error instanceof Error ? error.message : String(error) }, 500);
|
||||
}
|
||||
});
|
||||
server.middlewares.use("/midi-corpus/file", async (request: any, response: any) => {
|
||||
try {
|
||||
const url = new URL(request.url ?? "", "http://127.0.0.1");
|
||||
const path = url.searchParams.get("path");
|
||||
if (!path) {
|
||||
writeJson(response, { error: "missing MIDI path" }, 400);
|
||||
return;
|
||||
}
|
||||
const data = await readFile(path);
|
||||
response.statusCode = 200;
|
||||
response.setHeader("content-type", "audio/midi");
|
||||
response.end(data);
|
||||
} catch (error) {
|
||||
writeJson(response, { error: error instanceof Error ? error.message : String(error) }, 500);
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function listMidiFiles(root: string) {
|
||||
const files: Array<{ name: string; path: string; relativePath: string; size: number }> = [];
|
||||
async function visit(directory: string) {
|
||||
if (files.length >= midiFileLimit) return;
|
||||
const entries = await readdir(directory, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
if (files.length >= midiFileLimit) break;
|
||||
const path = join(directory, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
await visit(path);
|
||||
continue;
|
||||
}
|
||||
const extension = extname(entry.name).toLowerCase();
|
||||
if (extension !== ".mid" && extension !== ".midi") continue;
|
||||
const metadata = await stat(path);
|
||||
files.push({
|
||||
name: entry.name,
|
||||
path,
|
||||
relativePath: relative(root, path),
|
||||
size: metadata.size,
|
||||
});
|
||||
}
|
||||
}
|
||||
await visit(root);
|
||||
return files;
|
||||
}
|
||||
|
||||
function writeJson(response: any, payload: unknown, status = 200) {
|
||||
response.statusCode = status;
|
||||
response.setHeader("content-type", "application/json");
|
||||
response.end(JSON.stringify(payload));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -71,3 +71,4 @@
|
|||
{"ts": "2026-05-04T22:47:52+00:00", "type": "implementation", "status": "ok", "note": "Specialist self-memory persistence landed as Ghostlight-shaped role dossiers under state/agents plus a bounded selfPatch review surface in roleResult/roleAccept. Good mutations are role-matched, bounded, evidence-grounded lane memory/goal/value/private-note updates; project truth, authority, code edits, graphs, checkpoints, planning, scratch, jobs, and raw transcripts are refused with reasons. GUI/coordinator accept paths apply accepted selfPatch requests through tools/epiphany_agent_memory.py."}
|
||||
{"ts": "2026-05-05T09:38:42+00:00", "type": "implementation", "status": "ok", "note": "Perfect Machine GUI audio pass cut the muted legacy WebAudio voice layer from the aquarium dashboard. Agent sound now flows through the buffered spectral vocal path only: projected agents update vocal bins, bounded status/touch events enqueue chirplet-driven vocal bursts, and the visual smoke probe checks vocalAgentCount plus reactiveFlushes instead of fake partial/hum counters."}
|
||||
{"ts": "2026-05-05T09:56:04+00:00", "type": "implementation", "status": "ok", "note": "Aquarium audio transient pass landed: interaction bursts now take priority over idle bins, carry per-sample GPU/CPU envelope shapes, fan out across a staggered 7-agent choir, and reduce idle vocal bins to a quiet residual. Visual smoke now requires lastBurstChoirVoices and transientBins so future changes cannot silently regress back to a constant drone."}
|
||||
{"ts": "2026-05-05T10:17:02+00:00", "type": "implementation", "status": "ok", "note": "Aquarium harmony pass landed: GUI audio now extracts chord/progression states and available General MIDI instruments from shuffled classical MIDI files, assigns chord-tone pitches/instruments to agents, and exposes a small playlist control for current file, shuffle, and folder selection. The Vite dev endpoint serves the default Classical MIDIRip archive; the browser folder picker supports alternate corpora. Build, visual smoke, and a deferred playlist-load probe passed."}
|
||||
|
|
|
|||
Reference in a new issue