AI media harness for planning, generating, and editing locally
TypeScript
Send sound references with scene generations
Bittib95d8550a730
diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsxindex 586dc16..bbbec82 100644--- a/src/components/workspace/GeneratorView.tsx+++ b/src/components/workspace/GeneratorView.tsx@@ -1,7 +1,7 @@import type { GenerationSubmission } from "../../lib/workQueue";import { loadLoras, subscribeLoras } from "../../lib/loras";import { refreshDownloadedLoras } from "../../lib/weightDownloads";-import { characterReplaceBlocker, poseBlocker, isVideoTransition, videoTransitionBlocker, usableVideoReferences, type SceneType } from "../../lib/project";+import { audioReferenceBlocker, characterReplaceBlocker, poseBlocker, isVideoTransition, videoTransitionBlocker, usableAudioReferences, usableVideoReferences, type SceneType } from "../../lib/project";import { referenceRefmodInputs } from "../../lib/project";import { Add16, Delete16, GridView16, GridView16Filled, ListView16, ListView16Filled, Scene16, Scene32, Sparkle16, Stop14, Wand16 } from "../ui/icons";import { invoke } from "@tauri-apps/api/core";@@ -362,6 +362,11 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCodurationSeconds: reference.video?.durationSeconds ?? 2,includeAudio: isVideoTransition(job) ? false : reference.video?.includeAudio ?? true,})),+ referenceAudios: usableAudioReferences(bound).map((reference) => ({+ name: reference.name, relativePath: reference.relativePath, sourcePath: reference.sourcePath,+ startSeconds: reference.audio?.startSeconds ?? 0,+ durationSeconds: reference.audio?.durationSeconds ?? 15,+ })),};};@@ -736,6 +741,10 @@ function sendBlocker(job: GenerationJob, references: ProjectReference[]): stringif (job.usePreviousSceneLastFrame || bound.some((reference) => reference.refmods?.some((refmod) => refmod.strength > 0))) {return "Animate can’t continue a scene or use refmods.";}+ if (usableAudioReferences(bound).length) return "Animate can’t use sound references.";+ } else {+ const blocker = audioReferenceBlocker(job, sceneGenerationReferences(job, references));+ if (blocker) return blocker;}if (!animate && !characterReplace && shots.every((shot) => shot.action.trim().length === 0 && !(shot.speech ?? "").trim())) {return "Write a description or speech in at least one shot.";diff --git a/src/components/workspace/SceneEditor.tsx b/src/components/workspace/SceneEditor.tsxindex 795ba3f..02598ec 100644--- a/src/components/workspace/SceneEditor.tsx+++ b/src/components/workspace/SceneEditor.tsx@@ -1,9 +1,10 @@-import { Dismiss12, Image16, ImageAdd16, Text16, Video16 } from "../ui/icons";+import { Audio16, Dismiss12, Image16, ImageAdd16, Text16, Video16 } from "../ui/icons";import { useId, useMemo, useState, type ReactNode } from "react";import { ComboBox, InfoBar, PropRow, PropSection } from "../ui";import {actionReferenceIds,danglingReferenceTokens,+ isAudioReference,isReferenceUsable,isVisualReference,isVideoReference,@@ -51,7 +52,7 @@ const seconds = (value: number): string => `${value.toFixed(1)}s`;/** Everything that COULD be cited: the same filter pair the compiler applies,* over the whole project. See the lockstep note on `usableImageReferences`. */export const citableReferences = (references: readonly ProjectReference[]): ProjectReference[] =>- references.filter((reference) => isReferenceUsable(reference) && isVisualReference(reference));+ references.filter((reference) => isReferenceUsable(reference) && (isVisualReference(reference) || isAudioReference(reference)));/** The reference ids of a scene in the order it NUMBERS them, which is the* order the compiler numbers them in: project order, filtered by what this@@ -130,7 +131,7 @@ export function ShotInspector({ job, shots, shot, index, endsAt, duration, referconst number = numbered.findIndex((item) => item.id === reference.id) + 1;return {id: reference.id, name: reference.name, detail: `${number > 0 ? `Reference ${number}` : "Not in this scene yet"} · ${referenceTypeLabel(reference)}`,- icon: <ReferenceIcon reference={reference} folderPath={folderPath} fallback={isVideoReference(reference) ? <Video16 /> : referenceImages(reference).length ? <Image16 /> : <Text16 />} />,+ icon: <ReferenceIcon reference={reference} folderPath={folderPath} fallback={isVideoReference(reference) ? <Video16 /> : reference.kind === "audio" ? <Audio16 /> : referenceImages(reference).length ? <Image16 /> : <Text16 />} />,};}), [citable, numbered, folderPath]);const dangling = useMemo(() => danglingReferenceTokens(shots, references), [shots, references]);diff --git a/src/lib/project.ts b/src/lib/project.tsindex 82bdeff..7809455 100644--- a/src/lib/project.ts+++ b/src/lib/project.ts@@ -332,6 +332,10 @@ export const projectReferenceSchema = z.object({durationSeconds: z.number().finite().min(2).max(15),includeAudio: z.boolean(),}).optional(),+ audio: z.object({+ startSeconds: z.number().finite().min(0),+ durationSeconds: z.number().finite().min(2).max(15),+ }).optional(),intendedUse: z.array(z.enum(["character", "animal", "clothing", "accessory", "product", "location", "style", "audio"])).default([]),subcategory: z.string().optional(),// Generated library artwork is not an image conditioning attachment.@@ -342,6 +346,9 @@ export const projectReferenceSchema = z.object({if (reference.video && reference.kind !== "video") {context.addIssue({ code: z.ZodIssueCode.custom, path: ["video"], message: "Clip settings require a video reference." });}+ if (reference.audio && reference.kind !== "audio") {+ context.addIssue({ code: z.ZodIssueCode.custom, path: ["audio"], message: "Sound settings require a sound reference." });+ }const imageIds = new Set<string>();const refmodIds = new Set<string>();for (const refmod of reference.refmods ?? []) {@@ -732,7 +739,12 @@ export function isReferenceDescribed(reference: ProjectReference): boolean {* An image qualifies on its file alone: it can be sent to the engine and cited* as <Picture N> with nothing written about it. */export function isReferenceUsable(reference: ProjectReference): boolean {- return referenceImages(reference).length > 0 || (isVideoReference(reference) && Boolean(reference.sourcePath || reference.relativePath)) || activeReferenceRefmods(reference).length > 0 || isReferenceDescribed(reference);+ return referenceImages(reference).length > 0 || (isVideoReference(reference) && Boolean(reference.sourcePath || reference.relativePath)) || isAudioReference(reference) || activeReferenceRefmods(reference).length > 0 || isReferenceDescribed(reference);+}++/** A standalone sound file. It is cited as <Audio N>, never as a subject. */+export function isAudioReference(reference: ProjectReference): boolean {+ return reference.kind === "audio" && Boolean(reference.sourcePath || reference.relativePath);}export const activeReferenceRefmods = (reference: ProjectReference): ProjectReferenceRefmod[] =>@@ -758,13 +770,15 @@ export const referenceRefmodInputs = (folderPath: string, references: ProjectRef* no tag at all, is visible content as before. *//** The kind a picker names a reference by. A refmod reference steers the* model with its encoded conditioning, whatever else it holds. */-export function referenceTypeLabel(reference: ProjectReference): "Refmod" | "Video" | "Image" | "Text" {+export function referenceTypeLabel(reference: ProjectReference): "Refmod" | "Video" | "Audio" | "Image" | "Text" {if (reference.refmods?.length) return "Refmod";if (isVideoReference(reference)) return "Video";+ if (reference.kind === "audio") return "Audio";return reference.kind === "image" || referenceImages(reference).length ? "Image" : "Text";}export function isVisualReference(reference: ProjectReference): boolean {+ if (reference.kind === "audio") return false;return reference.kind === "video" || reference.intendedUse.length === 0 || reference.intendedUse.some((use) => use !== "audio");}@@ -865,6 +879,31 @@ export function usableVideoReferences(references: ProjectReference[]): ProjectRereturn references.filter((reference) => isVideoReference(reference) && Boolean(reference.sourcePath || reference.relativePath)).filter(isVisualReference);}+/** Standalone sounds, in the order SlopFab receives them: after every video. */+export function usableAudioReferences(references: ProjectReference[]): ProjectReference[] {+ return references.filter(isAudioReference);+}++/** SlopFab gives video soundtracks and standalone sounds one shared <Audio N>+ * counter in insertion order. Videos are attached first, so their enabled+ * soundtracks take the low numbers and standalone sounds follow. */+export function referenceAudioNumbers(references: ProjectReference[], soundtracks = true): Map<string, number> {+ const tracks = soundtracks ? usableVideoReferences(references).filter((reference) => reference.video?.includeAudio ?? true).length : 0;+ return new Map(usableAudioReferences(references).map((reference, index) => [reference.id, tracks + index + 1]));+}++/** Standalone sounds condition the target audio only alongside a picture,+ * a video, a refmod or a continued scene; SlopFab refuses them otherwise. */+export function audioReferenceBlocker(job: GenerationJob, bound: ProjectReference[]): string | null {+ const sounds = usableAudioReferences(bound);+ if (!sounds.length) return null;+ if (sounds.length > 3) return "Use at most three sound references per scene.";+ if (sounds.reduce((total, reference) => total + (reference.audio?.durationSeconds ?? 15), 0) > 15) return "Sound references must total no more than 15 seconds. Shorten them in References.";+ const anchored = usableReferenceImages(bound).length > 0 || usableVideoReferences(bound).length > 0+ || bound.some((reference) => activeReferenceRefmods(reference).length > 0) || Boolean(job.usePreviousSceneLastFrame);+ return anchored ? null : "Sound references need an image or video reference in the same scene.";+}+/** Opening and closing pictures come first, then bound references in project* order. Frame anchors use their first image, even on a multi-image reference;* the same anchor selected for both ends is sent only once. */@@ -1003,6 +1042,7 @@ export interface SceneGenerationInput {canvasHeight: number;referencePaths: readonly string[];referenceVideos?: readonly { name: string; relativePath?: string | null; sourcePath?: string | null; startSeconds: number; durationSeconds?: number; includeAudio: boolean }[];+ referenceAudios?: readonly { name: string; relativePath?: string | null; sourcePath?: string | null; startSeconds: number; durationSeconds: number }[];refmods?: readonly { path: string; strength: number; copies: number }[];previousSceneId?: string;continuationRelativePath?: string;@@ -1028,6 +1068,7 @@ export function sceneGenerationSnapshot(job: GenerationJob, input: SceneGeneraticanvasHeight: input.canvasHeight,referencePaths: input.referencePaths,...(input.referenceVideos?.length ? { referenceVideos: input.referenceVideos } : {}),+ ...(input.referenceAudios?.length ? { referenceAudios: input.referenceAudios } : {}),...(input.refmods?.length ? { refmods: input.refmods } : {}),...(input.previousSceneId ? { previousSceneId: input.previousSceneId } : {}),...(input.continuationRelativePath ? { continuationRelativePath: input.continuationRelativePath } : {}),@@ -1198,6 +1239,8 @@ export function compileScenePromptSegments(scene: ScenePrompt, references: Projeconst endFrame = references.find((reference) => reference.id === scene.endFrameReferenceId && referenceImages(reference).length > 0 && isReferenceUsable(reference)) ?? null;const usable = references.filter(isReferenceUsable).filter(isVisualReference).filter((reference) => reference.id !== startFrame?.id && reference.id !== endFrame?.id);const subjectNumber = new Map(usable.map((reference, index) => [reference.id, index + 1]));+ const sounds = usableAudioReferences(references);+ const audioNumber = referenceAudioNumbers(references, !scene.videoTransition);const compiled: CompiledShot[] = shots.map((shot, index) => {const body: PromptSegment[] = [];@@ -1212,6 +1255,12 @@ export function compileScenePromptSegments(scene: ScenePrompt, references: Proje// A token whose reference is gone, undescribed or tagged as sound only// has no <Subject N> to become. It is left out rather than guessed at,// and the editor says so in words above the field — see `danglingTokens`.+ const sound = audioNumber.get(part.value);+ if (sound) {+ body.push(frame(`<Audio ${sound}>`));+ text += `<Audio ${sound}>`;+ continue;+ }const number = subjectNumber.get(part.value);if (!number) continue;if (!citedIds.includes(part.value)) citedIds.push(part.value);@@ -1274,7 +1323,7 @@ export function compileScenePromptSegments(scene: ScenePrompt, references: Projeconst soundSegment = sound ? own(sound) : frame(DEFAULT_SOUNDSCAPE);const musicSegment = music ? own(music) : frame(DEFAULT_MUSIC);- if (usable.length === 0 && !startFrame && !endFrame) {+ if (usable.length === 0 && sounds.length === 0 && !startFrame && !endFrame) {// T2VA — base guide §2.2 field list and order.return [frame("integrated_multimodal_description: "),@@ -1319,7 +1368,7 @@ export function compileScenePromptSegments(scene: ScenePrompt, references: Proje// present an app-generated string to the model as the user's own words.// An image with no definition still belongs in the prompt — the picture is// real payload — so it is cited without any claim about what it contains.- const definitions = usable.flatMap((reference, index): PromptSegment[] => {+ const subjectDefinitions = usable.flatMap((reference, index): PromptSegment[] => {const detail = referenceDefinition(reference).replace(/\s+/g, " ");const pictures = pictureNumbers.get(reference.id) ?? [];const video = videoNumbers.get(reference.id);@@ -1338,6 +1387,16 @@ export function compileScenePromptSegments(scene: ScenePrompt, references: Proje...(detail ? [frame(" "), own(detail), ...addedStop(detail)] : []),];});+ // Ref guide §2.4: a sound is its own <Audio N> item, defined by its role.+ // Only the user knows that role, so without a description the line says no+ // more than that the clip exists.+ const audioDefinitions = sounds.flatMap((reference, index): PromptSegment[] => {+ const detail = referenceDefinition(reference).replace(/\s+/g, " ");+ const label = `<Audio ${audioNumber.get(reference.id)}>`;+ const lead = usable.length + index === 0 ? "" : "\n";+ return detail ? [frame(`${lead}${label}: `), own(detail), ...addedStop(detail)] : [frame(`${lead}${label} is a reference audio clip.`)];+ });+ const definitions = [...subjectDefinitions, ...audioDefinitions];const startPicture = startFrame ? pictureNumbers.get(startFrame.id)?.[0] ?? null : null;const endPicture = endFrame ? pictureNumbers.get(endFrame.id)?.[0] ?? null : null;const startDefinition = startPicture@@ -1365,9 +1424,11 @@ export function compileScenePromptSegments(scene: ScenePrompt, references: Proje// §3: task-type prefix. Subject references provide generation guidance; an// optional opening picture additionally anchors the first frame. The summary// reuses existing labels only and carries the user's lines through in order.+ // §3: a sound that is referenced rather than copied adds `audio reference`.+ const audioTask = sounds.length ? " + audio reference" : "";const summary: PromptSegment[] = [frame(scene.videoTransition === "extend" ? "[video continuation] Continue from the final frame of <Video 1>. "- : scene.videoTransition === "bridge" ? "[video continuation + reference generation] Generate the missing segment after <Video 1> and before <Video 2>. " : "[reference generation] "),+ : scene.videoTransition === "bridge" ? "[video continuation + reference generation] Generate the missing segment after <Video 1> and before <Video 2>. " : `[reference generation${audioTask}] `),...(poseDirection ? [frame(poseDirection)] : []),...compiled.flatMap((shot) => [...(shot.index === 0 ? [] : [frame(" ")]),@@ -1396,6 +1457,9 @@ export function compileScenePromptSegments(scene: ScenePrompt, references: Projeconst where = appearances.length > 0 ? ` (appears in ${appearances.join(", ")})` : "";return `${referenceLabel(reference, index)}${where}: fully_preserved - the referenced characteristics are retained.`;});+ // §4.2: `reference`, not a copy marker. The clip guides the target sound;+ // copying a signal 1:1 would need the user to say which layer and where.+ retention.push(...sounds.map((reference) => `<Audio ${audioNumber.get(reference.id)}>: reference - its audible characteristics guide the target audio without copying the original signal.`));if (startPicture) retention.unshift(`<Picture ${startPicture}>: first_frame - used as the opening frame.`);if (endPicture) retention.push(`<Picture ${endPicture}>: last_frame - used as the closing frame.`);@@ -1452,7 +1516,7 @@ export function compileScenePromptSegments(scene: ScenePrompt, references: Proje* left OUT of the compiled prompt, so the editor has to say which ones and* why, and sending is blocked until they are re-pointed or removed. */export function danglingReferenceTokens(shots: readonly SceneShot[], references: ProjectReference[]): string[] {- const usable = new Set(references.filter(isReferenceUsable).filter(isVisualReference).map((reference) => reference.id));+ const usable = new Set(references.filter(isReferenceUsable).filter((reference) => isVisualReference(reference) || isAudioReference(reference)).map((reference) => reference.id));const missing: string[] = [];for (const shot of shots) {for (const id of actionReferenceIds(shot.action)) {diff --git a/src/lib/referenceAudio.ts b/src/lib/referenceAudio.tsnew file mode 100644index 0000000..c62ea97--- /dev/null+++ b/src/lib/referenceAudio.ts@@ -0,0 +1,88 @@+import { invoke } from "@tauri-apps/api/core";+import { readMediaFileBytes } from "./persistence";+import type { SlopfabGenerationRequest } from "./runtime";++type AudioInput = NonNullable<SlopfabGenerationRequest["referenceAudios"]>[number];+const cancelledError = () => new Error("Sound reference preparation cancelled.");++export const MIN_REFERENCE_AUDIO_SECONDS = 2;+export const MAX_REFERENCE_AUDIO_SECONDS = 15;++/** The webview decodes; SlopFab takes interleaved float PCM and resamples it.+ * Surround sources are folded to stereo by the audio graph's standard downmix. */+export async function decodeReferenceAudio(bytes: ArrayBuffer): Promise<AudioBuffer> {+ const decoded = await new OfflineAudioContext(2, 1, 48_000).decodeAudioData(bytes.slice(0));+ if (decoded.numberOfChannels <= 2) return decoded;+ const context = new OfflineAudioContext(2, decoded.length, decoded.sampleRate);+ const source = context.createBufferSource();+ source.buffer = decoded;+ source.connect(context.destination);+ source.start();+ return context.startRendering();+}++export function referenceAudioRange(input: AudioInput, sourceDuration: number) {+ const { startSeconds: start, durationSeconds: duration } = input;+ if (!Number.isFinite(start) || start < 0 || !Number.isFinite(duration)+ || duration < MIN_REFERENCE_AUDIO_SECONDS || duration > MAX_REFERENCE_AUDIO_SECONDS) {+ throw new Error(`${input.name}: choose a sound clip lasting 2 to 15 seconds with a nonnegative start.`);+ }+ if (!Number.isFinite(sourceDuration) || start + duration > sourceDuration + 0.001) {+ throw new Error(`${input.name}: the selected range extends beyond the end of the sound file.`);+ }+ return { start, duration };+}++/** Interleaved samples of the selected range, clamped to SlopFab's [-1, 1]. */+export function referenceAudioPcm(buffer: AudioBuffer, start: number, duration: number): Float32Array {+ const channels = buffer.numberOfChannels;+ const offset = Math.round(start * buffer.sampleRate);+ const length = Math.min(Math.round(duration * buffer.sampleRate), buffer.length - offset);+ if (length < MIN_REFERENCE_AUDIO_SECONDS * buffer.sampleRate) throw new Error("The selected sound range is shorter than 2 seconds.");+ const pcm = new Float32Array(length * channels);+ for (let channel = 0; channel < channels; channel++) {+ const samples = buffer.getChannelData(channel);+ for (let index = 0; index < length; index++) {+ const value = samples[offset + index];+ pcm[index * channels + channel] = Number.isFinite(value) ? Math.max(-1, Math.min(1, value)) : 0;+ }+ }+ return pcm;+}++/** Clip options for a newly added sound: from the start, as long as allowed. */+export async function inspectReferenceAudio(folderPath: string, sourcePath: string) {+ const decoded = await decodeReferenceAudio(await readMediaFileBytes(folderPath, { sourcePath }));+ if (decoded.duration < MIN_REFERENCE_AUDIO_SECONDS) throw new Error("Sound references must be at least 2 seconds long.");+ return { startSeconds: 0, durationSeconds: Math.min(MAX_REFERENCE_AUDIO_SECONDS, Math.floor(decoded.duration * 100) / 100) };+}++export async function releaseReferenceAudios(ids: string[]) {+ if (ids.length) await invoke("release_reference_audios", { ids });+}++export async function prepareReferenceAudios(folderPath: string, request: SlopfabGenerationRequest, cancelled: () => boolean, report: (detail: string) => void): Promise<string[]> {+ const inputs = request.referenceAudios ?? [];+ if (inputs.length > 3) throw new Error("Use at most three sound references per generation.");+ const ids: string[] = [];+ let totalDuration = 0;+ try {+ for (const input of inputs) {+ if (cancelled()) throw cancelledError();+ report(`Preparing sound reference: ${input.name}`);+ const decoded = await decodeReferenceAudio(await readMediaFileBytes(folderPath, input));+ const { start, duration } = referenceAudioRange(input, decoded.duration);+ totalDuration += duration;+ if (totalDuration > MAX_REFERENCE_AUDIO_SECONDS + 1e-9) throw new Error("Sound references must total no more than 15 seconds. Shorten them in References.");+ const pcm = referenceAudioPcm(decoded, start, duration);+ if (cancelled()) throw cancelledError();+ ids.push(await invoke<string>("create_reference_audio", new Uint8Array(pcm.buffer), { headers: {+ "x-reference-channels": String(decoded.numberOfChannels), "x-reference-rate": String(decoded.sampleRate),+ } }));+ }+ return ids;+ } catch (error) {+ await releaseReferenceAudios(ids);+ throw error;+ }+}diff --git a/src/lib/runtime.ts b/src/lib/runtime.tsindex e39962f..e0aa484 100644--- a/src/lib/runtime.ts+++ b/src/lib/runtime.ts@@ -96,8 +96,10 @@ export interface SlopfabGenerationRequest {referencePaths: string[];refmods?: Array<{ path: string; strength: number; copies: number }>;referenceVideos?: Array<{ name: string; relativePath?: string | null; sourcePath?: string | null; startSeconds: number; durationSeconds?: number; includeAudio: boolean }>;+ referenceAudios?: Array<{ name: string; relativePath?: string | null; sourcePath?: string | null; startSeconds: number; durationSeconds: number }>;/** Temporary native handles, populated by the work queue and never saved. */referenceVideoIds?: string[];+ referenceAudioIds?: string[];/** Resolved by the app queue before native submission. */previousSceneId?: string;continuationRelativePath?: string;diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.tsindex d90ae79..278a63a 100644--- a/src/lib/workQueue.ts+++ b/src/lib/workQueue.ts@@ -20,6 +20,7 @@ import { remoteWorkerSelected } from "./workers";import { purgeTimelineThumbnails } from "./timelineThumbnails";import { ReferenceIconWork } from "./referenceIconWork";import { prepareReferenceVideos, releaseReferenceVideos } from "./referenceVideo";+import { prepareReferenceAudios, releaseReferenceAudios } from "./referenceAudio";export type WorkStatus = "queued" | "preparing" | "generating" | "encoding" | "completed" | "failed" | "cancelled";export interface GenerationSubmission { job: GenerationJob; request: SlopfabGenerationRequest; snapshot: string }@@ -293,6 +294,10 @@ export class WorkQueue {work.request.referenceVideoIds = await prepareReferenceVideos(next.folderPath, work.request, work.config,() => work.cancelled, (detail) => this.patch(work.id, { detail }));}+ if (work.request.referenceAudios?.length) {+ work.request.referenceAudioIds = await prepareReferenceAudios(next.folderPath, work.request,+ () => work.cancelled, (detail) => this.patch(work.id, { detail }));+ }if (work.cancelled) continue;const plan = await resolveSlopfabPlan(work.request, work.config, next.folderPath);if (work.cancelled) continue;@@ -307,6 +312,9 @@ export class WorkQueue {await releaseReferenceVideos(work.request.referenceVideoIds ?? []).catch((reason) =>writeDiagnostic("error", "work-queue", "references.release_failed", describeDiagnosticError(reason), { workId: work.id }));delete work.request.referenceVideoIds;+ await releaseReferenceAudios(work.request.referenceAudioIds ?? []).catch((reason) =>+ writeDiagnostic("error", "work-queue", "references.release_failed", describeDiagnosticError(reason), { workId: work.id }));+ delete work.request.referenceAudioIds;}}} finally { this.pumping = false; }