AI media harness for planning, generating, and editing locally
TypeScript
Add sound references to the References view
Bitti318b7206b7e6
diff --git a/src/components/workspace/ReferenceAudio.tsx b/src/components/workspace/ReferenceAudio.tsxnew file mode 100644index 0000000..66e788e--- /dev/null+++ b/src/components/workspace/ReferenceAudio.tsx@@ -0,0 +1,80 @@+import { Pause14, Play14 } from "../ui/icons";+import { useEffect, useRef, useState } from "react";+import { PropRow } from "../ui";+import { readMediaFileUrl } from "../../lib/persistence";+import type { ProjectReference } from "../../lib/project";+import { editReferenceVideoTrim, normalizeReferenceVideoTrim, referenceTime, MAX_REFERENCE_SECONDS, MIN_REFERENCE_SECONDS, type TrimAction } from "../../lib/referenceVideoTrim";+import { CommittedNumberInput } from "./CommittedNumberInput";++type AudioOptions = NonNullable<ProjectReference["audio"]>;++const AUDIO_TYPES: Record<string, string> = {+ mp3: "audio/mpeg", m4a: "audio/mp4", aac: "audio/mp4", wav: "audio/wav", flac: "audio/flac", ogg: "audio/ogg", oga: "audio/ogg",+};+const audioType = (path: string | null | undefined) => AUDIO_TYPES[path?.split(".").pop()?.toLowerCase() ?? ""] ?? "audio/mpeg";++/** The part of a sound file sent as a reference: 2 to 15 seconds of it. */+export function ReferenceAudio({ folderPath, reference, onChange }: { folderPath: string; reference: ProjectReference; onChange: (audio: AudioOptions) => void }) {+ const [url, setUrl] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [sourceDuration, setSourceDuration] = useState<number | null>(null);+ const [previewing, setPreviewing] = useState(false);+ const audio = useRef<HTMLAudioElement>(null);+ const location = reference.sourcePath ?? reference.relativePath;+ useEffect(() => {+ let disposed = false;+ let owned: string | null = null;+ setUrl(null); setError(null); setSourceDuration(null); setPreviewing(false);+ void readMediaFileUrl(folderPath, reference, audioType(location)).then((value) => {+ if (disposed) { if (value) URL.revokeObjectURL(value); return; }+ owned = value; setUrl(value);+ if (!value) setError("The sound file is unavailable.");+ }).catch((reason: unknown) => { if (!disposed) setError(String(reason)); });+ return () => { disposed = true; if (owned) URL.revokeObjectURL(owned); };+ }, [folderPath, reference.id, location]);++ const usable = sourceDuration !== null && sourceDuration >= MIN_REFERENCE_SECONDS;+ const trim = usable ? normalizeReferenceVideoTrim(reference.audio ?? { startSeconds: 0, durationSeconds: MAX_REFERENCE_SECONDS }, sourceDuration) : null;+ const start = trim?.startSeconds ?? reference.audio?.startSeconds ?? 0;+ const length = trim?.durationSeconds ?? reference.audio?.durationSeconds ?? MAX_REFERENCE_SECONDS;+ const change = (action: TrimAction, value: number) => {+ if (!trim || sourceDuration === null) return;+ const next = editReferenceVideoTrim(trim, sourceDuration, action, value);+ onChange({ startSeconds: next.startSeconds, durationSeconds: next.durationSeconds });+ };+ const stop = () => { audio.current?.pause(); setPreviewing(false); };+ const playSelection = async () => {+ const element = audio.current;+ if (!element || !trim) return;+ if (previewing) { stop(); return; }+ element.currentTime = start;+ setPreviewing(true);+ try { await element.play(); }+ catch (reason) { stop(); setError(`Could not play the selection: ${String(reason)}`); }+ };++ return <div className="reference-audio">+ {url && <audio ref={audio} src={url} controls preload="metadata" aria-label={`${reference.name} preview`}+ onLoadedMetadata={(event) => {+ const duration = event.currentTarget.duration;+ setSourceDuration(Number.isFinite(duration) ? duration : null);+ if (Number.isFinite(duration) && duration < MIN_REFERENCE_SECONDS) setError("Sound references must be at least 2 seconds long.");+ }}+ onTimeUpdate={(event) => { if (previewing && event.currentTarget.currentTime >= start + length) stop(); }}+ onPause={() => setPreviewing(false)}+ onError={() => setError("This sound file cannot be played in Slopus.")} />}+ <div className="reference-trim__summary"><strong>{referenceTime(start)} – {referenceTime(start + length)}</strong><span>{Number(length.toFixed(2))} s selected</span></div>+ <PropRow label="Start" htmlFor={`${reference.id}-audio-start`}>+ <CommittedNumberInput id={`${reference.id}-audio-start`} className="text-field" aria-label="Sound start in seconds" step={0.1} disabled={!trim}+ value={Number(start.toFixed(2))} minimum={0} maximum={Math.max(0, (sourceDuration ?? 0) - MIN_REFERENCE_SECONDS)} onCommit={(value) => change("move", value)} />+ </PropRow>+ <PropRow label="Length" htmlFor={`${reference.id}-audio-length`}>+ <CommittedNumberInput id={`${reference.id}-audio-length`} className="text-field" aria-label="Sound length in seconds" step={0.1} disabled={!trim}+ value={Number(length.toFixed(2))} minimum={MIN_REFERENCE_SECONDS} maximum={MAX_REFERENCE_SECONDS} onCommit={(value) => change("duration", value)} />+ </PropRow>+ <button type="button" className="secondary-button" disabled={!trim} onClick={() => void playSelection()}>+ {previewing ? <><Pause14 aria-hidden="true" /> Stop</> : <><Play14 aria-hidden="true" /> Play selection</>}+ </button>+ {error && <p role="alert">{error}</p>}+ </div>;+}diff --git a/src/components/workspace/ReferencesView.tsx b/src/components/workspace/ReferencesView.tsxindex 9892167..a42840e 100644--- a/src/components/workspace/ReferencesView.tsx+++ b/src/components/workspace/ReferencesView.tsx@@ -1,4 +1,4 @@-import { Add16, ArrowDown12, ArrowUp12, ChevronLeft16, ChevronRight16, CursorClick32, Delete14, Delete16, FolderOpen16, GridView16, GridView16Filled, ImageAdd14, ImageAdd16, Images32, ListView16, ListView16Filled, OpenExternal16, Refresh16, Refresh20, Rename16, Search16, TextFile14, TextFile16, TextFile24 } from "../ui/icons";+import { Add16, Audio22, ArrowDown12, ArrowUp12, ChevronLeft16, ChevronRight16, CursorClick32, Delete14, Delete16, FolderOpen16, GridView16, GridView16Filled, ImageAdd14, ImageAdd16, Images32, ListView16, ListView16Filled, OpenExternal16, Refresh16, Refresh20, Rename16, Search16, TextFile14, TextFile16, TextFile24 } from "../ui/icons";import { invoke } from "@tauri-apps/api/core";import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent, type MouseEvent } from "react";import { isReferenceDescribed, projectItemPath, referenceImages, type ProjectConfig, type ProjectReference, type ProjectReferenceImage } from "../../lib/project";@@ -29,9 +29,11 @@ import { ReferenceIconGenerationDialog } from "../ReferenceIconGenerationDialog"import { builtinIconRevision, refreshBuiltinIcons, subscribeBuiltinIcons } from "../../lib/builtinReferenceIcons";import { builtinIconVisitAction, saveBuiltinIconChoice } from "../../lib/referenceIconSettings";import { ReferenceVideo } from "./ReferenceVideo";+import { ReferenceAudio } from "./ReferenceAudio";import { ProjectStatus } from "./ProjectStatus";import { MediaThumbnail } from "./MediaThumbnail";import { inspectReferenceVideo } from "../../lib/referenceVideo";+import { inspectReferenceAudio } from "../../lib/referenceAudio";import { DebugPromptDialog } from "./DebugPromptDialog";import { referenceIconPrompt } from "../../lib/referenceIcons";import { loadDebugOptionsEnabled, subscribeDebugOptions } from "../../lib/settings";@@ -56,7 +58,7 @@ const referenceKindLabel = (reference: ProjectReference) => {/** The file a reference is made of, for "Show in File Explorer". */const referenceFile = (folderPath: string, reference: ProjectReference): string | null => {const image = referenceImages(reference)[0];- if (reference.kind === "video") return projectItemPath(folderPath, reference);+ if (reference.kind === "video" || reference.kind === "audio") return projectItemPath(folderPath, reference);if (image) return projectItemPath(folderPath, image);const refmod = reference.refmods?.[0];return refmod ? projectItemPath(folderPath, refmod) : null;@@ -272,14 +274,26 @@ export function ReferencesView({ config, folderPath, onChange, onRegenerateIcon,try {const files = imagesOnly? (await invoke<Array<{ name: string; relativePath: string }>>("choose_reference_images", { folderPath })).map((image) => ({ ...image, kind: "image" as const, sourcePath: null }))- : await invoke<Array<{ kind: "image" | "video" | "refmod"; name: string; relativePath?: string | null; sourcePath?: string | null }>>("choose_reference_files", { folderPath });+ : await invoke<Array<{ kind: "image" | "video" | "audio" | "refmod"; name: string; relativePath?: string | null; sourcePath?: string | null }>>("choose_reference_files", { folderPath });if (!files.length) return;+ // A sound is cited as <Audio N>, never as a subject, so pictures on the+ // same reference would have nothing to belong to.+ const sound = files.find((file) => file.kind === "audio");+ if (sound && (files.length > 1 || chosen.kind === "video" || referenceImages(chosen).length)) {+ throw new Error("Add a sound to its own reference, without images or a video.");+ }+ if (chosen.kind === "audio" && !sound) throw new Error("A sound reference can’t hold images or videos. Use another reference.");const clip = files.find((file) => file.kind === "video");const video = clip ? { startSeconds: 0, ...await inspectReferenceVideo(folderPath, clip.sourcePath!) } : undefined;+ const audio = sound ? await inspectReferenceAudio(folderPath, sound.sourcePath!) : undefined;const current = configRef.current;const target = current.references.find((reference) => reference.id === chosen.id);if (!target) throw new Error("The reference was removed while the files were importing.");if (target.refmods?.length) throw new Error("Remove the refmods before adding more files.");+ if (sound) {+ update(target.id, { kind: "audio", relativePath: null, sourcePath: sound.sourcePath, audio, video: undefined, images: [] });+ return;+ }const images: ProjectReferenceImage[] = files.filter((file) => file.kind === "image").map((file) => ({id: `ref-image-${crypto.randomUUID()}`, name: file.name, relativePath: file.relativePath, sourcePath: file.sourcePath,}));@@ -409,6 +423,8 @@ export function ReferencesView({ config, folderPath, onChange, onRegenerateIcon,asset={{ id: ref.id, kind: "video", name: ref.name, sourcePath: ref.sourcePath, relativePath: ref.relativePath, mimeType: "video/mp4", createdAt: ref.createdAt }}posterTimeSeconds={0}/></span>+ : ref.kind === "audio"+ ? <span className="reference-art reference-art--text"><Audio22 aria-hidden="true" /></span>: ref.refmods?.length && ref.iconRelativePath? <span className="reference-art reference-art--photo"><ReferenceImage folderPath={folderPath} relativePath={ref.iconRelativePath} alt={`${ref.name} icon`} /></span>: cover@@ -541,9 +557,17 @@ export function ReferencesView({ config, folderPath, onChange, onRegenerateIcon,<button className="secondary-button" onClick={() => update(selected.id, { kind: "text", sourcePath: null, relativePath: null, video: undefined, images: referenceImages(selected) })}><Delete16 aria-hidden="true" /> Remove video</button></section></PropSection>}+ {selected.kind === "audio" && <PropSection title="Sound clip" persistKey="references.audio">+ <section className="reference-video" aria-label="Sound reference">+ <ReferenceAudio key={`${selected.id}:${selected.sourcePath ?? selected.relativePath}`} folderPath={folderPath} reference={selected}+ onChange={(audio) => update(selected.id, { audio })} />+ <p>Needs a Ref2VA generator and an image or video reference in the same scene. Cite it in a shot to place it.</p>+ <button className="secondary-button" onClick={() => update(selected.id, { kind: "text", sourcePath: null, relativePath: null, audio: undefined })}><Delete16 aria-hidden="true" /> Remove sound</button>+ </section>+ </PropSection>}{/* The picture at a readable size, where the chip is only a glance:paging through the images, removing one. The header regenerates the icon. */}- {(selected.kind !== "video" || showImages || hasRefmods) && <PropSection+ {((selected.kind !== "video" && selected.kind !== "audio") || showImages || hasRefmods) && <PropSectiontitle="Preview"persistKey="references.preview"summary={showImages ? `${currentImagePage + 1} of ${selectedImages.length}` : undefined}@@ -592,6 +616,8 @@ export function ReferencesView({ config, folderPath, onChange, onRegenerateIcon,{hasRefmods ? <p>Remove the refmods to edit the prompt or add files.</p>: !isReferenceDescribed(selected) && <p>{isVideoReference(selected)? "The clip is sent as a reference. Add a prompt to describe what to keep."+ : selected.kind === "audio"+ ? "The sound is sent as a reference. Describe its role, such as the voice timbre for a character.": selectedImages.length > 0? "Not described yet — the picture is sent, but nothing tells the engine what to keep.": "Not described yet — it won’t be used until you add a definition."}</p>}diff --git a/src/lib/project.audio.test.ts b/src/lib/project.audio.test.tsnew file mode 100644index 0000000..ff75ff8--- /dev/null+++ b/src/lib/project.audio.test.ts@@ -0,0 +1,79 @@+import { expect, it } from "vitest";+import {+ audioReferenceBlocker, compileMiniMaxH3Prompt, compileScenePromptSegments, createDraftGenerationJob, danglingReferenceTokens, isReferenceUsable,+ projectReferenceSchema, referenceAudioNumbers, referenceToken, sceneGenerationSnapshot, usableAudioReferences, usableReferenceImages, type ProjectReference,+} from "./project";+import { referenceAudioPcm, referenceAudioRange } from "./referenceAudio";++const extension = { video: "mp4", audio: "wav", image: "png", text: "" } as const;+const reference = (id: string, kind: ProjectReference["kind"], description = ""): ProjectReference => ({+ id, kind, name: id, description, intendedUse: [], createdAt: "2026-10-03T00:00:00.000Z",+ ...(kind !== "text" ? { sourcePath: `C:/references/${id}.${extension[kind]}` } : {}),+ ...(kind === "audio" ? { audio: { startSeconds: 0, durationSeconds: 5 } } : {}),+});+const compile = (action: string, references: ProjectReference[]) =>+ compileScenePromptSegments({ shots: [{ id: "shot", startSeconds: 0, action, settings: null }] }, references).map((segment) => segment.value).join("");++it("numbers standalone sounds after enabled video soundtracks", () => {+ const withSound = { ...reference("talk", "video"), video: { startSeconds: 0, durationSeconds: 4, includeAudio: true } };+ const silent = { ...reference("walk", "video"), video: { startSeconds: 0, durationSeconds: 4, includeAudio: false } };+ const voice = reference("voice", "audio", "The voice timbre for the narrator");+ const references = [voice, withSound, silent];+ expect(isReferenceUsable(voice)).toBe(true);+ expect(usableAudioReferences(references).map((item) => item.id)).toEqual(["voice"]);+ expect(referenceAudioNumbers(references).get("voice")).toBe(2);+ expect(referenceAudioNumbers(references, false).get("voice")).toBe(1);+ const prompt = compile(`The narrator speaks in ${referenceToken("voice")}.`, references);+ expect(prompt).toContain("<Audio 2>: The voice timbre for the narrator.");+ expect(prompt).toContain("The narrator speaks in <Audio 2>.");+ expect(prompt).toContain("[reference generation + audio reference]");+ expect(prompt).toContain("<Audio 2>: reference - its audible characteristics guide the target audio without copying the original signal.");+ expect(prompt).not.toMatch(/<Subject \d> is the content shown in <Audio/);+});++it("defines an undescribed sound without inventing its role and keeps it out of subjects and pictures", () => {+ const references = [reference("hero", "image"), reference("ambience", "audio")];+ const prompt = compileMiniMaxH3Prompt("A walk through the market.", references);+ expect(prompt).toContain("<Subject 1> is the content shown in <Picture 1>.\n<Audio 1> is a reference audio clip.");+ expect(prompt).not.toContain("<Subject 2>");+ expect(usableReferenceImages(references)).toHaveLength(1);+});++it("lets shots cite sounds and blocks sounds without visual media", () => {+ const job = { ...createDraftGenerationJob("Scene"), referenceIds: ["voice"] };+ const voice = reference("voice", "audio");+ expect(danglingReferenceTokens([{ id: "shot", startSeconds: 0, action: referenceToken("voice") }], [voice])).toEqual([]);+ expect(audioReferenceBlocker(job, [voice])).toMatch(/image or video/);+ expect(audioReferenceBlocker({ ...job, usePreviousSceneLastFrame: true }, [voice])).toBeNull();+ expect(audioReferenceBlocker(job, [voice, reference("hero", "image")])).toBeNull();+ const sounds = ["a", "b", "c", "d"].map((id) => reference(id, "audio"));+ expect(audioReferenceBlocker(job, [reference("hero", "image"), ...sounds])).toMatch(/at most three/);+ expect(audioReferenceBlocker(job, [reference("hero", "image"), ...sounds.slice(0, 3).map((sound) => ({ ...sound, audio: { startSeconds: 0, durationSeconds: 6 } }))])).toMatch(/15 seconds/);+});++it("round trips sound options only on sound references", () => {+ const voice = reference("voice", "audio");+ expect(projectReferenceSchema.parse(JSON.parse(JSON.stringify(voice))).audio).toEqual(voice.audio);+ expect(projectReferenceSchema.safeParse({ ...voice, audio: { startSeconds: 0, durationSeconds: 1 } }).success).toBe(false);+ expect(projectReferenceSchema.safeParse({ ...reference("motion", "video"), audio: voice.audio }).success).toBe(false);+});++it("records sound ranges in generation snapshots without temporary handles", () => {+ const request = { prompt: "Talk", frames: 120, steps: 12, seed: 1, canvasWidth: 736, canvasHeight: 416, referencePaths: [],+ referenceAudios: [{ name: "Voice", sourcePath: "C:/voice.wav", startSeconds: 1, durationSeconds: 5 }], referenceAudioIds: ["temporary"] };+ const snapshot = JSON.parse(sceneGenerationSnapshot(createDraftGenerationJob("Talk"), request));+ expect(snapshot.referenceAudios).toEqual(request.referenceAudios);+ expect(snapshot.referenceAudioIds).toBeUndefined();+});++it("interleaves and clamps the selected sound range", () => {+ const left = Float32Array.from({ length: 400 }, (_, index) => index / 100);+ const right = Float32Array.from({ length: 400 }, () => -2);+ const buffer = { numberOfChannels: 2, sampleRate: 100, length: 400, duration: 4, getChannelData: (channel: number) => channel ? right : left } as unknown as AudioBuffer;+ const pcm = referenceAudioPcm(buffer, 0.5, 2);+ expect(pcm).toHaveLength(400);+ expect([pcm[0], pcm[1], pcm[2]]).toEqual([0.5, -1, 0.5099999904632568]);+ expect(pcm[398]).toBe(1);+ expect(() => referenceAudioPcm(buffer, 2.5, 2)).toThrow(/shorter than 2 seconds/);+ expect(() => referenceAudioRange({ name: "Voice", startSeconds: 3, durationSeconds: 2 }, 4)).toThrow(/beyond the end/);+});diff --git a/src/styles/references.css b/src/styles/references.cssindex ff3efa9..ac2e2fc 100644--- a/src/styles/references.css+++ b/src/styles/references.css@@ -588,6 +588,11 @@border-radius: var(--radius-sm);}+.reference-audio { display: grid; gap: var(--space-2); min-width: 0; }+.reference-audio audio { width: 100%; }+.reference-audio p { margin: 0; color: var(--text-muted); }+.reference-video > p { margin: 0; color: var(--text-muted); font-size: var(--text-xs); }+.reference-trim { display: grid; gap: var(--space-2); min-width: 0; }.reference-trim__summary { display: flex; flex-direction: column; gap: 4px; font-variant-numeric: tabular-nums; }.reference-trim__summary span, .reference-trim__ticks { color: var(--text-muted); font-size: var(--text-xs); }